Created
January 15, 2022 00:42
-
-
Save yanandrey/8ec3f9261e186ec366cff98b87905645 to your computer and use it in GitHub Desktop.
JWT Authentication/Authorization
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static IServiceCollection AddTokensServices(this IServiceCollection services, IConfiguration configuration) | |
{ | |
var tokenConfig = new TokenConfiguration(); | |
new ConfigureFromConfigurationOptions<TokenConfiguration>(configuration | |
.GetSection("TokenConfiguration")) | |
.Configure(tokenConfig); | |
services.AddSingleton(tokenConfig); | |
services.AddAuthentication(x => | |
{ | |
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; | |
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; | |
}) | |
.AddJwtBearer(options => | |
{ | |
options.SaveToken = true; | |
options.TokenValidationParameters = new TokenValidationParameters | |
{ | |
ValidateIssuer = true, | |
ValidateAudience = true, | |
ValidateLifetime = true, | |
ValidateIssuerSigningKey = true, | |
ValidIssuer = tokenConfig.Issuer, | |
ValidAudience = tokenConfig.Audience, | |
ClockSkew = TimeSpan.Zero, | |
IssuerSigningKey = | |
new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenConfig.Secret)) | |
}; | |
}); | |
services.AddAuthorization(auth => | |
{ | |
auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder() | |
.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme) | |
.RequireAuthenticatedUser() | |
.Build()); | |
}); | |
return services; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public async Task<LoginResponseDTO> BuildJwtSecurityToken(User user) | |
{ | |
var bytes = Encoding.UTF8.GetBytes(_tokenConfig.Secret); | |
var key = new SymmetricSecurityKey(bytes); | |
var claims = new List<Claim> | |
{ | |
new(ClaimTypes.Name, user.Email) | |
}; | |
var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); | |
var token = new JwtSecurityToken( | |
_tokenConfig.Issuer, | |
_tokenConfig.Audience, | |
claims, | |
expires: DateTime.Now.AddMinutes(_tokenConfig.Minutes), | |
signingCredentials: credentials); | |
await _context.SaveChangesAsync(); | |
return new LoginResponseDTO | |
{ | |
AccessToken = new JwtSecurityTokenHandler().WriteToken(token), | |
RefreshToken = user.RefreshToken, | |
TokenExpirationDate = token.ValidTo.ToLocalTime().ToString(CultureInfo.InvariantCulture) | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment