public JwtBearerTokenIssuerMiddleware(RequestDelegate next, IOptions <JwtAuthenticationOptions> jwtOptions, IConsumerValidator consumerValidator) { this.next = next; this.jwtOptions = jwtOptions.Value; this.consumerValidator = consumerValidator; }
public static AuthenticationBuilder AddJwtAuthentication(this AuthenticationBuilder authenticationBuilder, Action <JwtAuthenticationOptions> setupAction) { JwtAuthenticationOptions options = new JwtAuthenticationOptions(); setupAction(options); ConfigureServiceOptions(authenticationBuilder, options); authenticationBuilder.Services.AddSingleton <ISigningService, SigningService>(); authenticationBuilder.Services.AddSingleton <IJwtFactory, JwtFactory>(); authenticationBuilder.AddJwtBearer(cfg => { cfg.TokenValidationParameters = new TokenValidationParameters { ValidateAudience = options.ValidateAudience, ValidateIssuer = options.ValidateIssuer, ValidateIssuerSigningKey = options.ValidateIssuerSigningKey, ValidateLifetime = options.ValidateLifetime, ValidIssuer = options.Issuer, ValidAudience = options.Audience, ClockSkew = options.ClockSkew, IssuerSigningKey = authenticationBuilder.Services.BuildServiceProvider().GetService <ISigningService>().SecurityKey }; cfg.SaveToken = true; }); return(new AuthenticationBuilder(authenticationBuilder.Services)); }
private static IServiceCollection ConfigureJwtAuthentication(this IServiceCollection services, JwtAuthenticationOptions jwtAuthenticationOptions) { services .AddSingleton(jwtAuthenticationOptions) .AddAuthentication(a => { a.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; a.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(a => { a.RequireHttpsMetadata = false; a.SaveToken = true; a.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = jwtAuthenticationOptions.GetSymmetricSecurityKey(), ValidateIssuer = false, ValidateAudience = false, ValidIssuer = jwtAuthenticationOptions.Issuer }; }); return(services); }
public TokenGenerator( IOptionsMonitor <JwtAuthenticationOptions> optionsMonitor) { this.configuration = optionsMonitor.CurrentValue; this.securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(this.configuration.JwtSecurityKey)); this.signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256); }
public AuthController(IUserRepository userService, IJwtFactory jwtFactory, IOptions <JwtAuthenticationOptions> jwtOptions, IHttpContextAccessor httpContextAccessor, IConfiguration configuration) : base(configuration) { _userService = userService; _jwtFactory = jwtFactory; _jwtOptions = jwtOptions.Value; _caller = httpContextAccessor.HttpContext.User; _configuration = configuration; }
static OptionsHelpers() { Default = new JwtAuthenticationOptions() { SigningKey = "1234567890123456", Issuer = "honamic", Audience = "any", }; }
public static void ClassInitialize(TestContext context) { var options = new JwtAuthenticationOptions { Keys = TestData.Keys, VerifySignature = true }; _server = CreateServer(options); }
public TaskController(IUserRepository userService, ITaskRepository taskService, ITaskPriorityRepository taskPriorityService, ITaskStatusRepository taskStatusService, IJwtFactory jwtFactory, IOptions <JwtAuthenticationOptions> jwtOptions, IHttpContextAccessor httpContextAccessor, IConfiguration configuration) : base(configuration) { _userService = userService; _jwtFactory = jwtFactory; _jwtOptions = jwtOptions.Value; _caller = httpContextAccessor.HttpContext.User; _configuration = configuration; _taskService = taskService; _taskPriorityService = taskPriorityService; _taskStatusService = taskStatusService; }
public AccountController(IConfiguration config, MasterDbContext masterDbContext , UserManager <ApplicationUser> userManager, SignInManager <ApplicationUser> signInManager , IOptions <JwtAuthenticationOptions> jwtAuthenticationOptions , IOptions <IdentityOptions> identityOptions) { _masterDbContext = masterDbContext; _userManager = userManager; _signInManager = signInManager; _jwtAuthenticationOptions = jwtAuthenticationOptions.Value; _identityOptions = identityOptions.Value; }
static TokenValidationParameters CreateTokenValidationParameters(JwtAuthenticationOptions options) { options = options ?? JwtAuthenticationOptions.Load(ConfigurationManager.AppSettings); var validationParameters = new TokenValidationParameters { ValidIssuer = options.IssuerName, IssuerSigningToken = new BinarySecretSecurityToken(options.PresharedKey), AudienceValidator = delegate { return(true); } }; return(validationParameters); }
/// <summary> /// This method must be called first /// </summary> private void AddOptions(IServiceCollection services) { var jwtAuthenticationConfigSection = Configuration.GetSection(ConstConfigurationOption.JWT_AUTH); this.JwtAuthOptions = jwtAuthenticationConfigSection.Get <JwtAuthenticationOptions>(); services.Configure <JwtAuthenticationOptions>(jwtAuthenticationConfigSection); services.Configure <IdentityOptions>(Configuration.GetSection(ConstConfigurationOption.IDENTITY)); services.Configure <CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); }
public void ConfigureServices(IServiceCollection services) { services.AddMvc(config => { var policy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .Build(); config.Filters.Add(new AuthorizeFilter(policy)); }) .AddJsonOptions(opt => { opt.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; opt.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented; opt.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); }); JwtAuthenticationOptions.Configure(services, Configuration); services.AddScoped <DataContext, DataContext>(); services.AddTransient <IUow, Uow>(); services.AddTransient <IUserRepository, UserRepository>(); services.AddTransient <IUserService, UserService>(); services.AddTransient <IEmailService, EmailService>(); services.AddTransient <IPatientService, PatientService>(); services.AddTransient <IPatientRepository, PatientRepository>(); services.AddTransient <IDoctorService, DoctorService>(); services.AddTransient <IDoctorRepository, DoctorRepository>(); services.AddTransient <ISecretaryService, SecretaryService>(); services.AddTransient <ISecretaryRepository, SecretaryRepository>(); services.AddTransient <ITypeConsultRepository, TypeConsultRepository>(); services.AddTransient <ITypeConsultService, TypeConsultService>(); services.AddTransient <IScheduleRepository, ScheduleRepository>(); services.AddTransient <IScheduleService, ScheduleService>(); services.AddSwaggerDocumentation(); services.AddCors(options => { options.AddPolicy("CorsPolicy", builder => builder.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials() .Build()); }); }
private static TestServer CreateServer(JwtAuthenticationOptions configureOptions) { var builder = new WebHostBuilder() .Configure(app => { app.UseAuthentication(); app.Use(async(context, next) => { var authenticationResult = await context.AuthenticateAsync(); if (authenticationResult.Succeeded) { context.Response.StatusCode = (int)HttpStatusCode.OK; context.Response.ContentType = new ContentType("text/json").MediaType; await context.Response.WriteAsync("Hello"); } else { await context.ChallengeAsync(); } }); }) .ConfigureServices(services => { services.AddSingleton <IAlgorithmFactory, HMACSHAAlgorithmFactory>(); services.AddAuthentication(options => { // Prevents from System.InvalidOperationException: No authenticationScheme was specified, and there was no DefaultAuthenticateScheme found. options.DefaultAuthenticateScheme = JwtAuthenticationDefaults.AuthenticationScheme; // Prevents from System.InvalidOperationException: No authenticationScheme was specified, and there was no DefaultChallengeScheme found. options.DefaultChallengeScheme = JwtAuthenticationDefaults.AuthenticationScheme; }) .AddJwt(options => { options.Keys = configureOptions.Keys; options.VerifySignature = configureOptions.VerifySignature; }); }); return(new TestServer(builder)); }
public static IServiceCollection AddAPIAuthentication( this IServiceCollection services, JwtAuthenticationOptions configuration) { services .Configure(new Action <JwtAuthenticationOptions>(options => { options.JwtAudience = configuration.JwtAudience; options.JwtExpiryInMinutes = configuration.JwtExpiryInMinutes; options.JwtIssuer = configuration.JwtIssuer; options.JwtSecurityKey = configuration.JwtSecurityKey; })) .AddScoped <ITokenGenerator, TokenGenerator>() .AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(options => { options.Events = new JwtBearerEvents() { OnForbidden = context => Task.CompletedTask, OnAuthenticationFailed = context => Task.CompletedTask, }; options.RequireHttpsMetadata = false; options.SaveToken = true; options.TokenValidationParameters = new TokenValidationParameters() { // 修正过期时间偏移 ClockSkew = TimeSpan.Zero, ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = configuration.JwtIssuer, ValidAudience = configuration.JwtAudience, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration.JwtSecurityKey)) }; }); return(services); }
private static async Task <JwtAuthenticationHandler> CreateHandler(string header) { var serializer = new JsonNetSerializer(); var dateTimeProvider = new UtcDateTimeProvider(); var urlEncoder = new JwtBase64UrlEncoder(); var jwtValidator = new JwtValidator(serializer, dateTimeProvider); var decoder = new JwtDecoder(serializer, jwtValidator, urlEncoder, new HMACSHA256Algorithm()); var options = new JwtAuthenticationOptions { Keys = TestData.Secrets, VerifySignature = true }; var optionsMonitor = new Mock <IOptionsMonitor <JwtAuthenticationOptions> >(); optionsMonitor.Setup(m => m.Get(It.IsAny <string>())).Returns(options); var loggerFactory = new NullLoggerFactory(); var encoder = UrlEncoder.Default; var clock = new SystemClock(); var handler = new JwtAuthenticationHandler(decoder, optionsMonitor.Object, loggerFactory, encoder, clock); var scheme = new AuthenticationScheme(JwtAuthenticationDefaults.AuthenticationScheme, JwtAuthenticationDefaults.AuthenticationScheme, typeof(JwtAuthenticationHandler)); var context = new DefaultHttpContext { Request = { Headers = { { HeaderNames.Authorization, header } } } }; await handler.InitializeAsync(scheme, context); return(handler); }
public CustomJwtAuthenticationProvider(IOptions <JwtAuthenticationOptions> jwtAuthOptions) { _jwtAuthOptions = jwtAuthOptions.Value; }
private static void ConfigureServiceOptions(AuthenticationBuilder authenticationBuilder, JwtAuthenticationOptions options) { authenticationBuilder.Services.Configure <JwtTokenOptions>(cfg => { cfg.Issuer = options.Issuer; cfg.Audience = options.Audience; cfg.ExpiresInSeconds = options.ExpiresInSeconds; cfg.IssuedAt = DateTime.Now; cfg.NotBefore = DateTime.Now; }); authenticationBuilder.Services.Configure <SigningOptions>(cfg => { cfg.SALT_KEY = options.SALT_KEY; }); }
public static IAppBuilder UseJwtAuthentication(this IAppBuilder app, JwtAuthenticationOptions options) { return(app.Use <JwtAuthenticationMiddleware>(options)); }
public AuthorizationPolicyProvider(IOptions <AuthorizationOptions> options, IConfiguration configuration, IOptions <JwtAuthenticationOptions> jwtOptions) : base(options) { _options = options.Value; _configuration = configuration; _jwtOptions = jwtOptions.Value; }