public static IServiceCollection AddAppSwagger(this IServiceCollection services, IConfiguration configuration) { var swaggerSection = new SwaggerSection(); configuration.Bind(SwaggerSection.SectionName, swaggerSection); var stsServerUri = new Uri(swaggerSection.StsServer); services.AddSwaggerGen(options => { options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme { Name = "oauth2", Type = SecuritySchemeType.OAuth2, Scheme = JwtBearerDefaults.AuthenticationScheme, Flows = new OpenApiOAuthFlows { Implicit = new OpenApiOAuthFlow { Scopes = new Dictionary <string, string> { ["EventHub.Web.ApiAPI"] = "EventHub API" }, AuthorizationUrl = new Uri(stsServerUri, "/connect/authorize"), TokenUrl = new Uri(stsServerUri, "/connect/token") }, } }); options.OperationFilter <OAuth2OperationFilter>(); options.SwaggerDoc("v1", new OpenApiInfo { Title = "EventHub API", Version = "v1" }); }); return(services); }
public static IServiceCollection AddAppSecurity(this IServiceCollection services, IConfiguration configuration) { var swaggerSection = new SwaggerSection(); configuration.Bind(SwaggerSection.SectionName, swaggerSection); services.AddIdentityServer() .AddApiAuthorization <ApplicationUser, ApplicationDbContext>(c => { c.Clients.Add(new Client { ClientId = "EventHub.Swagger", ClientName = "Swagger UI for EventHub API", AllowedGrantTypes = GrantTypes.Implicit, AllowAccessTokensViaBrowser = true, RedirectUris = { new Uri(new Uri(swaggerSection.UIServer), "/swagger/oauth2-redirect.html").ToString() }, AllowedScopes = { "EventHub.Web.ApiAPI" }, RequireConsent = false, }); }); services.AddAuthentication() .AddGoogle(options => { var googleAuth = configuration.GetSection(GoogleAuthSection.SectionName).Get <GoogleAuthSection>(); options.ClientId = googleAuth.ClientId; options.ClientSecret = googleAuth.ClientSecret; }) .AddIdentityServerJwt(); services.Configure <JwtBearerOptions>( IdentityServerJwtConstants.IdentityServerJwtBearerScheme, options => { var onMessageReceived = options.Events.OnMessageReceived; options.Events.OnMessageReceived = async context => { var accessToken = context.Request.Query["access_token"]; var path = context.HttpContext.Request.Path; if (!string.IsNullOrEmpty(accessToken) && path.StartsWithSegments("/hubs/chat")) { context.Token = accessToken; } await onMessageReceived(context); }; }); services.AddAuthorization(options => { AuthorizationPolicies.AddPolicies(options); }); return(services); }