private string GenerateToken(UserDto user) { var claims = new List <Claim> { new Claim(nameof(UserDto.UserId), user.UserId), new Claim(ClaimTypes.Name, user.Email), new Claim(ClaimTypes.Role, user.Role), new Claim(JwtRegisteredClaimNames.Nbf, new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds().ToString()), new Claim(JwtRegisteredClaimNames.Exp, new DateTimeOffset(DateTime.Now.AddDays(1)).ToUnixTimeSeconds().ToString()), }; if (user.FacilityId.HasValue) { claims.Add(new Claim(nameof(UserDto.FacilityId), user.FacilityId.Value.ToString())); } if (user.DoctorId.HasValue) { claims.Add(new Claim(nameof(UserDto.DoctorId), user.DoctorId.Value.ToString())); } var token = new JwtSecurityToken( new JwtHeader(new SigningCredentials( AuthenticationOptions.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256)), new JwtPayload(claims)); return(new JwtSecurityTokenHandler().WriteToken(token)); }
public IActionResult Post([FromBody] AuthenticationDto model) { UserModel user; try { user = _userRepository.GetUser(model.UserName, model.Password); } catch (UserRepositoryException e) { return(Unauthorized(e.Message)); } var identity = AuthenticationHelper.GetIdentity(user, model.Password); var now = DateTime.UtcNow; var jwt = new JwtSecurityToken( issuer: AuthenticationOptions.ISSUER, audience: AuthenticationOptions.AUDIENCE, notBefore: now, claims: identity, expires: now.Add(TimeSpan.FromMinutes(AuthenticationOptions.LIFETIME)), signingCredentials: new SigningCredentials(AuthenticationOptions.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256)); var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); var response = new { access_token = encodedJwt, timeOut = AuthenticationOptions.LIFETIME, userName = user.UserName, roleId = user.Role.Id }; return(Ok(response)); }
public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddScoped <IRepositoryContextFactory, RepositoryContextFactory>(); services.AddDbContext <RepositoryContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); services.AddScoped <IUserRepository>(provider => new UserRepository(Configuration.GetConnectionString("DefaultConnection"), provider.GetService <IRepositoryContextFactory>())); services.AddScoped <ITestRepository>(provider => new TestRepository(Configuration.GetConnectionString("DefaultConnection"), provider.GetService <IRepositoryContextFactory>())); services.AddScoped <IQuestionRepository>(provider => new QuestionRepository(Configuration.GetConnectionString("DefaultConnection"), provider.GetService <IRepositoryContextFactory>())); services.AddScoped <IAssignmentsRepository>(provider => new AssignmentsRepository(Configuration.GetConnectionString("DefaultConnection"), provider.GetService <IRepositoryContextFactory>())); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.RequireHttpsMetadata = false; options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidIssuer = AuthenticationOptions.ISSUER, ValidateAudience = true, ValidAudience = AuthenticationOptions.AUDIENCE, ValidateLifetime = true, IssuerSigningKey = AuthenticationOptions.GetSymmetricSecurityKey(), ValidateIssuerSigningKey = true, }; 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("/chat"))) { context.Token = accessToken; } return(Task.CompletedTask); } }; }); services.AddLogging(loggingBuilder => { loggingBuilder.AddConfiguration(Configuration.GetSection("Logging")); loggingBuilder.AddConsole(); loggingBuilder.AddDebug(); }); }
private string GenerateToken(string username) { var claims = new[] { new Claim(ClaimTypes.Name, username), new Claim(JwtRegisteredClaimNames.Nbf, new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds().ToString()), new Claim(JwtRegisteredClaimNames.Exp, new DateTimeOffset(DateTime.Now.AddDays(1)).ToUnixTimeSeconds().ToString()), }; var token = new JwtSecurityToken( new JwtHeader(new SigningCredentials( AuthenticationOptions.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256)), new JwtPayload(claims)); return(new JwtSecurityTokenHandler().WriteToken(token)); }
public IActionResult RefreshToken() { var userName = Request.Form["userName"].ToString(); var userRole = Request.Form["userRole"].ToString(); if (userName == null) { return(null); } var claims = new List <Claim> { new Claim(ClaimsIdentity.DefaultNameClaimType, userName), new Claim(ClaimsIdentity.DefaultRoleClaimType, userRole) }; ClaimsIdentity identity = new ClaimsIdentity(claims, "Token", ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType); var now = DateTime.UtcNow; AuthenticationOptions opt = new AuthenticationOptions(); // создаем JWT-токен var jwt = new JwtSecurityToken( issuer: opt.ISSUER, audience: opt.AUDIENCE, notBefore: now, claims: identity.Claims, expires: now.Add(TimeSpan.FromMinutes(opt.LIFETIME)), signingCredentials: new SigningCredentials(opt.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256)); var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); var response = new { token = encodedJwt, username = identity.Name, }; return(Ok(response)); }
public async Task <IActionResult> LoginAsync([FromBody] User user) { var username = user.Name_text; var password = user.Password_text; var identity = await this.GetUserWithIdentity(username, password); if (identity == null) { Response.StatusCode = 400; return(BadRequest()); } var now = DateTime.UtcNow; AuthenticationOptions opt = new AuthenticationOptions(); // создаем JWT-токен var jwt = new JwtSecurityToken( issuer: opt.ISSUER, audience: opt.AUDIENCE, notBefore: now, claims: identity.Claims, expires: now.Add(TimeSpan.FromMinutes(opt.LIFETIME)), signingCredentials: new SigningCredentials(opt.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256)); var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); var claimsOfUser = identity.Claims; var roleClaimType = identity.RoleClaimType; var roles = claimsOfUser.Where(c => c.Type == ClaimTypes.Role).ToList(); var roleValue = roles[0].Value; var response = new { token = encodedJwt, username = identity.Name, role = roleValue }; return(Ok(response)); }
public async Task <LoginResultModel> UpdateTokens(string userId) { var user = await _database.UserRepostitory.GetUser(userId); DateTime timeNow = DateTime.UtcNow; UserModel userModel = _mapper.Map <UserModel>(user); userModel.Role = _database.UserRepostitory.GetRole(user); var tokenHandler = new JwtSecurityTokenHandler(); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, userModel.Id.ToString()), new Claim(ClaimTypes.Role, userModel.Role) }), Issuer = AuthenticationOptions.ISSUER, Audience = AuthenticationOptions.AUDIENCE, NotBefore = timeNow, Expires = timeNow.Add(TimeSpan.FromMinutes(AuthenticationOptions.LIFETIME)), SigningCredentials = new SigningCredentials(AuthenticationOptions.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256Signature) }; var jwt = tokenHandler.CreateToken(tokenDescriptor); var refreshToken = TokenGenerator.Generate().Trim(); LoginResultModel result = new LoginResultModel(); result.User = userModel; result.AccessToken = tokenHandler.WriteToken(jwt); result.RefreshToken = refreshToken; _database.UserRepostitory.SetRefreshToken(user, refreshToken); return(result); }
// This method gets called by the runtime. Use this method to add services to the container. // ReSharper disable once UnusedMember.Global public void ConfigureServices(IServiceCollection services) { services.ConfigureOptions(Configuration, typeof(NethereumOptions), typeof(AuthenticationOptions), typeof(SiteOptions), typeof(SmtpOptions), typeof(AzureStorageOptions)); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "SmartValley API", Version = "v1" }); }); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.RequireHttpsMetadata = _currentEnvironment.IsProduction(); options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidIssuer = AuthenticationOptions.Issuer, ValidateAudience = true, ValidAudience = AuthenticationOptions.Audience, ValidateLifetime = false, IssuerSigningKey = AuthenticationOptions.GetSymmetricSecurityKey(), ValidateIssuerSigningKey = true }; }); services.AddSingleton(provider => InitializeWeb3(provider.GetService <NethereumOptions>().RpcAddress)); services.AddSingleton <IClock, UtcClock>(); services.AddSingleton <EthereumMessageSigner>(); services.AddSingleton <EthereumClient>(); services.AddSingleton <EthereumContractClient>(); services.AddSingleton <MailService>(); services.AddSingleton <MailTokenService>(); services.AddSingleton <MailSender>(); services.AddSingleton <ITemplateProvider, TemplateProvider>(provider => new TemplateProvider(_currentEnvironment.ContentRootPath)); services.AddSingleton(InitializeProjectTeamMembersStorageProvider); services.AddSingleton(InitializeApplicationTeamMembersStorageProvider); services.AddSingleton(InitializeExpertApplicationsStorageProvider); services.AddSingleton(InitializeProjectStorageProvider); services.AddSingleton <IScoringContractClient, ScoringContractClient>( provider => new ScoringContractClient(provider.GetService <EthereumContractClient>(), provider.GetService <NethereumOptions>().ScoringContract)); services.AddSingleton <IERC223ContractClient, ERC223ContractClient>( provider => new ERC223ContractClient(provider.GetService <EthereumContractClient>(), provider.GetService <NethereumOptions>().ERC223Contract)); services.AddSingleton <IEtherManagerContractClient, EtherManagerContractClient>( provider => new EtherManagerContractClient(provider.GetService <EthereumContractClient>(), provider.GetService <NethereumOptions>().EtherManagerContract)); services.AddSingleton <IScoringsRegistryContractClient, ScoringsRegistryContractClient>( provider => new ScoringsRegistryContractClient(provider.GetService <EthereumContractClient>(), provider.GetService <NethereumOptions>().ScoringsRegistryContract)); services.AddSingleton <IScoringOffersManagerContractClient, ScoringOffersManagerContractClient>( provider => new ScoringOffersManagerContractClient(provider.GetService <EthereumContractClient>(), provider.GetService <NethereumOptions>().ScoringOffersManagerContract)); services.AddSingleton <IAllotmentEventsManagerContractClient, AllotmentEventsManagerContractClient>( provider => new AllotmentEventsManagerContractClient(provider.GetService <EthereumContractClient>(), provider.GetService <NethereumOptions>().AllotmentEventsManagerContract)); services.AddSingleton <IAllotmentEventContractClient, AllotmentEventContractClient>( provider => new AllotmentEventContractClient(provider.GetService <EthereumContractClient>(), provider.GetService <NethereumOptions>().AllotmentEventContract.Abi)); services.AddMemoryCache(); services.AddMvc(options => { options.Filters.Add(new AuthenticationFilterFactory()); options.Filters.Add(new AppErrorsExceptionFilter()); options.Filters.Add(new ModelStateFilter()); }); var builder = new DbContextOptionsBuilder <AppDBContext>(); builder.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")); var dbOptions = builder.Options; services.AddDbContext <AppDBContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); services.AddTransient(x => AppDBContext.CreateEditable(dbOptions)); services.AddTransient(x => AppDBContext.CreateReadOnly(dbOptions)); services.AddTransient <IProjectRepository, ProjectRepository>(); services.AddTransient <IScoringRepository, ScoringRepository>(); services.AddTransient <IScoringOffersRepository, ScoringOffersRepository>(); services.AddTransient <IProjectService, ProjectService>(); services.AddTransient <IEstimationService, EstimationService>(); services.AddTransient <IScoringService, ScoringService>(); services.AddTransient <IScoringCriterionRepository, ScoringCriterionRepository>(); services.AddTransient <IUserRepository, UserRepository>(); services.AddTransient <IUserService, UserService>(); services.AddTransient <IAdminService, AdminService>(); services.AddTransient <IUserRepository, UserRepository>(); services.AddTransient <IAuthenticationService, AuthenticationService>(); services.AddTransient <IExpertRepository, ExpertRepository>(); services.AddTransient <IExpertService, ExpertService>(); services.AddTransient <Experts.IExpertService, Experts.ExpertService>(); services.AddTransient <IExpertApplicationRepository, ExpertApplicationRepository>(); services.AddTransient <ICountryRepository, CountryRepository>(); services.AddTransient <IExpertApplicationRepository, ExpertApplicationRepository>(); services.AddTransient <IScoringApplicationRepository, ScoringApplicationRepository>(); services.AddTransient <IScoringApplicationQuestionsRepository, ScoringApplicationQuestionsRepository>(); services.AddTransient <IScoringApplicationService, ScoringApplicationService>(); services.AddTransient <IFeedbackRepository, FeedbackRepository>(); services.AddTransient <IFeedbackService, FeedbackService>(); services.AddTransient <IAllotmentEventService, AllotmentEventService>(); services.AddTransient <IAllotmentEventRepository, AllotmentEventRepository>(); services.AddTransient <IEthereumTransactionService, EthereumTransactionService>(); services.AddTransient <IEthereumTransactionRepository, EthereumTransactionRepository>(); var logger = CreateLogger(); services.AddSingleton(logger.ForContext("Source", "api")); var serviceProvider = services.BuildServiceProvider(); var siteOptions = serviceProvider.GetService <SiteOptions>(); ConfigureCorsPolicy(services, siteOptions); var dataProtectionProvider = serviceProvider.GetService <IDataProtectionProvider>(); services.AddSingleton <IMessageSession>( provider => EndpointConfigurator .StartAsync(Configuration, _currentEnvironment.ContentRootPath, dataProtectionProvider, logger.ForContext("Source", "nservicebus")) .GetAwaiter() .GetResult()); }
/// <summary> /// This method gets called by the runtime.Use this method to add services to the container. /// </summary> /// <param name="services"></param> public void ConfigureServices(IServiceCollection services) { ///Как идея использовать класс, который видно во всех методах. //var connectionString = Configuration.GetConnectionString("db_connection"); var connectionString = Settings.GetStringDB(); services.AddSingleton <ISettings>(provider => new Settings(connectionString)); services.AddSingleton <SettingsModel>(provider => new SettingsModelService().DeserializeFromDefaultLocation()); // TODO нужно будет переделать все классы под этот вариант services.AddScoped <IFilesRepository>(provider => new FilesRepository(connectionString)); services.AddScoped <IGlossaryRepository>(provider => new GlossaryRepository(connectionString)); services.AddScoped <IGlossariesRepository>(provider => new GlossariesRepository(connectionString)); services.AddScoped <ITranslationSubstringRepository>(provider => new TranslationSubstringRepository(connectionString)); services.AddScoped <ITranslationTroubleRepository>(provider => new TranslationTroubleRepository(connectionString)); services.AddScoped <ILocaleRepository>(provider => new LocaleRepository(connectionString)); services.AddScoped <IUserActionRepository>(provider => new UserActionRepository(connectionString)); services.AddScoped <IMail>(provider => new EMail()); services.AddScoped <ITranslationMemoryRepository>(provider => new TranslationMemoryRepository(connectionString)); services.AddScoped <IInvitationsRepository>(provider => new InvitationsRepository(connectionString)); services.AddScoped <IUserRepository>(provider => new UserRepository(connectionString)); services.AddScoped <IParticipantRepository>(provider => new ParticipantRepository(connectionString)); services.AddScoped <IImagesRepository>(provider => new ImageRepository(connectionString)); services.AddScoped <IProjectTranslationMemoryRepository>(provider => new ProjectTranslationMemoryRepository(connectionString)); services.AddScoped <IFilesPackagesRepository>(provider => new FilesPackagesRepository(connectionString)); services.AddScoped <ITranslationTopicRepository>(provider => new TranslationTopicRepository(connectionString)); services.AddScoped <ITypeOfServiceRepository>(provider => new TypeOfServiceRepository(connectionString)); services.AddScoped <FromExcel>(); services.AddScoped <FilesService>(); services.AddScoped <GlossaryService>(); services.AddScoped <GlossariesService>(); services.AddScoped <UserAction>(); services.AddScoped <TranslationMemoryService>(); services.AddScoped <InvitationsService>(); ////Данный блок кода включает доступ к серверу с любого порта(нужен для тестирования с нескольких клиентов)/////// var corsBuilder = new CorsPolicyBuilder(); corsBuilder.AllowAnyHeader(); corsBuilder.AllowAnyMethod(); corsBuilder.AllowAnyOrigin(); // For anyone access. //corsBuilder.WithOrigins("http://localhost:56573"); // for a specific url. Don't add a forward slash on the end! corsBuilder.AllowCredentials(); services.AddCors(options => { options.AddPolicy("SiteCorsPolicy", corsBuilder.Build()); }); //////////////Данный блок заканчивается ///2. авторизация services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.RequireHttpsMetadata = false; AuthenticationOptions opt = new AuthenticationOptions(); options.TokenValidationParameters = new TokenValidationParameters { // укзывает, будет ли валидироваться издатель при валидации токена ValidateIssuer = true, // строка, представляющая издателя ValidIssuer = opt.ISSUER, // будет ли валидироваться потребитель токена ValidateAudience = true, // установка потребителя токена ValidAudience = opt.AUDIENCE, // будет ли валидироваться время существования ValidateLifetime = true, // установка ключа безопасности IssuerSigningKey = opt.GetSymmetricSecurityKey(), // валидация ключа безопасности ValidateIssuerSigningKey = true, ClockSkew = TimeSpan.Zero }; }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); // In production, the Angular files will be served from this directory services.AddSpaStaticFiles(configuration => { configuration.RootPath = "ClientApp/dist"; }); //технологии коммуникаций в реальном времени: services.AddSignalR(options => options.EnableDetailedErrors = false); }
public void ConfigureServices(IServiceCollection services) { var path = Directory.GetCurrentDirectory(); //string connectionString = @"Server=(localdb)\mssqllocaldb;Database=productsdb;Trusted_Connection=True;"; string connectionString = $"Data Source=(localdb)\\mssqllocaldb;AttachDbFilename='{path}\\App_Data\\AppDB.mdf';Database=AppDB;Trusted_Connection=True;"; services.DBInit(connectionString); services.AddCors(); var mappingConfig = new MapperConfiguration(mc => { mc.AddProfile(new MappingProfile()); }); IMapper mapper = mappingConfig.CreateMapper(); services.AddSingleton(mapper); services.AddMvc(); services.AddTransient <IProductService, ProductServices>(); services.AddTransient <ICategoryService, CategoryService>(); services.AddTransient <IUserService, UserService>(); services.AddTransient <IAccountService, AccountService>(); services.AddTransient <IOrderService, OrderService>(); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.RequireHttpsMetadata = false; options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidIssuer = AuthenticationOptions.ISSUER, ValidateAudience = true, ValidAudience = AuthenticationOptions.AUDIENCE, ValidateLifetime = true, IssuerSigningKey = AuthenticationOptions.GetSymmetricSecurityKey(), ValidateIssuerSigningKey = true }; options.Events = new JwtBearerEvents { OnAuthenticationFailed = context => { if (context.Exception.GetType() == typeof(SecurityTokenExpiredException)) { context.Response.Headers.Add("Token-Expired", "true"); } return(Task.CompletedTask); } }; }); services.AddAuthorization(options => { options.DefaultPolicy = new AuthorizationPolicyBuilder(JwtBearerDefaults.AuthenticationScheme) .RequireAuthenticatedUser() .Build(); }); }