public AuthManagementController( UserManager <IdentityUser> userManager, IOptionsMonitor <JWTConfig> optionsMonitor) { _userManager = userManager; _jwtConfig = optionsMonitor.CurrentValue; }
public void ConfigureServices(IServiceCollection services) { // important step //services.AddNacosAspNetCore(Configuration); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); #region 读取配置信息 services.AddSingleton <ITokenHelper, TokenHelper>(); services.Configure <JWTConfig>(Configuration.GetSection("JWT")); JWTConfig config = new JWTConfig(); Configuration.GetSection("JWT").Bind(config); #endregion #region 启用JWT services.AddAuthentication(Options => { Options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; Options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }). AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidIssuer = config.Issuer, ValidAudience = config.RefreshTokenAudience, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config.IssuerSigningKey)) }; }); #endregion services.AddIdentityServer()//Ids4服务 .AddDeveloperSigningCredential() .AddInMemoryIdentityResources(Config.GetIdentityResources()) .AddInMemoryClients(Config.GetClients()); //把配置文件的Client配置资源放到内存 }
public AuthController( IOptions <JWTConfig> jwtConfig, IUsuarioServices usuarioServices) { _jwtConfig = jwtConfig.Value; _usuarioServices = usuarioServices; }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { var jwtConfigSection = Configuration.GetSection("JwtSettings"); JWTConfig jWTConfig = jwtConfigSection.Get <JWTConfig>(); jWTConfig.CreateSecurityKey(); services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ClockSkew = TimeSpan.FromMinutes(5), IssuerSigningKey = jWTConfig.SecurityKey, RequireSignedTokens = true, RequireExpirationTime = true, ValidateLifetime = true, ValidateIssuer = true, ValidIssuer = jWTConfig.Issuer, ValidateAudience = true, ValidAudience = jWTConfig.Audience }; }); services.AddDbContext <BackEndContext>(options => { options.UseSqlServer(Configuration.GetConnectionString("DbConnectionString")); }); services.AddControllers(); }
public AuthenticationController(IAuthenticationService authService, IOptions <JWTConfig> jwtConfig, IEmailService emailService) { _userService = authService; _emailService = emailService; this.jwtConfig = jwtConfig.Value; }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { var restApiConfigSection = Configuration.GetSection("RestApiConfig"); RestApiConfig restApiConfig = restApiConfigSection.Get <RestApiConfig>(); services.AddSingleton(restApiConfig); var blobStorageConfigSection = Configuration.GetSection("BlobStorageConfig"); BlobStorageConfig blobStorageConfig = blobStorageConfigSection.Get <BlobStorageConfig>(); services.AddSingleton(blobStorageConfig); var jwtConfigSection = Configuration.GetSection("JwtSettings"); JWTConfig jWTConfig = jwtConfigSection.Get <JWTConfig>(); jWTConfig.CreateSecurityKey(); services.AddSingleton(jWTConfig); // https://code-maze.com/create-pdf-dotnetcore/ services.AddSingleton(typeof(IConverter), new SynchronizedConverter(new PdfTools())); // https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-3.1#basic-usage services.AddHttpClient(); services.AddScoped <ServiceRepository>(); services.AddDbContext <FrontEndContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DbConnectionString"))); services.AddDefaultIdentity <FrontEndUser>(options => options.SignIn.RequireConfirmedAccount = false) .AddRoles <IdentityRole>() .AddEntityFrameworkStores <FrontEndContext>(); services.AddRazorPages(); services.AddControllersWithViews(); }
public UserRepository(UserManager <AppUser> _userManager, IOptions <JWTConfig> _jwtsettings /*, SignInManager<ApplicationUser> _signInManager*/) { userManager = _userManager; //signInManager = _signInManager; jwtsettings = _jwtsettings.Value; }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { RegisterHealthChecks(services, Configuration.GetConnectionString("DefaultConnection")); services.RegisterRepositoryServices(); //auto mapper start AutoMapperConfig.RegisterMappings(); services.AddMvc() .AddJsonOptions(options => { options.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore; }) .SetCompatibilityVersion(CompatibilityVersion.Version_2_2); services.Configure <ImageSettings>(options => Configuration.GetSection("ImageSettings").Bind(options)); services.Configure <EmailSettings>(options => Configuration.GetSection("EmailSettings").Bind(options)); services.Configure <ServerSettings>(options => Configuration.GetSection("ServerSettings").Bind(options)); services.Configure <NotificationSettings>(options => Configuration.GetSection("NotificationSettings").Bind(options)); JWTConfig.RegisterJWT(services, Configuration); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "SHAREBOOK API", Version = "v1" }); c.ResolveConflictingActions(x => x.First()); 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>() }, }); }); services.AddCors(options => { options.AddPolicy("AllowAllHeaders", builder => { builder.AllowAnyOrigin() .AllowAnyHeader() .AllowAnyMethod(); }); }); services.AddDbContext <ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); RollbarConfigurator.Configure(Configuration.GetSection("RollbarEnvironment").Value); MuambatorConfigurator.Configure(Configuration.GetSection("Muambator:Token").Value, Configuration.GetSection("Muambator:IsActive").Value); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.RegisterRepositoryServices(); //auto mapper start AutoMapperConfig.RegisterMappings(); services.AddMvc(); services.Configure <EmailSettings>(options => Configuration.GetSection("EmailSettings").Bind(options)); JWTConfig.RegisterJWT(services, Configuration); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "SHAREBOOK API", Version = "v1" }); 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>() }, }); }); services.AddDbContext <ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); }
public void ConfigureServices(IServiceCollection services) { RegisterHealthChecks(services, Configuration.GetConnectionString("DefaultConnection")); services.RegisterRepositoryServices(); services.AddAutoMapper(typeof(Startup)); services .AddControllers() .AddJsonOptions(options => { options.JsonSerializerOptions.IgnoreNullValues = true; options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()); }).AddNewtonsoftJson(); services .AddHttpContextAccessor() .Configure <RollbarOptions>(options => Configuration.GetSection("Rollbar").Bind(options)) .AddRollbarLogger(loggerOptions => loggerOptions.Filter = (loggerName, loglevel) => loglevel >= LogLevel.Trace); services.Configure <ImageSettings>(options => Configuration.GetSection("ImageSettings").Bind(options)); services.Configure <EmailSettings>(options => Configuration.GetSection("EmailSettings").Bind(options)); services.Configure <ServerSettings>(options => Configuration.GetSection("ServerSettings").Bind(options)); services.Configure <NotificationSettings>(options => Configuration.GetSection("NotificationSettings").Bind(options)); services.Configure <AWSSQSSettings>(options => Configuration.GetSection("AWSSQSSettings").Bind(options)); services.AddHttpContextAccessor(); JWTConfig.RegisterJWT(services, Configuration); services.RegisterSwagger(); services.AddCors(options => { options.AddPolicy("AllowAllHeaders", builder => { builder.AllowAnyOrigin() .AllowAnyHeader() .AllowAnyMethod(); }); }); services .AddDbContext <ApplicationDbContext>(options => options .UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); RollbarConfigurator .Configure(environment: Configuration.GetSection("Rollbar:Environment").Value, isActive: Configuration.GetSection("Rollbar:IsActive").Value, token: Configuration.GetSection("Rollbar:Token").Value, logLevel: Configuration.GetSection("Rollbar:LogLevel").Value); MuambatorConfigurator.Configure(Configuration.GetSection("Muambator:Token").Value, Configuration.GetSection("Muambator:IsActive").Value); }
public AccountController(IOptions <JWTConfig> jwtConfig , IAccountAppService accountService , ILogger <AccountController> logger) { _jwtConfig = jwtConfig.Value; _accountService = accountService; _logger = logger; }
public SSOAuthenticationMiddleware(RequestDelegate next , IOptions <JWTConfig> jwtConfig , IHybridProviderFactory hybridProviderFactory) { _next = next ?? throw new ArgumentNullException(nameof(next)); _cache = hybridProviderFactory.GetHybridCachingProvider(BaseEasyCachingConsts.HybridCaching) ?? throw new ArgumentNullException(nameof(_cache)); _jwtConfig = jwtConfig.Value; }
public AccountController(IOptionsSnapshot <JWTConfig> jwtConfig , IAccountAppService accountService , UserContext userContext) { _jwtConfig = jwtConfig.Value; _accountService = accountService; _userContext = userContext; }
public SSOAuthenticationMiddleware(RequestDelegate next , IOptions <JWTConfig> jwtConfig , ICacheProvider cache) { _next = next ?? throw new ArgumentNullException(nameof(next)); _cache = cache; _jwtConfig = jwtConfig.Value; }
public AccountController(IMapper mapper, IAccountStore accountStoreService, ICachingProvider cachingProvider, ILogger <AccountController> logger, IOptions <JWTConfig> jwtOptions) { _mapper = mapper; _accountStoreService = accountStoreService; _caching = cachingProvider.CreateCaching(); _logger = logger; _jwtConfig = jwtOptions.Value; }
public static string CreateRefreshToken(JWTConfig jwtConfig, UserValidateDto user) { var claims = new Claim[] { new Claim(ClaimTypes.NameIdentifier, user.Account), }; return(CreateToken(jwtConfig, claims, TokenType.RefreshToken)); }
public void ConfigureServices(IServiceCollection services) { JWTConfig jwtConfig = new JWTConfig() //Zrób to inaczej { AccessTokenExpiration = Convert.ToInt32(Environment.GetEnvironmentVariable("JwtAccessTokenExpiration")), RefreshTokenExpiration = Convert.ToInt32(Environment.GetEnvironmentVariable("JwtRefreshTokenExpiration")), Issuer = Environment.GetEnvironmentVariable("JwtIssuer"), Audience = Environment.GetEnvironmentVariable("JwtAudience"), Secret = Environment.GetEnvironmentVariable("JwtSecret") }; services.AddControllers(); services.AddDbContext <Context>(opt => opt.UseSqlite("Data Source=gameweb.db")); services.AddScoped <IGamesRepository, GamesRepository>(); services.AddScoped <IUsersRepository, UsersRepository>(); services.AddScoped <IGameGenresRepository, GameGenresRepository>(); services.AddScoped <IDevelopersRepository, DevelopersRepository>(); services.AddSwaggerGen(c => { var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); c.IncludeXmlComments(xmlPath); }); services.AddScoped <IAuthService, AuthService>(); services.AddSingleton <JWTConfig>(jwtConfig); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.RequireHttpsMetadata = false; options.SaveToken = true; options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = jwtConfig.Issuer, ValidAudience = jwtConfig.Audience, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtConfig.Secret)), ClockSkew = TimeSpan.Zero }; }); services.AddAuthorization(config => { config.AddPolicy(Policies.Admin, Policies.AdminPolicy()); config.AddPolicy(Policies.User, Policies.UserPolicy()); config.AddPolicy(Policies.Mod, Policies.ModPolicy()); config.AddPolicy(Policies.RefreshToken, Policies.RefreshTokenPolicy()); }); }
public AuthorizationController( IOptions <List <string> > knownUsers, IOptions <JWTConfig> jwtConfig, IConfiguration config, ILogger <AuthorizationController> logger) { _knownUsers = knownUsers.Value; _jwtConfig = jwtConfig.Value; _config = config; _logger = logger; }
private ServiceRegistrationHelper(IConfiguration configuration, IServiceCollection services) { _configuration = configuration; _services = services; Configure(); _jwtConfig = _configuration.GetSection("JWT").Get <JWTConfig>(); _mongoConfig = _configuration.GetSection("MongoDb").Get <MongoConfig>(); _mysqlConfig = _configuration.GetSection("Mysql").Get <MysqlConfig>(); }
public NotificationProcessService(NotificationProcessChannel processingChannel, IOptions <AzureDevOpsConfig> azureOptions, IOptions <KestrelConfig> kestrelOptions, IOptions <JWTConfig> JWTOptions) { this.processingChannel = processingChannel; this.kestrelConfig = kestrelOptions.Value; this.azureDevopsConfig = azureOptions.Value; this.JWTOptions = JWTOptions.Value; var credentials = new VssBasicCredential("", azureDevopsConfig.PatToken); connection = new VssConnection(new Uri(azureDevopsConfig.CollectionUri), credentials); subscriptionClient = connection.GetClient <ServiceHooksPublisherHttpClient>(); }
public CustomAuthenticationMiddleware(RequestDelegate next , UserContext userContext //, IDistributedCache cache , IOptions <JWTConfig> jwtConfig , IHybridProviderFactory hybridProviderFactory) { _next = next ?? throw new ArgumentNullException(nameof(next)); _currentUser = userContext ?? throw new ArgumentNullException(nameof(userContext)); //_cache = cache ?? throw new ArgumentNullException(nameof(cache)); _cache = hybridProviderFactory.GetHybridCachingProvider(BaseEasyCachingConsts.HybridCaching) ?? throw new ArgumentNullException(nameof(_cache)); _jwtConfig = jwtConfig.Value; }
public AccountController(IOptionsSnapshot <JWTConfig> jwtConfig , IAccountAppService accountService , ILogger <AccountController> logger , UserContext userContext , IHttpContextAccessor contextAccessor) { _jwtConfig = jwtConfig.Value; _accountService = accountService; _logger = logger; _userContext = userContext; _contextAccessor = contextAccessor; }
public static string CreateAccessToken(JWTConfig jwtConfig, UserValidateDto user) { var claims = new Claim[] { new Claim(ClaimTypes.NameIdentifier, user.Account), new Claim(JwtRegisteredClaimNames.Sub, user.Id.ToString()), new Claim(ClaimTypes.Name, user.Name), //new Claim(ClaimTypes.Role, user.RoleIds??"0") //new Claim(JwtRegisteredClaimNames.Email, user.Email), }; return(CreateToken(jwtConfig, claims, TokenType.AccessToken)); }
// https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-3.1 public ServiceRepository(IHttpClientFactory httpClientFactory, RestApiConfig config, JWTConfig jWTConfig, ILogger <ServiceRepository> logger) { this.httpClientFactory = httpClientFactory; this.restApiConfig = config; this.jWTConfig = jWTConfig; this.logger = logger; this.defaultClient = this.httpClientFactory.CreateClient(); this.defaultClient.BaseAddress = new Uri(this.restApiConfig.BaseUrl); caseInsensitiveOptions = new JsonSerializerOptions() { PropertyNameCaseInsensitive = true }; }
public static string CreateAccessToken(JWTConfig jwtConfig, UserValidateDto user, string refreshTokenTxt) { var token = new JwtSecurityTokenHandler().ReadJwtToken(refreshTokenTxt); if (token != null) { var claimAccount = token.Claims.First(x => x.Type == ClaimTypes.NameIdentifier).Value; if (user != null && user.Account == claimAccount) { return(CreateAccessToken(jwtConfig, user)); } } return(string.Empty); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.RegisterRepositoryServices(); //auto mapper start AutoMapperConfig.RegisterMappings(); services.AddMvc(); services.Configure <ImageSettings>(options => Configuration.GetSection("ImageSettings").Bind(options)); services.Configure <EmailSettings>(options => Configuration.GetSection("EmailSettings").Bind(options)); services.Configure <ServerSettings>(options => Configuration.GetSection("ServerSettings").Bind(options)); JWTConfig.RegisterJWT(services, Configuration); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "INDIQME API", Version = "v1" }); c.ResolveConflictingActions(x => x.First()); 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>() }, }); }); services.AddCors(options => { options.AddPolicy("AllowAllHeaders", builder => { builder.AllowAnyOrigin() .AllowAnyHeader() .AllowAnyMethod(); }); }); services.AddDbContext <ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); }
public void ConfigureServices(IServiceCollection services) { RegisterHealthChecks(services, Configuration.GetConnectionString("DefaultConnection")); services.RegisterRepositoryServices(); services.AddAutoMapper(typeof(Startup)); services .AddControllers() .AddJsonOptions(options => { options.JsonSerializerOptions.IgnoreNullValues = true; options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()); }).AddNewtonsoftJson(); services .AddHttpContextAccessor() .Configure <RollbarOptions>(options => Configuration.GetSection("Rollbar").Bind(options)) .AddRollbarLogger(loggerOptions => loggerOptions.Filter = (loggerName, loglevel) => loglevel >= LogLevel.Trace); services.AddHttpContextAccessor(); JWTConfig.RegisterJWT(services, Configuration); services.RegisterSwagger(); services.AddCors(options => { options.AddPolicy("AllowAllHeaders", builder => { builder.AllowAnyOrigin() .AllowAnyHeader() .AllowAnyMethod(); }); }); services .AddDbContext <ApplicationDbContext>(options => options .UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); }
public IActionResult Index(string uname, string pwd) { JWTConfig jwtconfig = new JWTConfig(); cfg.GetSection("JWT").Bind(jwtconfig); var claim = new Claim[] { new Claim("UserName", "lb") }; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtconfig.IssuerSigningKey)); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var token = new JwtSecurityToken( issuer: jwtconfig.Issuer, audience: jwtconfig.Audience, claims: claim, notBefore: DateTime.Now, expires: DateTime.Now.AddMinutes(jwtconfig.AccessTokenExpiresMinutes), signingCredentials: creds); return(Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token) })); }
public void ConfigureServices(IServiceCollection services) { #region 读取配置 JWTConfig config = new JWTConfig(); Configuration.GetSection("JWT").Bind(config); #endregion #region 启用JWT认证 services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }). AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidIssuer = config.Issuer, ValidAudience = config.Audience, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config.IssuerSigningKey)), //ClockSkew = TimeSpan.FromMinutes(5) }; //通过TokenValidationParameters的构造方法查看参数的默认值如下: //public TokenValidationParameters() //{ // RequireExpirationTime = true; // RequireSignedTokens = true; // SaveSigninToken = false; // ValidateActor = false; // ValidateAudience = true; // ValidateIssuer = true; // ValidateIssuerSigningKey = false; // ValidateLifetime = true; // ValidateTokenReplay = false; //} //DefaultClockSkew = TimeSpan.FromSeconds(300); //即ClockSkew的默认值为5分钟 }); #endregion services.AddMvc(options => options.EnableEndpointRouting = false).SetCompatibilityVersion(Microsoft.AspNetCore.Mvc.CompatibilityVersion.Latest); }
public static string CreateToken(JWTConfig jwtConfig, Claim[] claims, TokenType tokenType) { var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtConfig.SymmetricSecurityKey)); string issuer = jwtConfig.Issuer; string audience = tokenType.Equals(TokenType.AccessToken) ? jwtConfig.Audience : jwtConfig.RefreshTokenAudience; int expires = tokenType.Equals(TokenType.AccessToken) ? jwtConfig.Expire : jwtConfig.RefreshTokenExpire; var token = new JwtSecurityToken( issuer: issuer, audience: audience, claims: claims, notBefore: DateTime.Now, expires: DateTime.Now.AddMinutes(expires), signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256) ); var jwtAccessTokenToken = new JwtSecurityTokenHandler().WriteToken(token); return(jwtAccessTokenToken); }