public ExternalLoginService(IOptions <OpenIdOptions> openIdOptionsAccessor, ICacheService cacheService, IOptions <GoogleOptions> googleOptionsAccessor, IOptions <FacebookOptions> facebookOptionsAccessor) { _cacheService = cacheService; _openIdOptions = openIdOptionsAccessor.Value; _googleOptions = googleOptionsAccessor.Value; _facebookOptions = facebookOptionsAccessor.Value; }
/// <summary> /// Configures OpenIdOptions, IHttpContextAccessor, Authentication, cookies and bearer token /// </summary> /// <param name="services">Specifies the contract for a collection of service descriptors.</param> /// <param name="configuration">Represents a set of key/value application configuration properties.</param> /// <param name="cookieName">The cookie name. If the name is empty the cookie is not added</param> /// <returns></returns> public static IServiceCollection AddSharedKernelAuth(this IServiceCollection services, IConfiguration configuration, string cookieName = null) { var openIdOptions = new OpenIdOptions(); configuration.GetSection(nameof(OpenIdOptions)).Bind(openIdOptions); services.Configure <OpenIdOptions>(configuration.GetSection(nameof(OpenIdOptions))); // configure jwt authentication var key = Encoding.ASCII.GetBytes(openIdOptions.ClientSecret); var authenticationBuilder = services .AddTransient <IHttpContextAccessor, HttpContextAccessor>() .AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(options => { options.Authority = openIdOptions.Authority; options.Audience = openIdOptions.Audience; options.RequireHttpsMetadata = openIdOptions.RequireHttpsMetadata; options.SaveToken = true; options.TokenValidationParameters = new TokenValidationParameters { // Validate Authority ValidateIssuer = true, ValidIssuer = openIdOptions.Authority, ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(key), ValidateAudience = !string.IsNullOrWhiteSpace(openIdOptions.Audience), ValidAudience = openIdOptions.Audience, ValidateLifetime = true, ClockSkew = TimeSpan.Zero }; }); if (!string.IsNullOrWhiteSpace(cookieName)) { authenticationBuilder.AddCookie("MyCookie", options => { options.ExpireTimeSpan = TimeSpan.FromSeconds(openIdOptions.AccessTokenSecondsLifetime); }); } return(services); }
private static IServiceCollection AddAuthentication(this IServiceCollection services) { OpenIdOptions options = services.BuildServiceProvider().GetRequiredService <IOptions <OpenIdOptions> >().Value; //Add identity server if (_isDevelopment) { services.AddAuthentication("Development") .AddScheme <AuthenticationSchemeOptions, DevelopmentAuthenticationHandler>("Development", null); } else { services.AddSingleton <IDiscoveryCache>(r => { IHttpClientFactory factory = r.GetRequiredService <IHttpClientFactory>(); return(new DiscoveryCache(options.Authority, () => factory.CreateClient())); }); services.AddAuthentication(options => { options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultChallengeScheme = "oidc"; }) .AddCookie(x => { x.ExpireTimeSpan = TimeSpan.FromMinutes(60); x.Cookie.Name = options.CookieName; }) .AddOpenIdConnect("oidc", options => { options.Authority = options.Authority; options.RequireHttpsMetadata = false; options.ClientId = options.ClientId; options.ClientSecret = options.ClientSecret; options.ResponseType = OpenIdConnectResponseType.CodeIdToken; options.Scope.Clear(); options.Scope.Add(OpenIdConnectScope.OpenIdProfile); options.Scope.Add(OpenIdConnectScope.OpenId); options.Scope.Add(OpenIdConnectScope.Email); options.ClaimActions.MapAllExcept("iss", "nbf", "exp", "aud", "nonce", "iat", "c_hash"); options.GetClaimsFromUserInfoEndpoint = true; options.SaveTokens = true; options.TokenValidationParameters = new TokenValidationParameters { NameClaimType = JwtClaimTypes.Name, RoleClaimType = JwtClaimTypes.Role }; }); } return(services); }
/// <summary> /// Services configuration /// </summary> /// <param name="services"></param> /// <param name="configuration"></param> /// <returns></returns> public static IServiceCollection AddSharedKernelOpenApi(this IServiceCollection services, IConfiguration configuration) { var openApiOptions = new OpenApiOptions(); configuration.GetSection(nameof(OpenApiOptions)).Bind(openApiOptions); services.Configure <OpenApiOptions>(configuration.GetSection(nameof(OpenApiOptions))); var openIdOptions = new OpenIdOptions(); configuration.GetSection(nameof(OpenIdOptions)).Bind(openIdOptions); services.AddSwaggerGenNewtonsoftSupport(); services.AddFluentValidationRulesToSwagger(); services.AddSwaggerGen(swaggerGenOptions => { swaggerGenOptions.SwaggerDoc("v1", new OpenApiInfo { Title = openApiOptions.Title, Version = "v1" }); swaggerGenOptions.SchemaFilter <RequireValueTypePropertiesSchemaFilter>(); swaggerGenOptions.DescribeAllParametersInCamelCase(); var xmlPath = swaggerGenOptions.IncludeXmlComments(openApiOptions, true); swaggerGenOptions.AddSecurityDefinition(openIdOptions, openApiOptions); swaggerGenOptions.AddEnumsWithValuesFixFilters(services, xmlPath); swaggerGenOptions.OperationFilter <SecurityRequirementsOperationFilter>(); }); return(services); }
/// <summary> /// Add one or more "securityDefinitions", describing how your API is protected, to the generated Swagger /// </summary> /// <param name="swaggerGenOptions"></param> /// <param name="openIdOptions"><see cref="OpenIdOptions"/></param> /// <param name="openApiOptions"><see cref="OpenApiOptions"/></param> public static void AddSecurityDefinition(this SwaggerGenOptions swaggerGenOptions, OpenIdOptions openIdOptions, OpenApiOptions openApiOptions) { var authority = openApiOptions?.Authority ?? openIdOptions?.Authority; if (string.IsNullOrWhiteSpace(authority)) { return; } swaggerGenOptions.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme { Type = SecuritySchemeType.OAuth2, Flows = new OpenApiOAuthFlows { Password = new OpenApiOAuthFlow { AuthorizationUrl = new Uri(authority), TokenUrl = new Uri(authority + "/connect/token"), Scopes = openIdOptions.Scopes.ToDictionary(s => s.Name, s => s.DisplayName) } } }); swaggerGenOptions.AddSecurityRequirement(new OpenApiSecurityRequirement { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "oauth2" } }, new[] { openIdOptions.Audience } } }); }
/// <summary> /// Services configuration /// </summary> /// <param name="services"></param> /// <param name="configuration"></param> /// <returns></returns> public static IServiceCollection AddSharedKernelOpenApi(this IServiceCollection services, IConfiguration configuration) { var openApiOptions = new OpenApiOptions(); configuration.GetSection(nameof(OpenApiOptions)).Bind(openApiOptions); services.AddSwaggerGenNewtonsoftSupport(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = openApiOptions.Title, Version = "v1" }); // Set the comments path for the Swagger JSON and UI. string xmlPath = null; if (!string.IsNullOrWhiteSpace(openApiOptions.XmlDocumentationFile)) { xmlPath = Path.Combine(AppContext.BaseDirectory, openApiOptions.XmlDocumentationFile); c.IncludeXmlComments(xmlPath); } c.AddFluentValidationRules(); var openIdOptions = new OpenIdOptions(); configuration.GetSection(nameof(OpenIdOptions)).Bind(openIdOptions); if (!string.IsNullOrWhiteSpace(openIdOptions.Authority)) { c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme { Type = SecuritySchemeType.OAuth2, Flows = new OpenApiOAuthFlows { Password = new OpenApiOAuthFlow { AuthorizationUrl = new Uri(openIdOptions.Authority), TokenUrl = new Uri(openIdOptions.Authority + "/connect/token"), Scopes = openIdOptions.Scopes.ToDictionary(s => s.Name, s => s.DisplayName) } } }); c.AddSecurityRequirement(new OpenApiSecurityRequirement { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "oauth2" } }, new[] { openIdOptions.Audience } } }); } c.AddEnumsWithValuesFixFilters(services, o => { // add schema filter to fix enums (add 'x-enumNames' for NSwag) in schema o.ApplySchemaFilter = true; // add parameter filter to fix enums (add 'x-enumNames' for NSwag) in schema parameters o.ApplyParameterFilter = true; // add document filter to fix enums displaying in swagger document o.ApplyDocumentFilter = true; // add descriptions from DescriptionAttribute or xml-comments to fix enums (add 'x-enumDescriptions' for schema extensions) for applied filters o.IncludeDescriptions = true; // get descriptions from DescriptionAttribute then from xml-comments o.DescriptionSource = DescriptionSources.DescriptionAttributesThenXmlComments; // get descriptions from xml-file comments on the specified path // should use "options.IncludeXmlComments(xmlFilePath);" before if (!string.IsNullOrWhiteSpace(xmlPath)) { o.IncludeXmlCommentsFrom(xmlPath); } // the same for another xml-files... }); //c.OperationFilter<RemoveVersionFromParameter>(); //c.DocumentFilter<ReplaceVersionWithExactValueInPath>(); c.OperationFilter <SecurityRequirementsOperationFilter>(); //c.OperationFilter<FileOperation>(); // remove Paths and Defenitions from OpenApi documentation without accepted roles // c.DocumentFilter<HidePathsAndDefinitionsByRolesDocumentFilter>(new List<string> { "AcceptedRole" }); }); return(services); }