// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); 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, }; }); // In production, the React files will be served from this directory services.AddSpaStaticFiles(configuration => { configuration.RootPath = "ClientApp/build"; }); string connection = Configuration.GetConnectionString("DefaultConnection"); services.AddDbContext <ApplicationContext>(options => options.UseSqlServer(connection)); services.AddControllersWithViews(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { //using Dependency Injection services.AddControllers(); services.AddDbContext <CommentDBContext>(options => options.UseMySql(Configuration.GetConnectionString("DefaultConnection"))); services.AddControllers().AddNewtonsoftJson(options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore ); // add Authentication using jwt token services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.RequireHttpsMetadata = false; options.TokenValidationParameters = new TokenValidationParameters { // whether lifetime will be validated ValidateLifetime = true, // setting security key IssuerSigningKey = AuthOptions.GetSymmetricSecurityKey(), ValidateAudience = false, ValidateIssuer = false, //security key validation ValidateIssuerSigningKey = true, }; }); services.AddScoped <ICommentsRepository, CommentsRepository>(); services.AddAutoMapper(typeof(Startup).Assembly); services.AddCors(options => { options.AddPolicy(CorsOrigins, builder => { builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader(); }); }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { var connection = Configuration.GetConnectionString("DefaultConnection"); services.AddDbContext <EFDBContext> (options => options.UseSqlServer(connection, b => b.MigrationsAssembly("DataLayer"))); services.AddIdentity <ApplicationUser, IdentityRole>() .AddEntityFrameworkStores <EFDBContext>(); services.AddTransient <IAccountRepository, EFAccountRepository>(); services.AddTransient <IChatRepository, EFChatRepository>(); services.AddTransient <IMessageRepository, EFMessageRepository>(); services.AddAuthentication(x => { x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultChallengeScheme = 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.AddControllers(); services.AddSwaggerDocumentation(); services.AddAutoMapper(typeof(AutoMapping)); }
public async Task Token(TokenUserModel model) { if (!ModelState.IsValid) { Response.StatusCode = 400; await Response.WriteAsync("username or password cannot be empty"); return; } var email = model.UserName; //Request.Form["username"]; var password = model.Password; //Request.Form["password"]; var query = new GetUserByEmail(email); var result = BusControl.SendRequest <IGetUserByEmail, IGetUserResult>(query).Result; var identity = AuthOptions.GetIdentity(email, password, result.User.PasswordHash, result.User.RoleName); if (identity == null) { Response.StatusCode = 400; await Response.WriteAsync("Invalid username or password."); return; //return BadRequest("Invalid username or password."); } var encodedJwt = AuthOptions.Token(identity); var response = new { accesstoken = encodedJwt, username = identity.Name }; // сериализация ответа Response.ContentType = "application/json"; await Response.WriteAsync(JsonConvert.SerializeObject(response, new JsonSerializerSettings { Formatting = Formatting.Indented })); }
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"), b => b.MigrationsAssembly(configuration.GetSection("MigrationAssembly").Value ?? CURRENT_ASSEMBLY)); }); 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); }
// 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 = false, // строка, представляющая издателя //ValidIssuer = AuthOptions.ISSUER, // будет ли валидироваться потребитель токена ValidateAudience = false, // установка потребителя токена // ValidAudience = AuthOptions.AUDIENCE, // будет ли валидироваться время существования ValidateLifetime = true, // установка ключа безопасности IssuerSigningKey = AuthOptions.GetSymmetricSecurityKey(), // валидация ключа безопасности ValidateIssuerSigningKey = true, }; }); string connection = Configuration.GetConnectionString("RadioConnection"); services.AddDbContext <RadioContext>(options => options.UseSqlServer(connection)); services.AddScoped <IEmployerRepository, EmployerRepository>(); services.AddScoped <IReleaseRepository, ReleaseRepository>(); services.AddScoped <IReclameBlockRepository, ReclameBlockRepository>(); services.AddScoped <IEmployerService, EmployerService>(); services.AddScoped <IReleaseService, ReleaseService>(); services.AddScoped <IReclameBlockService, ReclameBlockService>(); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); }
public async Task <string> CreateToken(UserAccountDTO user) { var username = user.Login; var password = user.Password; var identity = await GetIdentity(username, password); if (identity == null) { 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, login = identity.Name, id = user.Id, email = user.Email, role = identity.Claims .Where(c => c.Type == ClaimTypes.Role) .Select(c => c.Value) }; string token = JsonConvert.SerializeObject(response, new JsonSerializerSettings { Formatting = Formatting.Indented }); return(token); }
public async Task Token(Card card) { var existingCard = await _context.Cards.FirstOrDefaultAsync(e => e.Email == card.Email); bool isVerified = Hashing.VerifyHashedPassword(existingCard.PasswordHash, card.PasswordHash); if (!isVerified) { Response.StatusCode = 400; await Response.WriteAsync("Invalid username or password."); return; } var identity = GetIdentity(card.Email, existingCard.PasswordHash); 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); var response = new { access_token = encodedJwt, email = identity.Name, cardId = existingCard.CardId, cardOwnerName = existingCard.CardOwnerName }; // сериализация ответа Response.ContentType = "application/json"; await Response.WriteAsync(JsonConvert.SerializeObject(response, new JsonSerializerSettings { Formatting = Formatting.Indented })); }
public void ConfigureServices(IServiceCollection services) { services.AddDbContext <IDataContext, DataContext>(options => options.UseLazyLoadingProxies() .UseSqlServer(Configuration.GetConnectionString("TSUKATDataBase"))); services.AddControllers() .AddNewtonsoftJson(options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore); var authOptions = new AuthOptions(); var authConfigurationSection = Configuration.GetSection("AuthOptions"); services.Configure <AuthOptions>(authConfigurationSection); authConfigurationSection.Bind(authOptions); 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.AddScoped <IAuthenticationService, AuthenticationService>(); services.AddScoped <IUserService, UserService>(); services.AddScoped <IGroupService, GroupService>(); services.AddScoped <IUserFacade, UserFacade>(); services.AddScoped <IGroupFacade, GroupFacade>(); }
public void ConfigureServices(IServiceCollection services) { services.AddSingleton(Configuration); services.AddDbContext <RestAppContext>(); services.AddRepository <User, IUsersRepository, UsersRepository>(); services.AddRepository <Label, Repository <Label> >(); services.AddRepository <Todo, Repository <Todo> >(); services.AddTransient <IUsersService, UsersService>(); services.AddTransient <IAuthenticationService, AuthenticationService>(); services.AddMediatR(AppDomain.CurrentDomain.GetAssemblies()); AuthOptions authOptions = new AuthOptions( Configuration["AuthOptions:SecretKey"], int.Parse(Configuration["AuthOptions:Lifetime"]) ); services.AddSingleton(authOptions); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).Configure(authOptions); services.AddCors(); services.AddControllers() .AddFluentValidation(options => { options.RegisterValidatorsFromAssemblies(AppDomain.CurrentDomain.GetAssemblies()); options.RunDefaultMvcValidationAfterFluentValidationExecutes = false; }) .AddNewtonsoftJson(options => options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver()); services.AddSwaggerGen(options => { options.SwaggerDoc("v1", new OpenApiInfo { Title = "RestAPI101.WebAPI", Version = "v1" }); }); }
public async Task Token() { var login = Request.Form["login"]; var typedPasswordHash = Request.Form["password"]; var employee = GetEmployeeByEmail(login); if (employee == null || typedPasswordHash != employee.Password.HashValue) { Response.StatusCode = 400; await Response.WriteAsync("Invalid username or password."); return; } var now = DateTime.UtcNow; // создаем JWT-токен var jwt = new JwtSecurityToken( issuer: AuthOptions.Issuer, audience: AuthOptions.Audience, notBefore: now, 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 = employee.EmailAddress }; // сериализация ответа Response.ContentType = "application/json"; await Response.WriteAsync(JsonConvert.SerializeObject(response, new JsonSerializerSettings { Formatting = Formatting.Indented })); }
/// <summary> /// Auth user and get token /// </summary> /// <param name="user"></param> /// <returns></returns> protected async Task <UserLoginResponseModel> AuthUserWithToken(AppUser user) { var userBucket = await GetIdentity(user); if (userBucket == null) { throw new LoginFailedException(user.Email); } var roles = userBucket.Item1; var identity = userBucket.Item2; var now = DateTime.UtcNow; var expires = now.Add(TimeSpan.FromSeconds(AuthOptions.LIFETIME)); var jwt = new JwtSecurityToken( issuer: AuthOptions.ISSUER, audience: AuthOptions.AUDIENCE, notBefore: now, expires: expires, claims: identity.Claims, signingCredentials: new SigningCredentials(AuthOptions.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256)); var encoded = new JwtSecurityTokenHandler().WriteToken(jwt); var response = _mapper.Map <UserLoginResponseModel>(user); response.Roles = roles; response.Token = new UserLoginTokenResponseModel { Expires = expires, Token = encoded, LoginProvider = LoginOptions.SERVICE_LOGIN_PROVIDER, LoginProviderDisplay = LoginOptions.SERVICE_LOGIN_DISPLAY }; await _appUserManager.AddLoginAsync(user, new UserLoginInfo(LoginOptions.SERVICE_LOGIN_PROVIDER, encoded, LoginOptions.SERVICE_LOGIN_DISPLAY)); return(response); }
// 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); services.AddDbContext <UserDBContext>(options => { options.UseNpgsql(Configuration["DbConnectionString"], c => c.MigrationsAssembly("AuthorizationSystem")); }); services.AddDomainServices(); services.AddSwaggerGen(opt => { opt.SwaggerDoc("authapi", new Info { Title = "AuthSystemApi", Version = "authapi" }); opt.DescribeAllEnumsAsStrings(); opt.AddSecurityDefinition("Bearer", new ApiKeyScheme { In = "header", Description = "Please enter into field the word 'Bearer' following by space and JWT", Name = "Authorization", Type = "apiKey" }); }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews() .AddNewtonsoftJson(options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore); services.AddCors(); string connection = Configuration.GetConnectionString("DefaultConnection"); services.AddDbContext <ApplicationContext>(options => options.UseNpgsql(connection)); 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, }; }); // In production, the React files will be served from this directory services.AddSpaStaticFiles(configuration => { configuration.RootPath = "ClientApp/build"; }); }
public async Task Token([FromBody] User userBody) { var email = userBody.email; var password = userBody.password.Encrypt(); var user = await _context.Users.SingleOrDefaultAsync(m => m.email == email && m.password == password); if (user == null) { Response.StatusCode = 400; await Response.WriteAsync("Invalid email or password."); return; } var identity = GetIdentity(user); var now = DateTime.UtcNow; // Création d'un token 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); var response = new { token = encodedJwt, user = user }; // Response sérialisation Response.ContentType = "application/json"; await Response.WriteAsync(JsonConvert.SerializeObject(response, new JsonSerializerSettings { Formatting = Formatting.Indented })); }
public async Task <TokenResponse> LoginAsync(UserDto login) { var identity = await GetIdentityAsync(login); if (identity == null) { throw new ArgumentException("Login failed. Check your login and password"); } var user = await _userManager.FindByEmailAsync(login.Email); // check if email is confirmed //var emailConfirmed = await _userManager.IsEmailConfirmedAsync(user); //if (!emailConfirmed) // throw new ArgumentException("Please confirm email"); var now = DateTime.Now; var jwt = new JwtSecurityToken( AuthOptions.ISSUER, AuthOptions.AUDIENCE, notBefore: now, claims: identity.Claims, expires: now.Add(TimeSpan.FromDays(AuthOptions.LIFETIME)), signingCredentials: new SigningCredentials(AuthOptions.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256)); var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); var token = new TokenResponse { Id = user.Id, AccessToken = encodedJwt, Email = identity.Name, User = user, UserId = user.Id }; return(token); }
public async Task Token([FromBody] LoginViewModel value) { try { var identity = GetIdentity(value.username, value.password); if (identity == null) { Response.StatusCode = 401; await Response.WriteAsync(JsonResponseFactory.CreateJson(null, new List <object> { "Username | Password" }, new List <string> { "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(JsonResponseFactory.CreateJson(response)); } catch (Exception ex) { Response.StatusCode = 400; Response.ContentType = "application/json"; await Response.WriteAsync(JsonResponseFactory.CreateJson(null, null)); } }
private async Task <(string AccessToken, bool Refreshed)> GetAccessTokenAsync() { await _lock.WaitAsync(); try { if (!IsAccessTokenExpired()) { return(_accessToken, false); } using (var request = new HttpRequestMessage(HttpMethod.Post, "oauth/token")) { AuthOptions options = _authOptions.Value; var requestObj = new JObject( new JProperty("grant_type", "client_credentials"), new JProperty("client_id", options.BackendClientId), new JProperty("client_secret", options.BackendClientSecret), new JProperty("audience", _authOptions.Value.ManagementAudience)); request.Content = new StringContent(requestObj.ToString(), Encoding.UTF8, "application/json"); if (string.IsNullOrEmpty(options.BackendClientSecret)) { Console.WriteLine("Note: AuthService is using an empty BackendClientSecret."); } HttpResponseMessage response = await _httpClient.SendAsync(request); await _exceptionHandler.EnsureSuccessStatusCode(response); string responseJson = await response.Content.ReadAsStringAsync(); var responseObj = JObject.Parse(responseJson); _accessToken = (string)responseObj["access_token"]; return(_accessToken, true); } } finally { _lock.Release(); } }
public async Task Token() { var username = Request.Form["email"]; var password = Request.Form["password"]; //var username = "******"; //var password = "******"; var identity = GetIdentity(username, password); if (identity == null) { Response.StatusCode = 400; await Response.WriteAsync("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); var response = new { access_token = encodedJwt, role = identity.RoleClaimType }; // сериализация ответа Response.ContentType = "application/json"; await Response.WriteAsync(JsonConvert.SerializeObject(response, new JsonSerializerSettings { Formatting = Formatting.Indented })); //return Ok(response); }
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 userId = um.GetUserIdByUsername(identity.Name); var userRolesNames = rm.GetListOfUserRolesNames(userId); var response = new { access_token = encodedJwt, role = userRolesNames.ToArray(), userId = userId }; Response.ContentType = "application/json"; await Response.WriteAsync(JsonConvert.SerializeObject(response, new JsonSerializerSettings { Formatting = Formatting.Indented })); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddSwagger(new SwaggerOptions { HostName = "Backand", BasePath = AppContext.BaseDirectory, FileNames = new[] { "RestService", }, }); services.AddDbContext <ApplicationContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); 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.AddScoped <INewsService, NewsService>(); services.AddScoped <IUserService, UserService>(); services.TryAddScoped <ExecuteService>(); }
public async Task Token([FromBody] LoginModel model) { var user = await userRepository.GetUser(model.Login); if (user == null) { Response.StatusCode = 400; await Response.WriteAsync("Invalid username or password."); return; } var identity = await GetIdentity(user, model.Password); var now = DateTime.UtcNow; var audience = ((Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.FrameRequestHeaders)((Microsoft.AspNetCore.Http.Internal.DefaultHttpRequest) this.Request).Headers).HeaderOrigin.First(); 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); var permissions = (await roleRepository.GetPermissions(user.Role.Name)).Select(p => p.Name); var response = new { access_token = encodedJwt, timeOut = AuthOptions.LIFETIME, userName = user.UserName, permissions }; Response.ContentType = "application/json"; await Response.WriteAsync(JsonConvert.SerializeObject(response, new JsonSerializerSettings { Formatting = Formatting.Indented })); }
private string GetToken(User user) { ClaimsIdentity identity = GetIdentity(user); if (identity == null) { return(null); } 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); 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, IssuerSigningKey = AuthOptions.GetSymmetricSecurityKey(), ValidateIssuerSigningKey = true, }; }); services.AddSingleton <IComputeTaskService, ComputeTaskService>(); services.AddSingleton <IUserService, UserService>(); services.AddHostedService <Worker>(); services.AddControllers(); services.AddDbContext <LoadManagerContext>(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo()); }); }
private JwtSecurityToken ReadToken(string jwt) { var handler = new JwtSecurityTokenHandler(); try { SecurityToken token; var principal = handler.ValidateToken(jwt, new TokenValidationParameters { ValidateIssuer = true, ValidIssuer = AuthOptions.ISSUER, ValidateAudience = true, ValidAudience = AuthOptions.AUDIENCE, ValidateLifetime = true, IssuerSigningKey = AuthOptions.GetSymmetricSecurityKey(), ValidateIssuerSigningKey = true, }, out token); } catch (SecurityTokenException e) { throw new SmartcontractException("Принятый токен невалиден: " + e.Message, ApiErrorCode.InvalidToken); } return(handler.ReadJwtToken(jwt)); }
public async Task RequestToken_WithAuthCallback_RetrievesTokenFromCallback() { var rest = GetRestClient(); var tokenRequest = new TokenParams { Capability = new Capability() }; var authCallbackCalled = false; var token = new TokenDetails(); var options = new AuthOptions { AuthCallback = (x) => { authCallbackCalled = true; return(Task.FromResult <object>(token)); } }; var result = await rest.Auth.RequestTokenAsync(tokenRequest, options); authCallbackCalled.Should().BeTrue(); Assert.Same(token, result); }
public void NameClaimTypeRetriever_Should_Use_XAuthenticatedUserId_If_Present() { var authOptions = new AuthOptions() { EnableServiceAccountAuthorization = false }; var devPermissionsOptions = new DevPermissionsOptions(); var jwtSigningKeyProviderMock = new Mock <IJwtSigningKeyResolver>(); var hostingEnvironmentMock = new Mock <IHostingEnvironment>(); var tokenValidationParametersFactory = new TokenValidationParametersFactory(Options.Create(authOptions), jwtSigningKeyProviderMock.Object, Options.Create(devPermissionsOptions), hostingEnvironmentMock.Object); var token = "eyJ4NXUiOiJodHRwczpcL1wvYXBpLWd3LW8uYW50d2VycGVuLmJlXC9rZXlzXC9wdWIiLCJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYmYiOjE0OTE5MTA5ODMsIlgtQ3JlZGVudGlhbC1Vc2VybmFtZSI6Im5vbmUiLCJYLUNvbnN1bWVyLUdyb3VwcyI6InBla2UubW9ja2Jpbi52MSIsImlzcyI6IjcwOTU5NGMyYjAwZDRkMjA5MDJlZTc3YWZkMDJiYjBjIiwiYXVkIjoibW9ja2Jpbi5vcmciLCJYLUpXVC1Jc3N1ZXIiOiJodHRwczpcL1wvYXBpLWd3LW8uYW50d2VycGVuLmJlIiwiWC1Db25zdW1lci1Vc2VybmFtZSI6ImludC1wZWtlLm1vY2tiaW4udjEiLCJYLUNvbnN1bWVyLUN1c3RvbS1JRCI6ImludC1wZWtlLm1vY2tiaW4udjEiLCJYLUF1dGhlbnRpY2F0ZWQtVXNlcmlkIjoicmMwMDExNUBkaWdhbnQuYW50d2VycGVuLmxvY2FsIiwiWC1BdXRoZW50aWNhdGVkLVNjb3BlIjoibm9uZSIsIlgtSG9zdC1PdmVycmlkZSI6Im5vbmUiLCJpYXQiOjE0OTE5MTEyODMsImp0aSI6IjhiNGJjNTIxNWJmODQ5NmJiOTM1ZjNiMzA1Yzg3NzEzIiwiWC1Db25zdW1lci1JRCI6IjU0ODkwNWU0LWM0OTUtNGUxOS1hOGQ5LTY0NGMwMmJkY2ExYiIsImV4cCI6MTQ5MjEyNzI4M30.MlSg19vT0zi3Vh8k283FzsHaseggezSWFuWN2-n4r-VsOXNuN1mxge95EFz2v_fJ__YN_b2w5CYJ0GKFXSDjD7kxctc3h8m3pI55GyHsDePn66qXipS0ayShaWKAkeg0xGWBV3KuHuGFVmEwcUJbi5yAYhfRqUdNbSSCMS1SuFA-jyOmr_jT7NSJGehjGzby20perBGnVnQhULv0mf3mX1Li3IX4jKHVMOB3dJKnhgazaOhS0pDhiERbTqop1e3H-g6hKttRSkOJNPyLbzw76fJfq9eLLQEGE8_XtU_W8iXy_1Wb6B6Qbao8IMFx65T1xGIALqR556TgWdXjNsAROQCBFNv0aCdbExvxYUjpu_w56JlYqMCRfEcxr1d2h8axxQDJrosu5T2YjjS61k0MXgFpbQqEj5N9Y47kvmp0qN9SQU9bKMsP3Pvw9oixgLNa-TaHvtTjovWl9iw4s4krQtaTlQvtXU5S99ZnQMLPdhZl_2VR3vVS75yoy-UXKENBAEoQRZ2FQfAV_cEBM8q5DGOR-SD17faNaRjIrTqLTRjr4RdXZbmYhQziEmKfG2vVQYjUIjBXINJS7KmiGLn4ZFpqM7jBXn-bmNBRRsmSEAMF4qIExhYavY2gwQ6MeQg4ZfwW7Oto9ce_Oy2fnxOanMPgAyG3GKfLRrm8Brg7i6w"; SecurityToken securityToken = new JwtSecurityToken(token); var result = tokenValidationParametersFactory.NameClaimTypeRetriever(securityToken, String.Empty); Assert.Equal(Claims.XAuthenticatedUserId, result); }
public void NameClaimTypeRetrieverShouldUseXConsumerUsernameClaimIfSubNotPresent() { var authOptions = new AuthOptions() { EnableServiceAccountAuthorization = true }; var devPermissionsOptions = new DevPermissionsOptions(); var jwtSigningKeyProviderMock = new Mock <IJwtSigningKeyResolver>(); var hostingEnvironmentMock = new Mock <IHostingEnvironment>(); var tokenValidationParametersFactory = new TokenValidationParametersFactory(Options.Create(authOptions), jwtSigningKeyProviderMock.Object, Options.Create(devPermissionsOptions), hostingEnvironmentMock.Object); var token = "eyJ4NXUiOiJodHRwczpcL1wvYXBpLWd3LWEuYW50d2VycGVuLmJlXC9rZXlzXC9wdWIiLCJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYmYiOjE1MjA1MTI1MTEsIlgtQ3JlZGVudGlhbC1Vc2VybmFtZSI6Im5vbmUiLCJYLUNvbnN1bWVyLUdyb3VwcyI6ImFzdGFkLmFwcm9maWVsLnYxLCBhYnMuYWJzYmlqbGFnZWFwaS52MSwgYWJzLmFic2Rvc3NpZXJhcGkudjEsIGFjcGFhcy53Y21jb250ZW50bWFuYWdlci52MywgamltbXloYW5ub24udGVzdC52MSwgYWJzLmFic3Byb2Nlc3NhcGkudjEsIGFjcGFhcy53Y21wcm94eS52MyIsImlzcyI6Imh0dHBzOlwvXC9hcGktZ3ctYS5hbnR3ZXJwZW4uYmUiLCJhdWQiOiJyYXN1MTE1NS5ydGUuYW50d2VycGVuLmxvY2FsOjUwMTAyIiwiWC1KV1QtSXNzdWVyIjoiaHR0cHM6XC9cL2FwaS1ndy1hLmFudHdlcnBlbi5iZSIsIlgtQ29uc3VtZXItVXNlcm5hbWUiOiJpbnQtYWJzaW9kLmZvcm1pb2Rsb2NhbC52MSIsIlgtQ29uc3VtZXItQ3VzdG9tLUlEIjoiaW50LWFic2lvZC5mb3JtaW9kbG9jYWwudjEiLCJYLUF1dGhlbnRpY2F0ZWQtVXNlcmlkIjoibm9uZSIsIlgtQXV0aGVudGljYXRlZC1TY29wZSI6Im5vbmUiLCJYLUhvc3QtT3ZlcnJpZGUiOiJub25lIiwiaWF0IjoxNTIwNTEyODExLCJqdGkiOiI2ODBkZmEyNzgxMGU0MDhhYWE3YjcyOGUxMTdlYjk5ZSIsIlgtQ29uc3VtZXItSUQiOiI3OGM5ZDA0Mi03NTNhLTRkNWUtOGMzNS1hYTg2Yjk4OTI2OTIiLCJleHAiOjE1MjA3Mjg4MTF9.XeGnL6a_NDHYl7WHPL3tmrXP1Ga483ZePFD6x-LoJP8znTmYVfbYtQcajADgtZu2x65detsSBb0Z_MnVK7mod3Eec7niyz67UMu2Be86CmTbl-wTtf6i4UZKVcCk6alS-d2ZC6g9Hk66njOecXES998xij4CiKoikGUJ5AdY6FWxhpnOKRFg5FbhiIpHt294Hf2QSHjuV2476xbYTWCSOr8A61LibPzhR9hOHaopOivnCOkPeJEZtn98Lyoa6CqcM44gdppZdO9rqQ1pxhLrycdsc2dSZ0yxHXwmZ5XwOfmCqbQRIl4WbmMpuMVfUEetHhuZ95pI_oUxZsIqxyMLRwOv6z1K184MVgRzFB6ziZY495a2zXoOMXwqhk7C-Zih_8mgPvYbsoR6Rv7jp95c7xfMTMUDuj0HelIr3FVlff-J7XZEuWeTDdp6Hvk4JkxMnkMiYkeuzmsiJKaCcirUlelSftcebr2AL_-jVQ9jtnfmXt7NUWKrYEd9Ohn7qyxaDWb2M-JzL_FhONt1H81zpzwq45SSC21YjjxNpo9basMtiYzRTtRNMusUbkEHxgwkfLcBNywse0vygWWnehWkD3rwryJAjL5ifrCWEKbC9Bk2BVf1i_kzdCI_iCixy5HXQcQ6bsTtUB_6k1XowsDj9kL7PLAe2nPCErxd7SYA2dg"; SecurityToken securityToken = new JwtSecurityToken(token); var result = tokenValidationParametersFactory.NameClaimTypeRetriever(securityToken, String.Empty); Assert.Equal(Claims.XConsumerUsername, result); }
public void NameClaimTypeRetrieverShouldUseSubClaimIfPresent() { var authOptions = new AuthOptions() { EnableServiceAccountAuthorization = true }; var devPermissionsOptions = new DevPermissionsOptions(); var jwtSigningKeyProviderMock = new Mock <IJwtSigningKeyResolver>(); var hostingEnvironmentMock = new Mock <IHostingEnvironment>(); var tokenValidationParametersFactory = new TokenValidationParametersFactory(Options.Create(authOptions), jwtSigningKeyProviderMock.Object, Options.Create(devPermissionsOptions), hostingEnvironmentMock.Object); var token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiIsIng1dSI6Imh0dHA6Ly9sb2NhbGhvc3Q6NTAwMC94NXUifQ.eyJpc3MiOiJPbmxpbmUgSldUIEJ1aWxkZXIiLCJpYXQiOjE0NzI1NDk1NDgsImV4cCI6MTUwNDA4NTU0OCwiYXVkIjoid3d3LmV4YW1wbGUuY29tIiwic3ViIjoianJvY2tldEBleGFtcGxlLmNvbSIsIkdpdmVuTmFtZSI6IkpvaG5ueSIsIlN1cm5hbWUiOiJSb2NrZXQiLCJFbWFpbCI6Impyb2NrZXRAZXhhbXBsZS5jb20iLCJSb2xlIjpbIk1hbmFnZXIiLCJQcm9qZWN0IEFkbWluaXN0cmF0b3IiXX0.jKg9l0cuTapEFcx9v1pLtBiigK_7EXlCqvKZBoS24XE"; SecurityToken securityToken = new JwtSecurityToken(token); var result = tokenValidationParametersFactory.NameClaimTypeRetriever(securityToken, String.Empty); Assert.Equal(Claims.Sub, result); }
// 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); }