private void AddAuthentication(IServiceCollection services) { services.AddAuthentication(options => { options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = Configuration["Hosting:Domain"], ValidAudience = Configuration["Hosting:Domain"], IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JWT:Secret"])), LifetimeValidator = (before, expires, token, parameters) => { var now = DateTimeOffset.UtcNow; var res = expires > now; return(res); }, RoleClaimType = "ro", NameClaimType = "id", }; }); services.AddAuthorization(options => { options.AddPolicy("Admin", p => p.RequireAuthenticatedUser() .RequireRole(RoleParser.ToInt(Role.Admin).ToString())); }); }
public Token CreateLoginToken(User user, IPAddress ipAddress, string audience, string issuer, TimeSpan?lifespan = null) { if (!lifespan.HasValue) { lifespan = _defaultLifetime; } var exp = DateTimeOffset.UtcNow.Add(lifespan.Value); var claims = new Dictionary <string, object> { { CustomClaims.Role, RoleParser.ToInt(user.Role) }, { CustomClaims.Ip, ipAddress.ToString() }, { CustomClaims.Id, user.Id }, { "exp", exp.ToUnixTimeSeconds() } }; if (!string.IsNullOrEmpty(audience)) { claims.Add("aud", audience); } if (!string.IsNullOrEmpty(issuer)) { claims.Add("iss", issuer); } var tokenString = CreateToken(claims); return(new Token { Audience = audience, Claims = claims, Expires = exp, Issuer = issuer, Lifespan = lifespan, TokenString = tokenString }); }