NET Core 3.1 MVC Authorization/Authentication with token (JWT) obtained externally in separate Net Core 3.1 Web Api
Hey I have solution for this please refer below point
- first of all you need to add authentication.
public void ConfigureServices(IServiceCollection services)
services.AddSession();
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = >JwtBearerDefaults.AuthenticationScheme;
options.DefaultAuthenticateScheme = >JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
// Adding Jwt Bearer
.AddJwtBearer(options =>
{
options.SaveToken = true;
options.RequireHttpsMetadata = false;
options.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuer = true,
ValidateAudience = true,
ValidAudience = Configuration["JWTConfig:ValidAudience"],
ValidIssuer = Configuration["JWTConfig:ValidIssuer"],
IssuerSigningKey = new >SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JWTConfig:Secret"]))
};
});
- After that you have to Use Session for storing authentication token and in this token you have to encrypt token combination of role list whatever role want to pass for the authorization.
Here i have used JWT Bearer token
- Using this session you have to configure in
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
startup.cs file for use header authentication.
app.UseSession();
app.Use(async (context, next) =>
{
var token = context.Session.GetString("Token");
if (!string.IsNullOrEmpty(token))
{
context.Request.Headers.Add("Authorization", "Bearer " + token);
}
await next();
});
- then after you you have to add in your controller
[Authorize(Roles = "Employee,Student")]
public ActionResult Leave()
{
// your code here
}
.NET Core MVC and Web API two authentication schemes
Inside my JWT Token Generator, I get details of the user I would like to store as claims such as the username, which can be used to identify the user.
public static class JwtTokenExtensions
{
/// <summary>
/// Generates a JWT Bearer token containing the users email
/// </summary>
/// <param name="user"></param>
/// <returns></returns>
public static string GenerateJwtToken(this Identity user)
{
// Set our token claims
Claim[] claims = {
// Unique ID for this token
new(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString("N")),
new(JwtRegisteredClaimNames.Email, user.Email),
// The username using the Identity name so it fills out the HttpContext.User.Identity.Name value
new(ClaimsIdentity.DefaultNameClaimType, user.UserName),
// Add user Id so that UserManager.GetUserAsync can find the user based on Id
new Claim(ClaimTypes.NameIdentifier, user.Id)
};
// Create the credentials used to generate the token
SigningCredentials credentials =
new SigningCredentials(SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:SecretKey"])),
SecurityAlgorithms.HmacSha256);
// Generate the Jwt Token that lasts for an hour before expiring
JwtSecurityToken token =
new JwtSecurityToken
(Configuration["Jwt:Issuer"],
Configuration["Jwt:Audience"],
claims:claims,
signingCredentials:credentials,
expires: DateTime.Now.AddHours(1));
// Return the generated token.
return new JwtSecurityTokenHandler().WriteToken(token);
}
}
Inside the api controllers with JWT authorization, I can get the user via the HttpContextvar user = await _userManager.GetUserAsync(HttpContext.User);
Related Topics
How to Get My C# Program to Sleep for 50 Msec
What Is the Purpose of Anonymous { } Blocks in C Style Languages
HTML Table (Text) to Image Using C#
Handling Decimal Values in Newtonsoft.JSON
How to Use the Cancellationtoken Property
How to Override a Non-Virtual Method
How to De-Elevate Privileges for a Child Process
Raise Event in High Resolution Interval/Timer
How to Use Elmah to Manually Log Errors
Custom Method Names in ASP.NET Web API
How to Get Memcached Running on a Windows (X64) 64Bit Environment
How to Convert JavaScript Datetime to C# Datetime
Reading a File Used by Another Process