public async Task <string> Login(UserLoginModel userData) { var checkingPasswordResult = await _signInManager.PasswordSignInAsync(userData.Email, userData.Password, false, false); if (checkingPasswordResult.Succeeded) { var signinCredentials = new SigningCredentials(_authenticationOptions.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256); var user = await _userManager.FindByEmailAsync(userData.Email); if (user == null) { throw new NotFoundException("A user with such Id was not found!"); } var userClaims = await _userManager.GetClaimsAsync(user); var loginClaims = new[] { new Claim(JwtRegisteredClaimNames.Iat, DateTime.UtcNow.ToString()), new Claim(JwtRegisteredClaimNames.Email, userData.Email), }; var jwtSecurityToken = new JwtSecurityToken( issuer: _authenticationOptions.Issuer, audience: _authenticationOptions.Audience, claims: loginClaims.Concat(userClaims).ToArray(), expires: DateTime.Now.AddDays(30), signingCredentials: signinCredentials ); var tokenHandler = new JwtSecurityTokenHandler(); var encodedToken = tokenHandler.WriteToken(jwtSecurityToken); return(encodedToken); } return(null); }
public string SetToken(List <Claim> claims, TUser user = null) { var claimsIdentity = new ClaimsIdentity(claims, "Token", ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType); var now = DateTime.Now; var jwt = new JwtSecurityToken( AuthOptions.ISSUER, AuthOptions.AUDIENCE, notBefore: now, claims: claimsIdentity.Claims, expires: now.Add(TimeSpan.FromMinutes(AuthOptions.LIFETIME)), signingCredentials: new SigningCredentials(AuthOptions.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256)); var token = new JwtSecurityTokenHandler().WriteToken(jwt); if (user != null) { user.Token = token; SetRefresh(user); user.LastLoginDate = DateTime.Now; } return(token); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.RequireHttpsMetadata = false; options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidIssuer = AuthOptions.ISSUER, ValidateAudience = true, ValidAudience = AuthOptions.AUDIENCE, ValidateLifetime = true, IssuerSigningKey = AuthOptions.GetSymmetricSecurityKey(), ValidateIssuerSigningKey = true, }; }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); }
public async Task <IActionResult> Token([FromBody] User user) { var claims = await GetIdentity(user.Username, user.Password); if (claims == null) { return(Unauthorized()); } var now = DateTime.UtcNow; var jwt = new JwtSecurityToken( issuer: AuthOptions.ISSUER, audience: AuthOptions.AUDIENCE, notBefore: now, claims: claims, expires: now.Add(TimeSpan.FromMinutes(AuthOptions.LIFETIME)), signingCredentials: new SigningCredentials(AuthOptions.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256)); var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); return(Json(encodedJwt)); }
private string GetRefreshToken(string userId) { Claim[] claims = new Claim[] { new Claim(ClaimsIdentity.DefaultNameClaimType, userId) }; var now = DateTime.UtcNow; var refreshToken = new JwtSecurityToken( issuer: AuthOptions.ISSUER, audience: AuthOptions.AUDIENCE, notBefore: now, claims: claims, expires: now.Add(TimeSpan.FromMinutes(30)), signingCredentials: new SigningCredentials(AuthOptions.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256)); var encodedRefreshJwt = new JwtSecurityTokenHandler().WriteToken(refreshToken); // Записать в кэш _refreshToken = encodedRefreshJwt; return(encodedRefreshJwt); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.RequireHttpsMetadata = false; options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters { ValidateIssuer = true, ValidIssuer = AuthOptions.ISSUER, ValidateAudience = true, ValidAudience = AuthOptions.AUDIENCE, ValidateLifetime = true, IssuerSigningKey = AuthOptions.GetSymmetricSecurityKey(), ValidateIssuerSigningKey = true }; }); services.AddDbContext <ApplicationDbContext>(options => options.UseSqlServer(Configuration["Data:PetStoreProducts:ConnectionString"])); services.AddTransient <IProductExtendedRepository, EFProductExtendedRepository>(); services.AddTransient <ICommentRepository, EFCommentRepository>(); services.AddTransient <IProductRepository, EFProductRepository>(); services.AddTransient <IStockRepository, EFStockRepository>(); services.AddTransient <IOrderRepository, EFOrderRepository>(); services.AddTransient <ICategoryRepository, EFCategoryRepository>(); services.AddTransient <IFilterConditionsProducts, FilterConditionsProducts>(); services.AddTransient <ImagesDbContext>(); services.AddTransient <IGetClaims, GetClaims>(); services.AddTransient <JwtSecurityTokenHandler>(); services.AddTransient <IEFUserRepository, EFUserRepository>(); services.AddSingleton <IPasswordHasher>(sp => new PasswordHasher()); services.AddScoped <IJwtTokenCryptographer, JwtTokenCryptographer>(); services.AddScoped(sp => SessionCart.GetCart(sp)); services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.RequireHttpsMetadata = false; options.TokenValidationParameters = new TokenValidationParameters { // укзывает, будет ли валидироваться издатель при валидации токена ValidateIssuer = true, // строка, представляющая издателя ValidIssuer = AuthOptions.ISSUER, // будет ли валидироваться потребитель токена ValidateAudience = true, // установка потребителя токена ValidAudience = AuthOptions.AUDIENCE, // будет ли валидироваться время существования ValidateLifetime = true, // установка ключа безопасности IssuerSigningKey = AuthOptions.GetSymmetricSecurityKey(), // валидация ключа безопасности ValidateIssuerSigningKey = true, }; }); services.AddDbContext <FierceStukCloudDbContext>(o => o.UseSqlServer(@"Data Source=88.135.50.215,1433; Initial Catalog=FSC_Data; User ID=Ivan; Password=789xxx44XX; Connect Timeout=30; Encrypt=False; TrustServerCertificate=False; ApplicationIntent=ReadWrite; MultiSubnetFailover=False")); //services.AddControllers(); //.AddNewtonsoftJson(options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore); services.AddSignalR(o => { o.MaximumReceiveMessageSize = 1048576; }); services.AddMvc(); }
private string Token(int id) { var identity = GetIdentity(id); if (identity == null) { Response.StatusCode = 400; return(null); } var now = DateTime.UtcNow; // создаем JWT-токен 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.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256)); var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); return(encodedJwt); }
public void ConfigureServices(IServiceCollection services) { services.AddMvc() .AddJsonOptions(x => x.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.RequireHttpsMetadata = false; options.SaveToken = true; options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidIssuer = AuthOptions.ISSUER, ValidAudience = AuthOptions.AUDIENCE, IssuerSigningKey = AuthOptions.GetSymmetricSecurityKey(), ValidateLifetime = true, ValidateIssuerSigningKey = true, ClockSkew = TimeSpan.Zero }; } ); }
private string GetIdentity(string username, string role) { var claims = new List <Claim> { new Claim(ClaimsIdentity.DefaultNameClaimType, username), new Claim(ClaimsIdentity.DefaultRoleClaimType, role) }; var claimsIdentity = new ClaimsIdentity(claims, "Token", ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType); var jwt = new JwtSecurityToken( issuer: AuthOptions.ISSUER, audience: AuthOptions.AUDIENCE, notBefore: DateTime.Now, claims: claimsIdentity.Claims, expires: DateTime.Now.Add(TimeSpan.FromMinutes(AuthOptions.LIFETIME)), signingCredentials: new SigningCredentials(AuthOptions.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256)); return(new JwtSecurityTokenHandler().WriteToken(jwt)); }
public static void AddJwtAuthentication(this IServiceCollection services, AuthOptions authOptions) { services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidIssuer = authOptions.Issuer, ValidateAudience = true, ValidAudience = authOptions.Audience, ValidateLifetime = true, ValidateIssuerSigningKey = true, IssuerSigningKey = authOptions.GetSymmetricSecurityKey(), }; options.Events = new JwtBearerEvents { OnMessageReceived = context => { var accessToken = context.Request.Query["access_token"]; var path = context.HttpContext.Request.Path; if (!string.IsNullOrEmpty(accessToken) && (path.StartsWithSegments("/hubs/notify"))) { context.Token = accessToken; } return(Task.CompletedTask); } }; }); }
private ClaimsPrincipal GetPrincipalFromExpiredToken(string token) { var tokenValidationParameters = new TokenValidationParameters { ValidateAudience = false, //you might want to validate the audience and issuer depending on your use case ValidateIssuer = false, ValidateIssuerSigningKey = true, IssuerSigningKey = AuthOptions.GetSymmetricSecurityKey(), ValidateLifetime = false //here we are saying that we don't care about the token's expiration date }; var tokenHandler = new JwtSecurityTokenHandler(); var principal = tokenHandler.ValidateToken(token, tokenValidationParameters, out SecurityToken securityToken); if (!(securityToken is JwtSecurityToken jwtSecurityToken) || !jwtSecurityToken.Header.Alg.Equals(SecurityAlgorithms.HmacSha256, StringComparison.InvariantCultureIgnoreCase)) { throw new SecurityTokenException("Invalid token"); } return(principal); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMyAccountsDb(Configuration); services.AddControllers(); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.RequireHttpsMetadata = false; options.TokenValidationParameters = new TokenValidationParameters { // укзывает, будет ли валидироваться издатель при валидации токена ValidateIssuer = true, // строка, представляющая издателя ValidIssuer = AuthOptions.ISSUER, // будет ли валидироваться потребитель токена ValidateAudience = true, // установка потребителя токена ValidAudience = AuthOptions.AUDIENCE, // будет ли валидироваться время существования ValidateLifetime = true, // установка ключа безопасности IssuerSigningKey = AuthOptions.GetSymmetricSecurityKey(), // валидация ключа безопасности ValidateIssuerSigningKey = true, }; }); services.AddSpaStaticFiles(configuration => { configuration.RootPath = "ClientApp"; }); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" }); }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddEntityFrameworkSqlite().AddDbContext <DatabaseContext>(); services.AddTransient <IDBFillHelper, DBFillHelper>(); services.AddControllers(); services.AddCors(options => { options.AddPolicy("AnyOrigin", builder => builder.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader()); }); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.RequireHttpsMetadata = false; options.TokenValidationParameters = new TokenValidationParameters { // укзывает, будет ли валидироваться издатель при валидации токена ValidateIssuer = true, // строка, представляющая издателя ValidIssuer = AuthOptions.ISSUER, // будет ли валидироваться потребитель токена ValidateAudience = true, // установка потребителя токена ValidAudience = AuthOptions.AUDIENCE, // будет ли валидироваться время существования ValidateLifetime = true, // установка ключа безопасности IssuerSigningKey = AuthOptions.GetSymmetricSecurityKey(), // валидация ключа безопасности ValidateIssuerSigningKey = true, }; }); }
public async Task Token() { var username = Request.Form["username"]; var password = Request.Form["password"]; var identity = GetIdentity(username, password); if (identity == null) { Response.StatusCode = 400; await Response.WriteAsync("Invalid username or password"); return; } 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.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256) ); var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); var response = new { access_token = encodedJwt, username = identity.Name }; Response.ContentType = "application/json"; await Response.WriteAsync(JsonConvert.SerializeObject(response, new JsonSerializerSettings { Formatting = Formatting.Indented })); }
/// <inheritdoc/> public async Task <dynamic> Login(UserRequest request) { var identity = GetIdentity(request.Login, request.Password); 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.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256)); var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); var response = new { access_token = encodedJwt, username = identity.Name, }; return(response); }
public async Task Token([FromBody] TokenModel model) { var username = model.username; var password = model.password; var identity = await GetIdentity(username, password); if (identity == null) { Response.StatusCode = 400; await Response.WriteAsync("Invalid username or password."); return; } 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.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256)); var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); var response = new { token = encodedJwt, username = identity.Name }; Response.ContentType = "application/json"; Response.Cookies.Append("jwt-token", encodedJwt); Response.Cookies.Append("jwt-user", identity.Name); var result = JsonConvert.SerializeObject(response, new JsonSerializerSettings { Formatting = Formatting.Indented }); await Response.WriteAsync(result); }
public IActionResult Token([FromForm] User form) { var identity = GetIdentity(form.Login, form.Password); if (identity == null) { return(Unauthorized(new { errorText = "Invalid username or password." })); } var now = DateTime.UtcNow; // создаем JWT-токен 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.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256)); var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); // создали вернули токен return(Ok(encodedJwt)); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddEntityFrameworkSqlite().AddDbContext <Db>(options => { options.UseLazyLoadingProxies(); }); services.AddTransient <IDbContext>(provider => { var aa = provider.GetService <Db>(); return(aa); }); services.AddTransient <IAuthRepository <User, UserRole>, IdentityUserService <User, Role, UserRole> >(); services.AddTransient <IRoleRepository <Role>, IdentityRoleService <Role> >(); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.RequireHttpsMetadata = false; options.TokenValidationParameters = new TokenValidationParameters { // укзывает, будет ли валидироваться издатель при валидации токена ValidateIssuer = true, // строка, представляющая издателя ValidIssuer = AuthOptions.ISSUER, // будет ли валидироваться потребитель токена ValidateAudience = true, // установка потребителя токена ValidAudience = AuthOptions.AUDIENCE, // будет ли валидироваться время существования ValidateLifetime = true, // установка ключа безопасности IssuerSigningKey = AuthOptions.GetSymmetricSecurityKey(), // валидация ключа безопасности ValidateIssuerSigningKey = true }; }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); services.AddDbContext <UserApiContext>(); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters() { ValidateIssuer = true, ValidIssuer = AuthOptions.ISSUER, ValidateAudience = true, ValidAudience = AuthOptions.AUDIENCE, ValidateLifetime = true, IssuerSigningKey = AuthOptions.GetSymmetricSecurityKey(), ValidateIssuerSigningKey = true, }; }); services.AddAuthorization(options => { foreach (PermissionType permission in Enum.GetValues(typeof(PermissionType))) { options.AddPolicy(permission.ToString(), policy => policy.Requirements.Add(new PermissionRequirement(permission))); } }); // In production, the React files will be served from this directory services.AddSpaStaticFiles(configuration => { configuration.RootPath = "ClientApp/build"; }); services.AddScoped <IAuthorizationHandler, PermissionHandler>(); services.AddScoped <PermissionService>(); }
public async Task Login([FromBody] LoginModel model) { var identity = GetIdentity(model); if (identity == null) { Response.StatusCode = 401; await Response.WriteAsync("Invalid username or password."); _logger.LogWarning("Invalid logging with login: {0}", model.Login); return; } var now = DateTime.UtcNow; // creating JWT-token var jwt = new JwtSecurityToken( AuthOptions.Issuer, AuthOptions.Audience, notBefore: now, claims: identity.Claims, expires: now.Add(TimeSpan.FromMinutes(AuthOptions.Lifetime)), signingCredentials: new SigningCredentials(AuthOptions.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256)); var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); var response = new { access_token = encodedJwt, login = identity.Name, userid = _context.Users.FirstOrDefault(u => u.Login == model.Login).Id }; // serializing response Response.ContentType = "application/json"; await Response.WriteAsync(JsonConvert.SerializeObject(response, new JsonSerializerSettings { Formatting = Formatting.Indented })); _logger.LogInformation("Success token granted for user: {0}", model.Login); }
public async Task <UserManagerResponse> Login([FromBody] LoginDto model) { var checkingPasswordResult = await _signInManager.PasswordSignInAsync(model.Username, model.Password, false, false); if (checkingPasswordResult.Succeeded) { var signinCredentials = new SigningCredentials(_authenticationOptions.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256); var jwtSecurityToken = new JwtSecurityToken( issuer: _authenticationOptions.Issuer, audience: _authenticationOptions.Audience, claims: new List <Claim>(), expires: DateTime.Now.AddDays(30), signingCredentials: signinCredentials ); var tokenHandler = new JwtSecurityTokenHandler(); var encodedToken = tokenHandler.WriteToken(jwtSecurityToken); var user = _userManager.FindByNameAsync(model.Username); UserDto userInfo = _mapper.Map <UserDto>(user.Result); return(new UserManagerResponse { Message = "Success", IsSucces = true, ExpireDate = jwtSecurityToken.ValidTo, Token = encodedToken, User = userInfo }); } return(new UserManagerResponse { IsSucces = false, Message = "Incorect password" }); }
public IActionResult Token([FromBody] UserBLL model) { var identity = GetIdentity(model.Login, model.Password); if (identity == null) { return(Unauthorized()); } var now = DateTime.UtcNow; var jwt = new JwtSecurityToken( issuer: AuthOptions.ISSUER, audience: AuthOptions.AUDIENCE, notBefore: now, claims: identity, expires: now.Add(TimeSpan.FromMinutes(AuthOptions.LIFETIME)), signingCredentials: new SigningCredentials(AuthOptions.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256)); var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); userHelper.Token = encodedJwt; return(Ok(userHelper)); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddDbContext <SimpleCarrierDbContext>(options => options.UseNpgsql("Host=localhost;Port=5432;Database=SimpleCarrier;Username=postgres;Password=password")); services.AddIdentity <UserDbModel, RoleDbModel>() .AddEntityFrameworkStores <SimpleCarrierDbContext>(); services.AddAuthorization(options => { options.DefaultPolicy = new AuthorizationPolicyBuilder(JwtBearerDefaults.AuthenticationScheme) .RequireAuthenticatedUser() .Build(); }); services .AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.RequireHttpsMetadata = false; options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidIssuer = AuthOptions.Issuer, ValidateAudience = false, ValidateLifetime = true, ValidateIssuerSigningKey = true, IssuerSigningKey = AuthOptions.GetSymmetricSecurityKey() }; }); services .AddMvc() .AddJsonOptions(options => { options.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver(); }); }
public async Task <string> CreateJwtTokenAsync(string email, string password) { var claimsIdentity = await GetIdentity(email, password); if (claimsIdentity == null) { return(null); } var now = DateTime.UtcNow; var jwt = new JwtSecurityToken( issuer: authOptions.Issuer, audience: authOptions.Audience, notBefore: now, claims: claimsIdentity.Claims, expires: now.Add(TimeSpan.FromMinutes(authOptions.Lifetime)), signingCredentials: new SigningCredentials(authOptions.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256)); var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); return(encodedJwt); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options => { options.RequireHttpsMetadata = false; options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidIssuer = AuthOptions.ISSUER, ValidateAudience = true, ValidAudience = AuthOptions.AUDIENCE, ValidateLifetime = true, ValidateIssuerSigningKey = true, IssuerSigningKey = AuthOptions.GetSymmetricSecurityKey() }; }); services.AddDbContext <ApplicationContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); services.AddIdentity <User, IdentityRole>().AddEntityFrameworkStores <ApplicationContext>(); services.AddMvc(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddDbContext <ExampleContext>(opt => opt.UseInMemoryDatabase("ORM-example")); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters() { ValidateIssuer = true, ValidIssuer = AuthOptions.ISSUER, ValidateAudience = true, ValidAudience = AuthOptions.AUDIENCE, ValidateIssuerSigningKey = true, IssuerSigningKey = AuthOptions.GetSymmetricSecurityKey(), ValidateLifetime = true, }; } ); services.AddControllers(); }
public async Task <string> Post([FromBody] UserDTO model) { var identity = await GetIdentityAsync(model.Email, model.Password); if (identity == null) { return("Invalid username or password."); } var now = DateTime.UtcNow; // создаем JWT-токен var jwt = new JwtSecurityToken( notBefore: now, claims: identity.Claims, expires: now.Add(TimeSpan.FromMinutes(AuthOptions.LIFETIME)), signingCredentials: new SigningCredentials(AuthOptions.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256)); var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); var response = new JWT(encodedJwt, "auth_token"); return(JsonSerializer.Serialize(encodedJwt)); }
public static IServiceCollection AddAppAuthentication(this IServiceCollection services, IConfiguration configuration) { services.Configure <AuthOptions>(configuration.GetSection(AuthOptions.Security)); services.AddDbContext <AuthenticationDbContext>(options => options.UseSqlServer(configuration.GetConnectionString("Auth"))); services .AddIdentity <User, IdentityRole>() .AddEntityFrameworkStores <AuthenticationDbContext>() .AddDefaultTokenProviders(); var authOptions = new AuthOptions(); configuration.GetSection(AuthOptions.Security).Bind(authOptions); services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(options => { options.SaveToken = true; options.RequireHttpsMetadata = false; options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidIssuer = authOptions.Issuer, ValidateAudience = true, ValidAudience = authOptions.Audience, ValidateLifetime = true, IssuerSigningKey = authOptions.GetSymmetricSecurityKey(), }; }); return(services); }
public async Task <ActionResult> Login(User user) { if (!ModelState.IsValid) { return(new InvalidObjectHttpException().ToJson()); } var userDb = _loginService.Get(user.Name).Value; if (userDb == null || user.Password != userDb.Password) { return(new LoginHttpException().ToJson()); } var identity = await GetIdentity(userDb); 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.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256)); var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); var response = new { access_token = encodedJwt, username = identity.Name }; Response.ContentType = "application/json"; await Response.WriteAsync(JsonConvert.SerializeObject(response, new JsonSerializerSettings { Formatting = Formatting.Indented })); return(Ok()); }