public async Task <AccessTokenModel> AuthUser(EntityUser user, EntityUserSocialType provider) { var identity = await GetUserIdentity(user, provider); var now = DateTime.UtcNow; var jwt = new JwtSecurityToken( issuer: AuthOptions.ISSUER, audience: AuthOptions.AUDIENCE, claims: identity.Claims, expires: now.Add(TimeSpan.FromMinutes(AuthOptions.LIFETIME)), signingCredentials: new SigningCredentials(AuthOptions.GetKey(), SecurityAlgorithms.HmacSha256)); var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); return(new AccessTokenModel { Token = encodedJwt, Email = user.Email, Expires = jwt.ValidTo.Subtract(now).Ticks, FirstName = user.FirstName, LastName = user.LastName, OAuthProvider = provider.ToString(), ProfileImageUrl = user.PictureUrl }); }
private string GetToken(ClaimsIdentity identity) { var jwt = new JwtSecurityToken ( issuer: AuthOptions.ISSUER, audience: AuthOptions.AUDIENCE, notBefore: DateTime.Now, claims: identity.Claims, expires: DateTime.Now.Add(TimeSpan.FromMinutes(AuthOptions.LIFETIME)), signingCredentials: new SigningCredentials(AuthOptions.GetKey(), SecurityAlgorithms.HmacSha256) ); return(new JwtSecurityTokenHandler().WriteToken(jwt)); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddScoped <IUserStore, UsersStore>(); services.AddSingleton <AuthService>(); services.AddControllers(); var cont = new OpenApiContact { Url = new Uri("https://*****:*****@asd.asd", Name = "Developer" }; var licence = new OpenApiLicense { Name = "APACHE", Url = new Uri("https://localhost:44313/#license") }; services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "WebAPIApp", Version = "v1", Contact = cont, Description = "Test Web API project", TermsOfService = new Uri("https://localhost:44313/#terms"), License = licence }); }); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(opts => { //opts.RequireHttpsMetadata = false; opts.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidIssuer = AuthOptions.ISSUER, ValidateAudience = true, ValidAudience = AuthOptions.AUDIENCE, ValidateLifetime = true, ValidateIssuerSigningKey = true, IssuerSigningKey = AuthOptions.GetKey() }; }); }
public void ConfigureServices(IServiceCollection services) { string connection = Configuration.GetConnectionString("DbConnection"); services.AddDbContext <DataContext>(options => options.UseSqlite(connection)); services.AddMvc(); 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.GetKey(), ValidateIssuerSigningKey = true }; }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddDbContext <ApiDbContext>(options => options.UseMySql(Configuration.GetConnectionString("MySQLConnection"), b => b.MigrationsAssembly("Api"))); ContextSeed(ApiDbContext.CreateFromConnectionString(Configuration.GetConnectionString("MySQLConnection"))); services.AddIdentity <EntityUser, IdentityRole>().AddEntityFrameworkStores <ApiDbContext>(); services.AddAuthentication("Bearer") .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.GetKey(), ValidateIssuerSigningKey = true, }; }); services.AddCors(); services.AddCors((o) => o.AddPolicy("Client", builder => builder .AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials())); services .AddMvc() .AddJsonOptions(jsonOptions => { jsonOptions.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore; }); services.AddAutoMapper(); services.Configure <MvcOptions>(options => { options.Filters.Add(new CorsAuthorizationFilterFactory("Client")); }); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "LR twitter neural api", Version = "v1" }); }); services.AddTransient <ApiUserStore, ApiUserStore>(); services.AddTransient(x => new AppDataModel { FacebookAppId = Configuration["Auth:Facebook:Id"], FacebookAppSecret = Configuration["Auth:Facebook:Secret"], }); services.AddTransient(x => new StorageBlobClient(Configuration["Storage:Blob:ConnectionString"])); services.AddTransient(x => new TwitterClient(Configuration["Auth:Twitter:Key"], Configuration["Auth:Twitter:Secret"], Configuration["Auth:Twitter:RedirectUrl"])); services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>(); services.AddTransient <IPrincipal>(provider => provider.GetService <IHttpContextAccessor>()?.HttpContext?.User); services.AddTransient(x => new VReader(Configuration["neural:vocabulary"])); // stores services.AddTransient <ITwitterCollectionsStore, TwitterCollectionsStore>(); services.AddTransient <ITwitterSourcesStore, TwitterSourcesStore>(); services.AddTransient <IUserSocialsStore, UserSocialsStore>(); services.AddTransient <INeuralStore, NeuralStore>(); services.AddTransient <ITrainSetStore, TrainSetStore>(); // managers services.AddTransient <TrainSetManager>(); services.AddTransient <UserManager, UserManager>(); services.AddTransient <TwitterManager, TwitterManager>(); services.AddTransient <ICollectionsManager, CollectionsManager>(); services.AddTransient <NeuralManager>(); // services services.AddSingleton <IHostedService, CollectionHostedService>(); }
public void ConfigureServices(IServiceCollection services) { //services.AddTransient<IEmailSender, DebugEmailSender>(); services.AddTransient <IEmailSender, MailKitEmailSender>(); services.AddDbContext <ApplicationDbContext>(opts => { //var builder = new SqlConnectionStringBuilder(Configuration.GetConnectionString("DefaultConnection")) //{ // Password = Configuration.GetSection("dbConnection").Value //}; //opts.UseSqlServer(builder.ConnectionString); opts.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")); }); services.AddDatabaseDeveloperPageExceptionFilter(); services.AddIdentity <User, Role>() .AddEntityFrameworkStores <ApplicationDbContext>() .AddDefaultTokenProviders() .AddClaimsPrincipalFactory <TestClaimsFactory>() .AddTokenProvider <DigitsTokenProvider>("Digits"); //.AddTokenProvider<DataProtectorTokenProvider<User>>(TokenOptions.DefaultProvider); services.AddControllersWithViews(); services.AddAuthentication() .AddJwtBearer(opts => { //opts.ForwardDefault = "Identity.Application"; opts.ForwardAuthenticate = "Identity.Application"; opts.TokenValidationParameters = new TokenValidationParameters { ValidateAudience = true, ValidAudience = AuthOptions.AUDIENCE, ValidateIssuer = true, ValidIssuer = AuthOptions.ISSUER, ValidateLifetime = true, ValidateIssuerSigningKey = true, IssuerSigningKey = AuthOptions.GetKey() }; }) .AddGoogle(opts => { IConfigurationSection credentials = Configuration.GetSection("Auth:Google"); opts.ClientId = credentials["ClientId"]; opts.ClientSecret = credentials["ClientSecret"]; }); services.AddAuthorization(opts => { opts.AddPolicy("IsAdmin", policy => { policy.RequireAuthenticatedUser(); policy.RequireUserName("admin"); }); }); services.AddCors(opts => { opts.AddPolicy("cors_test", builder => { builder.WithOrigins("http://localhost:54910"); builder.AllowAnyHeader(); builder.WithMethods("post"); }); }); services.AddSignalR(); services.AddScoped <IAuthorizationHandler, UserManagerAuthorizationHandler>(); services.AddScoped <IAuthorizationHandler, TestAuthHandler>(); services.AddSingleton <IAuthorizationMiddlewareResultHandler, ApiAuthMiddleware>(); services.AddScoped <ISecurityStampValidator, CustomSecurityStampValidator <User> >(); //services.AddDataProtection(); services.Configure <IdentityOptions>(opts => { opts.Password.RequireDigit = false; opts.Password.RequireLowercase = false; opts.Password.RequireUppercase = false; opts.Password.RequireNonAlphanumeric = false; opts.Password.RequiredLength = 6; opts.Password.RequiredUniqueChars = 1; opts.User.RequireUniqueEmail = true; opts.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_"; opts.SignIn.RequireConfirmedAccount = true; opts.Lockout.MaxFailedAccessAttempts = 2; opts.Tokens.ChangeEmailTokenProvider = "Digits"; opts.Tokens.EmailConfirmationTokenProvider = "Email"; opts.Tokens.ChangePhoneNumberTokenProvider = "Phone"; opts.Tokens.PasswordResetTokenProvider = "Authenticator"; }); services.Configure <PasswordHasherOptions>(opts => { opts.IterationCount = 12000; opts.CompatibilityMode = PasswordHasherCompatibilityMode.IdentityV3; }); services.ConfigureApplicationCookie(opts => { opts.Cookie.Name = "IdentityCookie"; }); //Upadte impersonating cookies on cookie refresh services.Configure <SecurityStampValidatorOptions>(opts => { opts.OnRefreshingPrincipal = context => { var originalUserIdClaim = context.CurrentPrincipal.FindFirst("OriginalUserId"); var isImpersonatingClaim = context.CurrentPrincipal.FindFirst("IsImpersonating"); if (isImpersonatingClaim?.Value == true.ToString() && originalUserIdClaim?.Value != null) { context.NewPrincipal.Identities.First().AddClaims(new[] { originalUserIdClaim, isImpersonatingClaim }); } return(Task.CompletedTask); }; //Как часто проверять штамп безопасности (разлогин при смене пароля) opts.ValidationInterval = TimeSpan.FromSeconds(120);//TimeSpan.FromMinutes(30); }); services.Configure <AntiforgeryOptions>(opts => { opts.FormFieldName = "_af"; opts.HeaderName = "H_antiforgery"; //Если true - в ответ на запрос будет передаваться заголовок X-Frame-Options = SAMEORIGIN bool val = opts.SuppressXFrameOptionsHeader; //opts.Cookie.Name = "COOKIE_af"; }); services.Configure <SmtpOptions>(Configuration.GetSection("smtpSettings")); services.Configure <HstsOptions>(opts => { opts.Preload = true; opts.IncludeSubDomains = true; opts.MaxAge = TimeSpan.FromDays(365); }); services.Configure <CookiePolicyOptions>(opts => { opts.CheckConsentNeeded = context => true; opts.MinimumSameSitePolicy = SameSiteMode.None; opts.Secure = CookieSecurePolicy.None; }); }