private string GetToken(User user, DateTime now, DateTime to, string role) { var claims = new List <Claim> { new Claim(ClaimsIdentity.DefaultNameClaimType, user.UserName), new Claim("Id", user.Id.ToString()) }; if (role != null) { claims.Add(new Claim(ClaimsIdentity.DefaultRoleClaimType, role)); } ClaimsIdentity claimsIdentity = new ClaimsIdentity(claims, "Token", ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType); // создаем JWT-токен var jwt = new JwtSecurityToken( issuer: AuthTokenOptions.ISSUER, notBefore: now, claims: claimsIdentity.Claims, expires: to, signingCredentials: new SigningCredentials(AuthTokenOptions.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256)); var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); return(encodedJwt); }
protected UserService( IGametekiDbContext context, IOptions <AuthTokenOptions> optionsAccessor, IOptions <GametekiApiOptions> lobbyOptions, IEmailSender emailSender, IViewRenderService viewRenderService, ILogger <UserService> logger, IStringLocalizer <UserService> localizer) { if (lobbyOptions == null) { throw new ArgumentNullException(nameof(lobbyOptions)); } if (optionsAccessor == null) { throw new ArgumentNullException(nameof(optionsAccessor)); } this.context = context; apiOptions = lobbyOptions.Value; this.emailSender = emailSender; this.viewRenderService = viewRenderService; this.logger = logger; t = localizer; tokenOptions = optionsAccessor.Value; }
// This method gets called by the runtime. Use this method to add services to the container public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddApplicationInsightsTelemetry(Configuration); services.AddTransient(provider => new DatabaseConnections() { Database = Configuration.GetValue <string>("Connections:Database") }) .AddTransient <IEncryptor, Encryptor>() .AddTransient(typeof(IStorageContext <>), typeof(StorageContext <>)) .AddTransient <IStorageContext <AppUser>, StorageContext <AppUser> >() .AddTransient <UserStorageContext>() .AddTransient <IPasswordComplexity>(provider => new PasswordComplexity() .MinimumLength(8) .LowerCase() .UpperCase() .Numbers() .SpecialCharacters() ) .AddTransient <IValidator <Features.Accounts.Models.RegisterUserModel>, Features.Accounts.Validations.RegisterUserModelValidation>(); key = new RsaSecurityKey(GetRandomKey()); services.AddSingleton(typeof(AuthTokenOptions), tokenOptions = new AuthTokenOptions() { Audience = TokenAudience, Issuer = TokenIssuer, SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.RsaSha256Signature) }); services.AddMvc(options => { options.Filters.Add(new AuthorizeFilter(new AuthorizationPolicyBuilder() .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme) .RequireAuthenticatedUser() .Build())); }).AddFluentValidation(provider => { provider.ValidatorFactory = new ValidatorFactory(services.BuildServiceProvider()); }); }
public LobbyHub(ILobbyService lobbyService, IConnectionMultiplexer redisConnection, IGameNodeService gameNodeService, IOptions <AuthTokenOptions> tokenOptions) { this.lobbyService = lobbyService; this.gameNodeService = gameNodeService; this.tokenOptions = tokenOptions.Value; var subscriber = redisConnection.GetSubscriber(); database = redisConnection.GetDatabase(); if (setupDone) { return; } subscriber.Subscribe(RedisChannels.LobbyMessage).OnMessage(OnLobbyMessageAsync); subscriber.Subscribe(RedisChannels.LobbyMessageRemoved).OnMessage(OnLobbyMessageRemovedAsync); subscriber.Subscribe("RemoveRunningGame").OnMessage(OnRemoveGameAsync); setupDone = true; }
public TokenProvider(UserManager <ApplicationUser> userManager, IOptions <AuthTokenOptions> authTokenOptions) { _userManager = userManager; _authTokenOptions = authTokenOptions.Value; }
// 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 = AuthTokenOptions.ISSUER, ValidateAudience = false, ValidateLifetime = true, IssuerSigningKey = AuthTokenOptions.GetSymmetricSecurityKey(), ValidateIssuerSigningKey = true }; }); services.Configure <IdentityOptions>(options => { options.Password.RequireDigit = true; options.Password.RequiredLength = 6; options.Password.RequireNonAlphanumeric = false; options.Password.RequireUppercase = false; options.Password.RequireLowercase = false; options.User.RequireUniqueEmail = true; }); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "Galery API", Version = "v1" }); var basePath = AppContext.BaseDirectory; c.AddSecurityDefinition("Bearer", new ApiKeyScheme { Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"", Name = "Authorization", In = "header", Type = "apiKey" }); c.AddSecurityRequirement(new Dictionary <string, IEnumerable <string> > { { "Bearer", Enumerable.Empty <string>() } }); }); var config = new AutoMapper.MapperConfiguration(cfg => { cfg.AddProfile <PictureProfile>(); }); var mapper = config.CreateMapper(); services.AddSingleton(mapper); services.AddTransient <IUserStore <User>, UserStore>(); services.AddTransient <IRoleStore <Role>, RoleStore>(); services.AddSingleton <DbProviderFactory>(SqlClientFactory.Instance); services.AddIdentity <User, Role>().AddDefaultTokenProviders(); services.AddTransient <IUnitOfWork, UnitOfWork>(); services.AddTransient <IPictureService, PicturesService>(); services.AddTransient <IFileWorkService, FileWorkService>(); services.AddTransient <ITagService, TagService>(); services.AddTransient <IEmailService, EmailService>(); services.AddTransient <ICommentService, CommentService>(); services.AddTransient <ISubscribeService, SubscribeService>(); services.AddMvc(); }
public async Task <IActionResult> Token([FromBody] LoginViewModel model) { try { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var user = await _userManager.FindByNameAsync(model.UserName); if (user != null) { var ok = await _userManager.CheckPasswordAsync(user, model.Password); if (ok) { // проверяем, подтвержден ли email //if (!await _userManager.IsEmailConfirmedAsync(user)) //{ // ModelState.AddModelError("Email", "Вы не подтвердили свой email"); // return BadRequest(ModelState); //} var userClaims = await _userManager.GetClaimsAsync(user); var roles = await _userManager.GetRolesAsync(user); //var roles = await _uow.AspNetUserRoles.Query() // .Include(s => s.Role) // .Where(s => s.UserId == user.Id) // .Select(s => s.Role.Name) // .ToListAsync(); var claims = new List <Claim>() { new Claim(ClaimsIdentity.DefaultNameClaimType, model.UserName) //new Claim(ClaimsIdentity.DefaultRoleClaimType, roles.FirstOrDefault()) }; ClaimsIdentity claimsIdentity = new ClaimsIdentity(claims, "Token", ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType); var now = DateTime.UtcNow; // создаем JWT-токен var jwt = new JwtSecurityToken( issuer: AuthTokenOptions.ISSUER, notBefore: now, claims: claimsIdentity.Claims, expires: now.Add(TimeSpan.FromMinutes(AuthTokenOptions.LIFETIME)), signingCredentials: new SigningCredentials(AuthTokenOptions.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256)); var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); var response = new TokenResponse { Access_token = encodedJwt, Username = claimsIdentity.Name, PersonInfoId = user.PersonInfoId, Roles = roles, Start = now, Finish = now.Add(TimeSpan.FromMinutes(AuthTokenOptions.LIFETIME)) }; return(Ok(response)); } ModelState.AddModelError("Password", "Wrong password"); return(BadRequest(ModelState)); } ModelState.AddModelError("UserName", "User with such UserName doesn't exist"); return(BadRequest(ModelState)); } catch (Exception ex) { throw; } }
public TokenController(AuthTokenOptions tokenOptions, UserStorageContext context) { this.tokenOptions = tokenOptions; userContext = context; }
// 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)//(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.RequireHttpsMetadata = false; options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidIssuer = AuthTokenOptions.ISSUER, ValidateAudience = false, ValidateLifetime = true, IssuerSigningKey = AuthTokenOptions.GetSymmetricSecurityKey(), ValidateIssuerSigningKey = true }; }); services.AddDbContext <Steam_InvestContext>(options => { options.UseNpgsql(Configuration.GetConnectionString("DefaultConnection"), b => b.MigrationsAssembly("Steam_Invest.DAL")).UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking); }); services.AddIdentity <AspNetUser, IdentityRole>().AddEntityFrameworkStores <Steam_InvestContext>().AddDefaultTokenProviders(); services.Configure <IdentityOptions>(options => { // Password settings options.Password.RequireDigit = true; options.Password.RequiredLength = 6; options.Password.RequireNonAlphanumeric = false; options.Password.RequireUppercase = false; options.Password.RequireLowercase = false; options.User.RequireUniqueEmail = true; }); services.AddMvc(option => option.EnableEndpointRouting = false); services.AddSpaStaticFiles(configuration => { configuration.RootPath = "ClientApp/build"; }); services.AddTransient <IUnitOfWork, UnitOfWork>(); services.AddControllers(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" }); var basePath = AppContext.BaseDirectory; c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme { Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"", Name = "Authorization", In = ParameterLocation.Header, Type = SecuritySchemeType.ApiKey }); c.AddSecurityRequirement(new OpenApiSecurityRequirement() { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" }, Scheme = "oauth2", Name = "Bearer", In = ParameterLocation.Header, }, new List <string>() } }); }); services.AddControllersWithViews(); services.AddRazorPages(); services.AddTransient <IItemService, ItemService>(); services.AddTransient <IDictionaryService, DictionaryService>(); var config = new AutoMapper.MapperConfiguration(cfg => { cfg.AddProfile <ItemProfile>(); }); var mapper = config.CreateMapper(); services.AddSingleton(mapper); }