public async Task <ActionResult <UserViewModel> > Login(string email, string password) { var user = await _userService.LoginUser(email, password); if (user == null) { return(BadRequest(new { errorText = "Invalid username or password." })); } var now = DateTime.UtcNow; var jwt = new JwtSecurityToken( issuer: JwtAuthOptions.ISSUER, audience: JwtAuthOptions.AUDIENCE, notBefore: now, expires: now.Add(TimeSpan.FromMinutes(JwtAuthOptions.LIFETIME)), signingCredentials: new SigningCredentials(JwtAuthOptions.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256)); var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); var response = new { access_token = encodedJwt, username = _mapper.Map <UserViewModel>(user), }; return(Ok(response)); }
public IActionResult Token(string login, string password) { //TODO: INCRIPTING FUNK var passHash = login; var user = _plansDbContext.Users.FirstOrDefault(u => u.Login == login && u.PasswordHash == u.PasswordHash); if (user == null) { return(BadRequest(new { errorText = "Invalid username or password." })); } var claims = new List <Claim> { new Claim(ClaimsIdentity.DefaultNameClaimType, user.Login) }; var now = DateTime.UtcNow; //TODO: ADD Factory to JwtSecurityToken var jwt = new JwtSecurityToken( issuer: JwtAuthOptions.ISSUER, audience: JwtAuthOptions.AUDIENCE, notBefore: now, claims: claims, expires: now.Add(TimeSpan.FromMinutes(JwtAuthOptions.LIFETIME)), signingCredentials: new SigningCredentials( JwtAuthOptions.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256) ); var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); return(Content(encodedJwt)); }
public static IServiceCollection AddJwtAuth(this IServiceCollection services, Action <JwtAuthOptions> optionsAction) { var jwtAuthOptions = new JwtAuthOptions(); optionsAction(jwtAuthOptions); services .AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters() { ValidIssuer = jwtAuthOptions.Issuer, ValidAudience = jwtAuthOptions.Audience, IssuerSigningKey = jwtAuthOptions.GetSymmetricSecurityKey(), ValidateIssuer = true, ValidateAudience = true, ValidateIssuerSigningKey = true, ValidateLifetime = true }; }); services.AddSingleton(jwtAuthOptions); services.AddScoped <IHashService, BCryptHashService>(); services.AddScoped <IAuthService, JwtAuthService>(); return(services); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddDbContext <PortfolioContext>(); services.AddScoped <IUserRepository, UserRepository>(); services.AddScoped <ISkillAppRepository, SkillAppRepository>(); services.AddScoped <IProtfolioService, PortfolioService>(); services.AddScoped <IUserService, UserService>(); services.AddSwaggerGen(); services.AddAutoMapper(typeof(Startup)); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.RequireHttpsMetadata = false; options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidIssuer = JwtAuthOptions.ISSUER, ValidateAudience = true, ValidAudience = JwtAuthOptions.AUDIENCE, ValidateLifetime = true, IssuerSigningKey = JwtAuthOptions.GetSymmetricSecurityKey(), ValidateIssuerSigningKey = true, }; }); services.AddControllers(); }
public JwtAccessTokenFactory(IOptions <JwtAuthOptions> options) { _authOptions = options.Value; if (_authOptions.SecretKey is null) { throw new ArgumentNullException(nameof(_authOptions.SecretKey)); } }
/// <summary> /// Creates POST body with form data encoding to simulate a form authentication. /// </summary> /// <remarks><para>Other implementation could use JSON instead.</para> /// <para>This is only called in case a POST request is performed as requested in the authentication /// options <see cref="JwtAuthOptions"/>.</para> /// <code> /// var json = JsonConvert.SerializeObject(new JsonObject() /// { /// {"grant_type", "password"}, /// {"username", authOptions?.Username}, /// {"password", authOptions?.Password} /// }); /// /// return new StringContent(json, Encoding.UTF8, "application/json"); /// </code> /// </remarks> /// <param name="authOptions">The authentication options usable to create the request body.</param> /// <returns></returns> protected virtual HttpContent CreatePostContent(JwtAuthOptions authOptions) { return(new FormUrlEncodedContent(new Dictionary <string, string>() { { "grant_type", "password" }, { "username", authOptions?.Username }, { "password", authOptions?.Password } })); }
public JwtAuthenticatorImpl( ISyncTargetAuthenticationDatabaseProvider <SyncTargetAuthenticationDatabaseModel> syncTargetAuthenticationDatabaseProvider, JwtAuthOptions authOptions, IServiceProvider serviceProvider, ILogger <JwtAuthenticatorImpl> logger) { _syncTargetAuthenticationDatabaseProvider = syncTargetAuthenticationDatabaseProvider; _serviceProvider = serviceProvider; _logger = logger; AuthenticationOptions = authOptions; }
// This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.RequireHttpsMetadata = false; options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidIssuer = JwtAuthOptions.ISSUER, ValidateAudience = true, ValidAudience = JwtAuthOptions.AUDIENCE, ValidateLifetime = true, ValidateIssuerSigningKey = true, IssuerSigningKey = JwtAuthOptions.GetSymmetricSecurityKey() }; }); services.AddTransient <PlansDbContext>(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { string connection = Configuration.GetConnectionString("DefaultConnection"); services.AddDbContext <CustomDbContext>(options => options.UseSqlServer(connection)); //Configuration for Identity services.Configure <IdentityOptions>(options => { // Password settings. options.Password.RequireDigit = false; options.Password.RequireLowercase = false; options.Password.RequireNonAlphanumeric = false; options.Password.RequireUppercase = false; options.Password.RequiredLength = 1; options.Password.RequiredUniqueChars = 1; // Lockout settings. options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5); options.Lockout.MaxFailedAccessAttempts = 5; options.Lockout.AllowedForNewUsers = true; // User settings. options.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+"; options.User.RequireUniqueEmail = true; }); services.AddIdentity <User, Role>() .AddEntityFrameworkStores <CustomDbContext>() .AddDefaultTokenProviders(); //todo Dependency injections match here services.AddScoped <IAccountService, AccountService>(); services.AddScoped <IAuthenticateService, AuthenticateService>(); services.AddScoped <IEmailService, GmailService>(); //Todo extract into new section IConfigurationSection section = Configuration.GetSection(JwtAuthOptions.SectionName); JwtAuthOptions.AUDIENCE = section["AUDIENCE"]; JwtAuthOptions.ISSUER = section["ISSUER"]; JwtAuthOptions.KEY = section["KEY"]; JwtAuthOptions.LIFETIME = int.Parse(section["LIFETIME"]); 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 = JwtAuthOptions.ISSUER, ValidateAudience = true, ValidAudience = JwtAuthOptions.AUDIENCE, ValidateLifetime = true, IssuerSigningKey = JwtAuthOptions.GetSymmetricSecurityKey(), ValidateIssuerSigningKey = true, }; }); services.AddControllers(); }
public static void AddKioskBrainsApplication( this IServiceCollection services, WafHostEnum wafHost, IConfiguration configuration) { Assure.ArgumentNotNull(configuration, nameof(configuration)); JsonDefaultSettings.Initialize(); // Settings services.Configure <EkSearchSettings>(configuration.GetSection("EkSearchSettings")); // Memory Cache services.AddMemoryCache(); // Persistent Cache services.AddScoped <IPersistentCache, DbPersistentCache>(); // DB Context services.AddDbContextPool <KioskBrainsContext>(options => options .UseSqlServer(configuration.GetConnectionString("KioskBrainsContext")) .ConfigureWarnings(warnings => warnings.Throw(RelationalEventId.QueryClientEvaluationWarning))); if (wafHost == WafHostEnum.Web) { // Authentication services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidIssuer = JwtAuthOptions.Issuer, ValidateAudience = true, ValidAudience = JwtAuthOptions.Audience, ValidateLifetime = true, ValidateIssuerSigningKey = true, IssuerSigningKey = JwtAuthOptions.GetSymmetricSecurityKey(), }; }); // Add CurrentUser services.AddCurrentUser(); } // WAF services.AddWaf( wafHost, appActionAssemblyNames: AppActionAssemblyNames, appManagerAssemblyNames: AppActionAssemblyNames); // Integration Log services.AddTransient <IIntegrationLogManager, IntegrationLogManager>(); // Notifications services.Configure <NotificationManagerSettings>(configuration.GetSection("NotificationManagerSettings")); services.AddScoped <INotificationManager, NotificationManagerStub>(); //Repo and services services.AddScoped <ITranslateService, TranslateService>(); services.AddScoped <IReadOnlyRepository, ReadOnlyRepository <KioskBrainsContext> >(); services.AddScoped <IWriteOnlyRepository, WriteOnlyRepository <KioskBrainsContext> >(); // Common Clients services.Configure <KioskProxyClientSettings>(configuration.GetSection("KioskProxyClientSettings")); services.AddScoped <KioskProxyClient>(); services.Configure <AzureStorageSettings>(configuration.GetSection("AzureStorageSettings")); services.AddScoped <AzureStorageClient>(); }
public JwtAuthService(UserRepository userRepository, IHashService hashService, JwtAuthOptions jwtAuthOptions) { _userRepository = userRepository; _hashService = hashService; _jwtAuthOptions = jwtAuthOptions; }
public JwtFactory(JwtOptions jwtOptions, JwtAuthOptions jwtAuthOptions, JwtSecurityTokenHandler jwtHandler) { _jwtHandler = jwtHandler; _jwtAuthOptions = jwtAuthOptions; _jwtOptions = jwtOptions; }