Esempio n. 1
0
        /// <summary>
        /// Helper to add jwt bearer authentication
        /// </summary>
        /// <param name="services"></param>
        /// <param name="config"></param>
        /// <param name="inDevelopment"></param>
        public static void AddJwtBearerAuthentication(this IServiceCollection services,
                                                      IAuthConfig config, bool inDevelopment)
        {
            if (config.HttpsRedirectPort > 0)
            {
                services.AddHsts(options => {
                    options.Preload           = true;
                    options.IncludeSubDomains = true;
                    options.MaxAge            = TimeSpan.FromDays(60);
                });
                services.AddHttpsRedirection(options => {
                    options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect;
                    options.HttpsPort          = config.HttpsRedirectPort;
                });
            }

            // Allow access to context from within token providers and other client auth
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            // Add jwt bearer auth
            services
            .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options => {
                options.Authority = config.GetAuthorityUrl() + "/v2.0";
                options.SaveToken = true;     // Save token to allow request on behalf

                options.TokenValidationParameters = new TokenValidationParameters {
                    ClockSkew        = config.AllowedClockSkew,
                    ValidateIssuer   = true,
                    IssuerValidator  = (iss, t, p) => ValidateIssuer(iss, config),
                    ValidateAudience = !string.IsNullOrEmpty(config.Audience),
                    ValidAudience    = config.Audience
                };
                options.Events = new JwtBearerEvents {
                    OnAuthenticationFailed = ctx => {
                        if (config.AuthRequired)
                        {
                            ctx.NoResult();
                            return(WriteErrorAsync(ctx.Response, inDevelopment ?
                                                   ctx.Exception : null));
                        }
                        return(Task.CompletedTask);
                    },
                    OnTokenValidated = ctx => {
                        if (ctx.SecurityToken is JwtSecurityToken accessToken)
                        {
                            if (ctx.Principal.Identity is ClaimsIdentity identity)
                            {
                                identity.AddClaim(new Claim("access_token",
                                                            accessToken.RawData));
                            }
                        }
                        return(Task.CompletedTask);
                    }
                };
            });
        }