as I am new to the .Net Core, I am facing the following issue
I have Authentication_API that returns JWT Token to the login controller at client side. After successfull login, I want to redirect to Home page. But when I use [Autherize] attribute to the controller it is not working. But without [Autherize] attribute it is displaying the home page.
Please help me how to solve this issue.
I think I am not saving the token in the header.
I was referencing the below API for JWT ,
http://jasonwatmore.com/post/2019/01/08/aspnet-core-22-role-based-authorization-tutorial-with-example-api
Here is my token generator
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(_appSettings.Secret);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[]
{
new Claim(ClaimTypes.Name, user.UserId.ToString()),
new Claim(ClaimTypes.Role,user.Role.RoleNameE.ToString())
}),
Expires = DateTime.UtcNow.AddDays(7),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
var tokenString = tokenHandler.WriteToken(token);
After this point, I want to redirect to Home page
this is my Startup page
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddDbContext<Tejoury_MSContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DatabaseConnection")));
var appSettingsSection = Configuration.GetSection("AppSettings");
services.Configure<AppSettings>(appSettingsSection);
var appSettings = appSettingsSection.Get<AppSettings>();
var key = Encoding.ASCII.GetBytes(appSettings.Secret);
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(x =>
{
x.Events = new JwtBearerEvents
{
OnTokenValidated = context =>
{
var userService = context.HttpContext.RequestServices.GetRequiredService<IUserService>();
var userId = int.Parse(context.Principal.Identity.Name);
var user = userService.GetById(userId);
if (user == null)
{
context.Fail("Unauthorized");
}
return Task.CompletedTask;
}
};
x.RequireHttpsMetadata = false;
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false
};
});
services.AddScoped<IUserService, UserService>();
services.AddAuthorization(options =>
{
options.AddPolicy("RequireAdminRole",
authBuilder =>
{ authBuilder.RequireRole("Admin"); });
});
}
What I have tried:
I want to implement
JWT Authentication API in my client asp.net core applcaiton
this is the api I am using,
ASP.NET Core 2.2 - Role Based Authorization Tutorial with Example API | Jason Watmore's Blog[
^]