示例#1
0
        private void ConfigureAuthentication(IServiceCollection services)
        {
            services.AddAuthentication(authOptions =>
            {
                authOptions.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                authOptions.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(jwtOptions =>
            {
                jwtOptions.Authority = Configuration["Authentication:Authority"];
                jwtOptions.Audience  = Configuration["Authentication:Audience"];

                jwtOptions.SaveToken           = false;
                jwtOptions.IncludeErrorDetails = true;

                if (Environment.IsDevelopment())
                {
                    jwtOptions.RequireHttpsMetadata = false;
                }

                jwtOptions.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateAudience         = true,
                    ValidateIssuerSigningKey = true,
                    ValidateIssuer           = true,
                    ValidIssuer      = Configuration["Authentication:Authority"],
                    ValidateLifetime = true,
                };

                jwtOptions.Events = new JwtBearerEvents
                {
                    OnAuthenticationFailed = failedAuthContext =>
                    {
                        failedAuthContext.NoResult();
                        failedAuthContext.Response.StatusCode  = 500;
                        failedAuthContext.Response.ContentType = "text/plain";

                        var errorMessage = failedAuthContext.Exception switch
                        {
                            SecurityTokenExpiredException _ => "Expired token.",
                            SecurityTokenNotYetValidException _ => "Token not yet valid.",
                            SecurityTokenInvalidLifetimeException _ => "Invalid token lifetime.",
                            SecurityTokenNoExpirationException _ => "Missing token expiration.",
                            SecurityTokenSignatureKeyNotFoundException _ => "Invalid token. Key not found.",
                            _ => "An error occured processing your authentication."
                        };

                        return(failedAuthContext.Response.WriteAsync(errorMessage));
                    },

                    // OnMessageReceived = debugContext =>
                    // {
                    //     var response = debugContext.Response;
                    //     return Task.CompletedTask;
                    // }
                };
            });

            // services.AddAuthorization(policyOptions =>
            // {
            //     policyOptions.AddPolicy("Keycloak", new AuthorizationPolicyBuilder()
            //         .RequireAuthenticatedUser()
            //         .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
            //         .Build());
            // });
        }
示例#2
0
        private void ConfigureAuthentication(IServiceCollection services)
        {
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(bearerOptions =>
            {
                bearerOptions.Authority           = Configuration["Jwt:Authority"];
                bearerOptions.Audience            = Configuration["Jwt:Audience"];
                bearerOptions.SaveToken           = true;
                bearerOptions.IncludeErrorDetails = true;
                if (Environment.IsDevelopment())
                {
                    bearerOptions.RequireHttpsMetadata = false;
                }

                var listAudiences = new List <string>();
                listAudiences.Add(Configuration["Jwt:Audience"]);

                bearerOptions.TokenValidationParameters = new TokenValidationParameters
                {
                    SaveSigninToken          = true,
                    ValidateIssuerSigningKey = true,
                    ValidateIssuer           = true,
                    ValidIssuer      = Configuration["Jwt:Authority"],
                    ValidateAudience = true,
                    ValidAudiences   = listAudiences,
                    ValidateLifetime = true
                };

                bearerOptions.Events = new JwtBearerEvents
                {
                    OnAuthenticationFailed = context =>
                    {
                        context.NoResult();
                        context.Response.StatusCode  = 401;
                        context.Response.ContentType = "text/plain";

                        var errorMessage = context.Exception switch
                        {
                            SecurityTokenExpiredException _ => "Expired token.",
                            SecurityTokenNotYetValidException _ => "Token not yet valid.",
                            SecurityTokenInvalidLifetimeException _ => "Invalid token lifetime.",
                            SecurityTokenNoExpirationException _ => "Missing token expiration.",
                            SecurityTokenSignatureKeyNotFoundException _ => "Invalid token. Key not found.",
                            _ => "An error occured processing your authentication."
                        };

                        if (Environment.IsDevelopment())
                        {
                            errorMessage += " - " + context.Exception.ToString();
                        }

                        return(context.Response.WriteAsync(errorMessage));
                    },

                    OnTokenValidated = context =>
                    {
                        var resourceAccess = JObject.Parse(context.Principal.FindFirstValue("resource_access"));
                        var clientRoles    = resourceAccess[Configuration["Jwt:Audience"]]["roles"];
                        var claimsIdentity = context.Principal.Identity as ClaimsIdentity;
                        if (claimsIdentity != null)
                        {
                            foreach (var clientRole in clientRoles)
                            {
                                claimsIdentity.AddClaim(new Claim(ClaimTypes.Role, clientRole.ToString()));
                            }
                        }
                        return(Task.CompletedTask);
                    }
                };
            });
        }