public void Inject(IServiceCollection serviceCollection, IConfiguration configuration, IHostEnvironment env) { AuthOptions authConfig = configuration.GetSection("Auth").Get <AuthOptions>(); serviceCollection.AddScoped <IAuthDataProvider, AuthDataProvider>(); serviceCollection.AddScoped <ICurrentUserProvider, CurrentUserProvider>(); /* add identity */ serviceCollection.AddIdentity <User, IdentityRole <int> >(config => { config.Password.RequiredLength = 4; config.Password.RequireDigit = false; config.Password.RequireLowercase = false; config.Password.RequireNonAlphanumeric = false; config.Password.RequireUppercase = false; }) .AddUserManager <UserManager <User> >() .AddSignInManager <SignInManager <User> >() .AddEntityFrameworkStores <AppDbContext>(); /* jwt auth configure */ serviceCollection .AddAuthentication(opts => { opts.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; opts.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; opts.DefaultSignInScheme = JwtBearerDefaults.AuthenticationScheme; opts.DefaultSignOutScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(options => { options.Events = new JwtBearerEvents { OnForbidden = context => { context.Response.StatusCode = StatusCodes.Status403Forbidden; return(Task.CompletedTask); }, OnAuthenticationFailed = context => { context.Response.StatusCode = StatusCodes.Status401Unauthorized; return(Task.CompletedTask); } }; options.SaveToken = true; options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = authConfig.ISSUER, ValidAudience = authConfig.AUDIENCE, IssuerSigningKey = authConfig.GetSymmetricAlgorithmKey(), }; }); }
public string GetJwtByIdentity(ClaimsIdentity identity) { var now = DateTime.UtcNow; var jwt = new JwtSecurityToken( issuer: _authOptions.ISSUER, audience: _authOptions.AUDIENCE, notBefore: now, claims: identity.Claims, expires: now.Add(TimeSpan.FromMinutes(_authOptions.LIFETIME)), signingCredentials: new SigningCredentials( _authOptions.GetSymmetricAlgorithmKey(), SecurityAlgorithms.HmacSha256 ) ); var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); return(encodedJwt); }