public static void AddAzureAdAndB2CJwtBearerAuthentication(this IServiceCollection services, AzureAdOptions azureAdOptions, AzureAdB2COptions azureB2COptions, Assembly controllerAssembly, string policyIdentifier = "") { // Setup Authentication services.AddAuthentication(options => { options.DefaultAuthenticateScheme = AzureJwtSchemes.AZURE_AD_AUTHENTICATION_SCHEME; }) .AddAzureB2CJwtBearer(azureB2COptions) .AddAzureAdJwtBearer(azureAdOptions); // Setup Authorization var customPolicyBuilder = new AuthorizationPolicyBuilder(AzureJwtSchemes.AZURE_AD_B2_C_AUTHENTICATION_SCHEME, AzureJwtSchemes.AZURE_AD_AUTHENTICATION_SCHEME); var defaultPolicy = customPolicyBuilder.RequireAuthenticatedUser().Build(); // scan custom defined policies in Authorization attribute to add as custom policies var customDefinedPolicies = FindAuthorizationPolicies(controllerAssembly, policyIdentifier); // add these custom policies to the authorization process services.AddAuthorization(o => { o.DefaultPolicy = defaultPolicy; customDefinedPolicies.ForEach(customDefinedPolicy => o.AddPolicy(customDefinedPolicy, policy => { policy.Requirements.Add(new AzurePolicyRequirement(customDefinedPolicy)); policy.AuthenticationSchemes.Add(AzureJwtSchemes.AZURE_AD_B2_C_AUTHENTICATION_SCHEME); policy.AuthenticationSchemes.Add(AzureJwtSchemes.AZURE_AD_AUTHENTICATION_SCHEME); })); }); }
public static void AddCustomAuthentication(this IServiceCollection services, AppSettingsBase appSettings) { services.AddSingleton <IAuthorizationHandler, ActiveTokenPolicy>(); var key = Encoding.ASCII.GetBytes(appSettings.Secret); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, x => { x.RequireHttpsMetadata = false; x.SaveToken = true; x.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(key), ValidateIssuer = false, ValidateAudience = false, ClockSkew = TimeSpan.Zero }; }); services.AddAuthorization(options => { var defaultAuthorizationPolicyBuilder = new AuthorizationPolicyBuilder(JwtBearerDefaults.AuthenticationScheme); defaultAuthorizationPolicyBuilder = defaultAuthorizationPolicyBuilder.RequireAuthenticatedUser(); options.DefaultPolicy = defaultAuthorizationPolicyBuilder.Build(); options.AddPolicy("ActiveToken", policy => policy.Requirements.Add(new ActiveTokenRequirement())); }); }
// 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.AddAuthentication(x => { x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(options => options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidIssuer = Configuration["Jwt:Issuer"], ValidAudience = Configuration["Jwt:Issuer"], IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"])) }); services.AddAuthorization(options => { var defaultAuthorizationPolicyBuilder = new AuthorizationPolicyBuilder( JwtBearerDefaults.AuthenticationScheme); defaultAuthorizationPolicyBuilder = defaultAuthorizationPolicyBuilder.RequireAuthenticatedUser(); options.DefaultPolicy = defaultAuthorizationPolicyBuilder.Build(); }); services.AddGrpc(); services.AddDbContext <PrisonDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("PrisonDB"))); }
/// <summary> /// Override method to handle custom role based authorization. /// </summary> /// <param name="policyName"></param> /// <returns></returns> public async override Task <AuthorizationPolicy> GetPolicyAsync(string policyName) { AuthorizationPolicyBuilder builder = new AuthorizationPolicyBuilder(); builder.RequireAuthenticatedUser(); switch (policyName) { case Constants.AdminAccess: builder.RequireRole(Role.Admin.ToString()); break; case Constants.AddEditDeleteAccess: builder.RequireRole(Role.AddEditDelete.ToString(), Role.Admin.ToString()); break; case Constants.AddEditAccess: builder.RequireRole(Role.AddEdit.ToString(), Role.AddEditDelete.ToString(), Role.Admin.ToString()); break; default: builder.RequireRole(Domain.Global.RoleList); break; } return(await Task.FromResult(builder.Build())); }
/// <summary> /// Add services and configuration needed for <see cref="WindowsAuthenticationHandler" /> /// to work for integration tests using <see cref="Microsoft.AspNetCore.TestHost.TestServer" /> /// </summary> /// <param name="services"></param> /// <returns></returns> public static IServiceCollection AddWindowsAuthenticationForTesting(this IServiceCollection services) { services.AddAuthenticationCore(options => { const string scheme = WindowsAuthenticationHandler.AuthenticationScheme; // Set the default auth scheme to our windows auth scheme. // Normally, this would be done in the call to .AddAuthentication() in Startup.cs, // but because we don't want to require modifications to web projects to be aware of integration tests, // we can instead modify the options after the fact to use our scheme. //options.DefaultScheme = scheme; //options.DefaultChallengeScheme = "Bearer"; options.AddScheme(scheme, s => { s.HandlerType = typeof(WindowsAuthenticationHandler); s.DisplayName = scheme; }); }); services.AddAuthorization(options => { var defaultAuthorizationPolicyBuilder = new AuthorizationPolicyBuilder( WindowsAuthenticationHandler.AuthenticationScheme, "Test"); defaultAuthorizationPolicyBuilder = defaultAuthorizationPolicyBuilder.RequireAuthenticatedUser(); options.DefaultPolicy = defaultAuthorizationPolicyBuilder.Build(); }); services.AddTransient <WindowsAuthenticationHandler>(); return(services); }
public static IServiceCollection AddAuthenticationWithBypass(this IServiceCollection services, Action <JwtBearerOptions> configureJwtBearer, Action <AuthenticationWithBypassOptions> configureBypass) { var options = new AuthenticationWithBypassOptions(); configureBypass(options); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(configureJwtBearer) .AddScheme <MagicHeaderAuthenticationOptions, MagicHeaderAuthenticationHandler>(MagicHeaderDefaults.AuthenticationScheme, opt => { opt.Header = options.BypassAuthenticationHeader; opt.Secret = options.BypassAuthenticationSecret; }); // Configure the default authorization policy to use two schemes in an OR fashion services.AddAuthorization(opt => { var defaultAuthorizationPolicyBuilder = new AuthorizationPolicyBuilder( JwtBearerDefaults.AuthenticationScheme, MagicHeaderDefaults.AuthenticationScheme); defaultAuthorizationPolicyBuilder = defaultAuthorizationPolicyBuilder.RequireAuthenticatedUser(); opt.DefaultPolicy = defaultAuthorizationPolicyBuilder.Build(); }); return(services); }
// 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.AddAuthentication("CookieAuth") .AddCookie("CookieAuth", config => { config.Cookie.Name = "Grandmas.Cookie"; config.LoginPath = "/Home/Authenticate"; }); services.AddAuthorization(config => { //var defaultAuthBuilder = new AuthorizationPolicyBuilder(); //var defaultAuthPolicy = defaultAuthBuilder //.RequireAuthenticatedUser() //.RequireClaim(ClaimTypes.DateOfBirth) //.Build(); //config.DefaultPolicy = defaultAuthPolicy; //config.AddPolicy("Claim.DoB", policyBuilder => //{ // policyBuilder.RequireClaim(ClaimTypes.DateOfBirth); //}); // these below 2 lines are one and the same //config.AddPolicy("Admin", policyBuilder => policyBuilder.RequireRole("Admin")); config.AddPolicy("Admin", policyBuilder => policyBuilder.RequireClaim(ClaimTypes.Role, "Admin")); config.AddPolicy("Claim.DoB", policyBuilder => { policyBuilder.AddRequirements(new CustomRequireClaim(ClaimTypes.DateOfBirth)); }); }); services.AddSingleton <IAuthorizationPolicyProvider, CustomAuthorizationPolicyProvider>(); services.AddScoped <IAuthorizationHandler, SecurityLevelHandler>(); services.AddScoped <IAuthorizationHandler, CustomRequireClaimHandler>(); services.AddScoped <IAuthorizationHandler, CookieJarAuthorizationHandler>(); services.AddScoped <IClaimsTransformation, ClaimsTransformation>(); services.AddRazorPages() .AddRazorPagesOptions(config => { config.Conventions.AuthorizePage("/Razor/SecurePage"); config.Conventions.AuthorizePage("/Razor/policy", "Admin"); config.Conventions.AuthorizeFolder("/RazorSecured"); config.Conventions.AllowAnonymousToPage("/RazorSecured/Anon"); }); services.AddControllersWithViews(config => { var defaultAuthBuilder = new AuthorizationPolicyBuilder(); var defaultAuthPolicy = defaultAuthBuilder .RequireAuthenticatedUser() .Build(); // global authorization filter // config.Filters.Add(new AuthorizeFilter(defaultAuthPolicy)); }); }
// This method gets called by the runtime. Use this method to add public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); services.AddRazorPages(); services.Configure <CookiePolicyOptions>(options => { options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); //Defined to use our database connection in each module services.AddDbContext <DIYSIYContext>(options => { options.UseSqlServer("server=.; database=DIYSIYBlog; uid=sa; pwd=123;"); options.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking); }); //The AddScoped method registers the service with a scoped lifetime, the lifetime of a single request. services.AddScoped(typeof(ICoreService <>), typeof(BaseService <>)); //services.AddTransient(typeof(ICoreService<>), typeof(BaseService<>)); //services.AddSingleton(typeof(ICoreService<>), typeof(BaseService<>)); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0); //Authentication configurations services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(option => { option.Cookie.Name = "UserLoginCookie"; option.LoginPath = "/Login/LoginPage"; }); //Authorization configuration role ýnfo take from ClaimTypes.Role as string services.AddAuthorization(option => { var userAuthPolicyBuilder = new AuthorizationPolicyBuilder(); option.DefaultPolicy = userAuthPolicyBuilder.RequireAuthenticatedUser().RequireClaim(ClaimTypes.Role).Build(); }); }
public HttpClient CreateAuthClient() { var client = this.WithWebHostBuilder(builder => { builder.ConfigureTestServices(services => { services .AddAuthentication("Test") .AddScheme <AuthenticationSchemeOptions, TestAuthHandler>("Test", options => {}); // Allow both the JWT authentication and our Test authentication method services.AddAuthorization(options => { var defaultAuthorizationPolicyBuilder = new AuthorizationPolicyBuilder( JwtBearerDefaults.AuthenticationScheme, "Test"); defaultAuthorizationPolicyBuilder = defaultAuthorizationPolicyBuilder.RequireAuthenticatedUser(); options.DefaultPolicy = defaultAuthorizationPolicyBuilder.Build(); }); }); }).CreateClient(new WebApplicationFactoryClientOptions { AllowAutoRedirect = false }); client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Test"); return(client); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); //.NET Core has built-in IOC support //.Net Framework did not had Built-in IOC.. We had to use 3rd party IOC, NINJECT, Autofac services.AddDbContext <MovieShopDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString(("MovieShopDbConnection")))); //Registering our DI services... Binding Services to interfaces //Also Repository services.AddScoped <IMovieService, MovieService>(); services.AddScoped <IMovieRepository, MovieRepository>(); services.AddScoped <IGenreService, GenreService>(); services.AddScoped <IAsyncRepository <Genre>, EfRepository <Genre> >(); services.AddScoped <IAsyncRepository <MovieGenre>, EfRepository <MovieGenre> >(); services.AddScoped <IUserService, UserService>(); services.AddScoped <IUserRepository, UserRepository>(); services.AddScoped <ICryptoService, CryptoService>(); services.AddScoped <ICastRepository, CastRepository>(); services.AddScoped <ICastService, CastService>(); services.AddScoped <IPurchaseRepository, PurchaseRepository>(); services.AddScoped <IFavoriteRepository, FavoriteRepository>(); services.AddScoped <IReviewRepository, ReviewRepository>(); //sets the default authentication scheme for the app services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options => { options.Cookie.Name = "MovieShopAuthCookie"; options.ExpireTimeSpan = TimeSpan.FromHours(2); options.LoginPath = "/Account/Login"; }); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer( options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = false, ValidateAudience = false, ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["TokenSettings:PrivateKey"])) }; }); services.AddAuthorization(options => { var defaultAuthorizationPolicyBuilder = new AuthorizationPolicyBuilder(JwtBearerDefaults.AuthenticationScheme); defaultAuthorizationPolicyBuilder = defaultAuthorizationPolicyBuilder.RequireAuthenticatedUser(); options.DefaultPolicy = defaultAuthorizationPolicyBuilder.Build(); }); }
public Task <AuthorizationPolicy> GetPolicyAsync(string policyName) { if (policyName.StartsWith("Create") || policyName.StartsWith("Delete") || policyName.StartsWith("Edit") || policyName.StartsWith("View")) { var policyBuilder = new AuthorizationPolicyBuilder(); policyBuilder.RequireAuthenticatedUser(); policyBuilder.AddRequirements(new PermissionRequirement(policyName)); return(Task.FromResult(policyBuilder.Build())); } else if (policyName.StartsWith("delete.") || policyName.StartsWith("read.") || policyName.StartsWith("worker.") || policyName.StartsWith("write.")) { var policyBuilder = new AuthorizationPolicyBuilder(); policyBuilder.RequireAuthenticatedUser(); policyBuilder.AddRequirements(new ScopeRequirement(policyName)); return(Task.FromResult(policyBuilder.Build())); } return(FallbackPolicyProvider.GetPolicyAsync(policyName)); }
public static IServiceCollection ResolverAutenticacao(this IServiceCollection services) { var key = Encoding.ASCII.GetBytes(ChaveToken.Key); services.AddAuthorization(options => { var defaultAuthorizationPolicyBuilder = new AuthorizationPolicyBuilder( JwtBearerDefaults.AuthenticationScheme); defaultAuthorizationPolicyBuilder = defaultAuthorizationPolicyBuilder.RequireAuthenticatedUser(); options.DefaultPolicy = defaultAuthorizationPolicyBuilder.Build(); }); services.AddAuthentication(x => { x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(x => { x.RequireHttpsMetadata = false; x.SaveToken = true; x.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(key), ValidateIssuer = false, ValidateAudience = false }; }); return(services); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddCors(options => { options.AddPolicy("LocalAzure", builder => { builder.WithOrigins("http://localhost", "http://<App Service URL>") .WithMethods("GET"); }); }); services.AddTransient <TokenAuthorizationProvider>(); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Latest).AddRazorRuntimeCompilation(); services.AddSingleton <ICosmosDbService>(InitializeCosmosClientInstanceAsync(Configuration.GetSection("CosmosDb")).GetAwaiter().GetResult()); services.AddAuthentication("Bearer").AddJwtBearer(options => { options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters() { IssuerSigningKey = TokenAuthorizationProvider.CreateSecurityKey(), ValidIssuer = TokenAuthorizationProvider.Issuer, ValidAudience = TokenAuthorizationProvider.Audience }; }); services.AddAuthorization(options => { AuthorizationPolicyBuilder builder = new AuthorizationPolicyBuilder("Bearer"); options.AddPolicy("SessionToken", builder.RequireAuthenticatedUser().Build()); }); }
// 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.AddDbContext <AppDbContext>(config => { config.UseSqlServer(Configuration.GetConnectionString("ApplicationConnection")); }); services.AddIdentity <IdentityUser, IdentityRole>(config => { // config }) .AddEntityFrameworkStores <AppDbContext>() .AddDefaultTokenProviders(); services.AddAuthentication("CookieAuth") .AddCookie(config => { config.Cookie.Name = "uid"; }); services.AddAuthorization(config => { var defaultAuthBuilder = new AuthorizationPolicyBuilder(); var defaultAuthPolicy = defaultAuthBuilder .RequireAuthenticatedUser() .Build(); config.DefaultPolicy = defaultAuthPolicy; }); services.AddControllers(); }
public void Require(AuthorizationPolicyBuilder policyOptions) { policyOptions.AuthenticationSchemes.Add(ServiceAuthConsts.AuthenticationScheme); policyOptions.RequireAuthenticatedUser(); policyOptions.RequireClaim(ServiceAuthConsts.ClaimUserType, ServiceAuthConsts.ClaimUserTypeUser); policyOptions.RequireClaim(ServiceAuthConsts.ClaimCanDelete, ServiceAuthConsts.ClaimTargetTopic); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddDbContextPool <AppDbContext>(conf => { conf.UseInMemoryDatabase("Memory"); }); //addIdentity Registers the services services.AddIdentity <IdentityUser, IdentityRole>(cnf => { cnf.Password.RequireNonAlphanumeric = false; cnf.Password.RequireNonAlphanumeric = false; cnf.Password.RequireUppercase = false; cnf.Password.RequireDigit = false; cnf.SignIn.RequireConfirmedEmail = true; }) .AddEntityFrameworkStores <AppDbContext>() .AddDefaultTokenProviders(); services.AddAuthentication("CookieAuth").AddCookie(cnf => { cnf.Cookie.Name = "identity.Cookie"; cnf.LoginPath = "/Home/LogIn"; }); services.AddAuthorization(config => { var defaultauthBuilder = new AuthorizationPolicyBuilder(); var defaultAuthPolicy = defaultauthBuilder .RequireAuthenticatedUser() //.RequireClaim(ClaimTypes.DateOfBirth) .Build(); config.DefaultPolicy = defaultAuthPolicy; }); //This for configering mail into he project services.AddMailKit(config => config.UseMailKit(Configuration.GetSection("Email").Get <MailKitOptions>())); services.AddControllersWithViews(); }
/// <summary> /// Policies are looked up by string name, so expect 'parameters' to be encoded (embedded) in the policy names (errr-don't blame me). /// </summary> /// <param name="encodedPolicyName">A colon ':' delimited string of three values [<see cref="RightType>"/>:<see cref="Permission"/>:<see cref="string"/>]</param> /// <remarks> /// For Encoding and Decoding see <see cref="PolicyName"/> /// </remarks> public Task <AuthorizationPolicy> GetPolicyAsync(string encodedPolicyName) { // here's the other end of the magic to decode the string with the requirement details var requirementDetails = PolicyName.Deserialise(encodedPolicyName); // If the policy name doesn't match the format expected by this policy provider, // try the fallback provider. If no fallback provider is used, this would return // Task.FromResult<AuthorizationPolicy>(null) instead. if (requirementDetails == null) { return(FallbackPolicyProvider.GetPolicyAsync(encodedPolicyName)); } var policy = new AuthorizationPolicyBuilder(); policy.RequireAuthenticatedUser(); // Set multiple bearer tokens. This pairs with .AddAuthententication to expose // multiple www-authenticate headers on a 401 // // see https://stackoverflow.com/questions/49694383/use-multiple-jwt-bearer-authentication // policy.AuthenticationSchemes.Add(AuthenticatorDefaults.ExternalAuthenticationSchemeName); // now we can hand in the requirements from the attribute into the policy which what we really want to do policy.AddRequirements( new HasPermissionsOnResourceRequirement( requirementDetails.Type, requirementDetails.Access, requirementDetails.ResourceKey)); return(Task.FromResult(policy.Build())); }
public void ConfigureServices(IServiceCollection services) { services.AddControllers() .AddNewtonsoftJson(options => { options.SerializerSettings.ContractResolver = new DefaultContractResolver(); }); services.AddAuthentication(x => { x.AddScheme <UserApiAuthenticationHandler>(UserApiAuthenticationHandler.SchemeName, UserApiAuthenticationHandler.SchemeName); x.DefaultScheme = UserApiAuthenticationHandler.SchemeName; }); services.AddAuthorization(opt => { var apb = new AuthorizationPolicyBuilder(new[] { UserApiAuthenticationHandler.SchemeName }); apb = apb.RequireAuthenticatedUser(); opt.DefaultPolicy = apb.Build(); //opt.AddPolicy("Default", policy => //{ // policy.AuthenticationSchemes.Add(UserAPIAuthenticationHandler.SchemeName); // policy.RequireAuthenticatedUser(); //}); }); services.AddCors(options => { options.AddPolicy("CorsPolicy", builder => builder.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader() ); }); services.AddUserIdentityServices(Configuration); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { 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; }); services.AddTransient <TokenAuthorizationProvider>(); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); services.AddAuthentication("Bearer").AddJwtBearer(options => { options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters() { IssuerSigningKey = TokenAuthorizationProvider.CreateSecurityKey(), ValidIssuer = TokenAuthorizationProvider.Issuer, ValidAudience = TokenAuthorizationProvider.Audience }; }); services.AddAuthorization(options => { AuthorizationPolicyBuilder builder = new AuthorizationPolicyBuilder("Bearer"); options.AddPolicy("SessionToken", builder.RequireAuthenticatedUser().Build()); }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddSpaStaticFiles(configuration => { configuration.RootPath = "wwwroot"; }); var keySecret = Configuration["JwtSigningKey"]; var symmetricKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(keySecret)); services.AddAuthentication() .AddJwtBearer(options => { options.TokenValidationParameters.ValidateIssuerSigningKey = true; options.TokenValidationParameters.IssuerSigningKey = symmetricKey; options.TokenValidationParameters.ValidateAudience = false; options.TokenValidationParameters.ValidateIssuer = false; }); services.AddAuthorization(options => { var defaultAuthorizationPolicyBuilder = new AuthorizationPolicyBuilder( JwtBearerDefaults.AuthenticationScheme); defaultAuthorizationPolicyBuilder = defaultAuthorizationPolicyBuilder.RequireAuthenticatedUser(); options.DefaultPolicy = defaultAuthorizationPolicyBuilder.Build(); }); }
// 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.AddCors(); services.AddSpaStaticFiles(configuration => { configuration.RootPath = "ClientApp/dist"; }); services.AddDbContext <DatabaseContext>(options => options.UseSqlServer(Properties.Resources.MSSQL_DatabaseConnectionString)); //services.AddDbContext<DatabaseContext>(options => options.UseSqlite(Properties.Resources.SQlite_DatabaseConnectionString)); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options => { options.RequireHttpsMetadata = true; options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters() { IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Properties.Resources.TokenSecurityKey)), ValidateLifetime = true, ValidateIssuer = true, ValidIssuer = Properties.Resources.TokenIssuer, ValidateIssuerSigningKey = true, ValidateAudience = true, ValidAudience = Properties.Resources.TokenAudience }; }); services.AddAuthorization(options => { var defaultPolicy = new AuthorizationPolicyBuilder(JwtBearerDefaults.AuthenticationScheme); defaultPolicy = defaultPolicy.RequireAuthenticatedUser(); options.DefaultPolicy = defaultPolicy.Build(); }); services.AddControllers().AddNewtonsoftJson(); }
private static void ConfigureAuthentication(IServiceCollection services) { var key = Encoding.ASCII.GetBytes(Settings.Secret); services.AddAuthentication(x => { x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(x => { x.RequireHttpsMetadata = false; x.SaveToken = true; x.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(key), ValidateIssuer = false, ValidateAudience = false }; }); services.AddAuthorization(x => { var defaultAuthorizationPolicyBuilder = new AuthorizationPolicyBuilder(JwtBearerDefaults.AuthenticationScheme); defaultAuthorizationPolicyBuilder = defaultAuthorizationPolicyBuilder.RequireAuthenticatedUser(); x.DefaultPolicy = defaultAuthorizationPolicyBuilder.Build(); }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "MovieShop.API", Version = "v1" }); }); services.AddDbContext <MovieShopDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("MovieShopDbConnection"))); services.AddScoped <IMovieRepository, MovieRepository>(); services.AddScoped <IAsyncRepository <Genre>, EfRepository <Genre> >(); services.AddScoped <IUserRepository, UserRepository>(); services.AddScoped <ICastRepository, CastRepository>(); services.AddScoped <ICurrentUserService, CurrentUserService>(); services.AddScoped <IUserService, UserService>(); services.AddScoped <IMovieService, MovieService>(); services.AddScoped <IGenreService, GenreService>(); services.AddScoped <ICastService, CastService>(); // add httpcontext to classes/services // enables ihttpcontext interface // injects into CurrentUserService for example services.AddHttpContextAccessor(); services.AddScoped <IAsyncRepository <Favorite>, EfRepository <Favorite> >(); // add the movieshopheaderfilter services.AddControllersWithViews( options => options.Filters.Add(typeof(MovieShopHeaderFilter)) ); services.AddMemoryCache(); services.AddScoped <IJwtService, JwtService>(); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer( options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = false, ValidateAudience = false, ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["TokenSetting:PrivateKey"])) }; } ); services.AddAuthorization(options => { var defaultAuthorizationPolicyBuilder = new AuthorizationPolicyBuilder(JwtBearerDefaults.AuthenticationScheme); defaultAuthorizationPolicyBuilder = defaultAuthorizationPolicyBuilder.RequireAuthenticatedUser(); options.DefaultPolicy = defaultAuthorizationPolicyBuilder.Build(); }); }
public static void AddIdentitySetup(this IServiceCollection services, IConfiguration configuration) { services.Configure <AppSecret>(configuration.GetSection("AppSettings")); var AppSecret = configuration.GetSection("AppSettings").Get <AppSecret>(); services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(options => { options.RequireHttpsMetadata = true; options.SaveToken = true; options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, RequireExpirationTime = true, ValidIssuer = AppSecret.Issuer, ValidAudience = AppSecret.Audience, IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(AppSecret.Key)), }; }); services.AddAuthorization(options => { var defaultAuthorizationPolicyBuilder = new AuthorizationPolicyBuilder(JwtBearerDefaults.AuthenticationScheme); defaultAuthorizationPolicyBuilder = defaultAuthorizationPolicyBuilder.RequireAuthenticatedUser(); options.DefaultPolicy = defaultAuthorizationPolicyBuilder.Build(); }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddAuthorization(cfg => { var defaultAuthorizationPolicyBuilder = new AuthorizationPolicyBuilder(JwtBearerDefaults.AuthenticationScheme); defaultAuthorizationPolicyBuilder = defaultAuthorizationPolicyBuilder.RequireAuthenticatedUser(); cfg.DefaultPolicy = defaultAuthorizationPolicyBuilder.Build(); }); services.AddAuthentication(cfg => { cfg.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; cfg.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(cfg => { cfg.TokenValidationParameters = new TokenValidationParameters() { ValidIssuer = TokenSecurity.ISSUER, ValidAudience = TokenSecurity.AUDIENCE, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(TokenSecurity.SIGNING_KEY)), }; }); services.AddControllersWithViews(); }
/// <summary> /// SSO配置 /// </summary> /// <param name="services"></param> /// <param name="appConfig"></param> private static void AddSSOSetup(IServiceCollection services, AppConfig appConfig) { services.AddAuthentication(options => { /*设置相关处理的默认方案*/ options.DefaultScheme = IdentityServerAuthenticationDefaults.AuthenticationScheme; //默认方案(包含了以下所有配置,但是可以被以下配置覆盖) options.DefaultAuthenticateScheme = IdentityServerAuthenticationDefaults.AuthenticationScheme; //认证方案 options.DefaultChallengeScheme = nameof(ResponseAuthenticationHandler); //401消息处理方案 options.DefaultForbidScheme = nameof(ResponseAuthenticationHandler); //403消息处理方案 }) .AddIdentityServerAuthentication(options => { options.Authority = appConfig.IdentityServer.Url; //授权端点 options.RequireHttpsMetadata = appConfig.IdentityServer.RequireHttps; //需要HTTPS options.SupportedTokens = SupportedTokens.Jwt; //Token类型 options.ApiName = appConfig.IdentityServer.ApiName; //api资源名称 options.ApiSecret = appConfig.IdentityServer.ApiSecret; //api资源机密串 options.NameClaimType = JwtClaimTypes.Name; //指定映射到用户名的Claim options.RoleClaimType = JwtClaimTypes.Role; //指定映射到角色的Claim options.JwtValidationClockSkew = TimeSpan.Zero; //设置Token有效期验证的时间偏移量为0 options.ClaimsIssuer = appConfig.IdentityServer.Issuer; //颁发者 }) .AddScheme <AuthenticationSchemeOptions, ResponseAuthenticationHandler>(nameof(ResponseAuthenticationHandler), o => { }); //设置授权配置 services.AddAuthorization(options => { var policy = new AuthorizationPolicyBuilder(); policy.RequireAuthenticatedUser(); policy.AddRequirements(new PermissionRequirement(ConstantOptions.RoleConstant.AllRoles)); options.DefaultPolicy = policy.Build(); }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews().AddNewtonsoftJson(); // In production, the React files will be served from this directory services.AddSpaStaticFiles(configuration => { configuration.RootPath = "client/build"; }); services.Configure <AuthenticationConfiguration>(Configuration.GetSection("Auth")); services.AddAuthentication() .AddJwtBearer("JwtBearer", options => { options.Authority = Configuration["Auth:Authority"]; options.Audience = Configuration["Auth:Audience"]; }) .AddIdentityServerAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme, options => { options.Authority = Configuration["Auth:Authority"]; options.ApiName = Configuration["Auth:ApiName"]; }); services.AddAuthorization(options => { var defaultAuthorizationPolicyBuilder = new AuthorizationPolicyBuilder( "JwtBearer", IdentityServerAuthenticationDefaults.AuthenticationScheme ); defaultAuthorizationPolicyBuilder = defaultAuthorizationPolicyBuilder.RequireAuthenticatedUser(); options.DefaultPolicy = defaultAuthorizationPolicyBuilder.Build(); }); }
public static void AddJwtSetup(this IServiceCollection services, IConfiguration configuration) { var appSettingsSection = configuration.GetSection("ApiSettings"); services.Configure <JwtSettings>(appSettingsSection); var appSettings = appSettingsSection.Get <JwtSettings>(); var key = Encoding.ASCII.GetBytes(appSettings.Secret); services.AddAuthentication(x => { x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(x => { x.RequireHttpsMetadata = true; x.SaveToken = true; x.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(key), ValidateIssuer = true, ValidateAudience = true, ValidAudience = appSettings.ValidAt, ValidIssuer = appSettings.Issuer }; }); services.AddAuthorization(options => { var defaultAuthorizationPolicyBuilder = new AuthorizationPolicyBuilder(JwtBearerDefaults.AuthenticationScheme); defaultAuthorizationPolicyBuilder = defaultAuthorizationPolicyBuilder.RequireAuthenticatedUser(); options.DefaultPolicy = defaultAuthorizationPolicyBuilder.Build(); }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "MovieShop.API", Version = "v1" }); }); services.AddDbContext <MovieShopDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString(("MovieShopDbConnection")))); services.AddScoped <IMovieService, MovieServices>(); services.AddScoped <IMovieRepository, MovieRepository>(); services.AddScoped <IGenreService, GenreServices>(); services.AddScoped <IAsyncRepository <Genre>, EfRepository <Genre> >(); services.AddScoped <IAsyncRepository <Cast>, EfRepository <Cast> >(); services.AddScoped <IUserService, UserServices>(); services.AddScoped <IUserRepository, UserRepository>(); services.AddScoped <ICryptoService, CryptoServices>(); services.AddScoped <IPurchaseService, PurchaseServices>(); services.AddScoped <IPurchaseRepository, PurchaseRepository>(); services.AddScoped <ICastService, CastServices>(); services.AddScoped <IReviewService, ReviewServices>(); services.AddScoped <IReviewRepository, ReviewRepository>(); services.AddScoped <IAsyncRepository <Purchase>, EfRepository <Purchase> >(); services.AddScoped <IAsyncRepository <Favorite>, EfRepository <Favorite> >(); services.AddAutoMapper(typeof(Startup), typeof(MoviesMappingProfile)); /*services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer( * options => * { * options.TokenValidationParameters = new TokenValidationParameters * { * ValidateIssuerSigningKey = true, * IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["TokenSettings:PrivateKey"])) * }; * });*/ services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer( options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = false, ValidateAudience = false, ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["TokenSettings:PrivateKey"])) }; }); services.AddAuthorization(options => { var defaultAuthorizationPolicyBuilder = new AuthorizationPolicyBuilder(JwtBearerDefaults.AuthenticationScheme); defaultAuthorizationPolicyBuilder = defaultAuthorizationPolicyBuilder.RequireAuthenticatedUser(); options.DefaultPolicy = defaultAuthorizationPolicyBuilder.Build(); }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "MovieShopAPI", Version = "v1" }); }); services.AddScoped <IMovieService, MovieService>(); //AddTransient services.AddScoped <IMovieRepository, MovieRepository>(); services.AddScoped <IAsyncRepository <Genre>, EfRepository <Genre> >(); services.AddScoped <IGenreService, GenreService>(); services.AddScoped <ICastRepository, CastRepository>(); services.AddScoped <ICastService, CastService>(); //services.AddAutoMapper(typeof(Startup), typeof(MovieShopMappingProfile)); //https://docs.automapper.org/en/latest/Understanding-your-mapping.html services.AddScoped <IUserService, UserService>(); services.AddScoped <IUserRepository, UserRepository>(); services.AddScoped <ICurrentUserService, CurrentUserService>(); services.AddScoped <IJwtService, JwtService>(); services.AddDbContext <MovieShopDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("MovieShopDbConnection"))); services.AddHttpContextAccessor(); services.AddMemoryCache(); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer( options => { options.TokenValidationParameters = new TokenValidationParameters() { ValidateIssuer = false, ValidateAudience = false, ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["TokenSetting:PrivateKey"])) }; } ); services.AddAuthorization(options => { var defaultAuthorizationPolicyBuilder = new AuthorizationPolicyBuilder(JwtBearerDefaults.AuthenticationScheme); defaultAuthorizationPolicyBuilder = defaultAuthorizationPolicyBuilder.RequireAuthenticatedUser(); options.DefaultPolicy = defaultAuthorizationPolicyBuilder.Build(); }); services.AddCors(options => { options.AddPolicy("CorsApi", builder => builder.WithOrigins(Configuration.GetValue <string>("clientSPAUrl"), Configuration.GetValue <string>("clientSPAUrl2")) .AllowAnyHeader() .AllowAnyMethod()); }); }