public static void ConfigureAuthorization(this IServiceCollection services, IConfiguration configuration)
        {
            var identityUrl = "http://localhost:54140";
            var audience    = configuration.GetValue <string>("Audience");

            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata      = false;
                x.SaveToken                 = true;
                x.TokenValidationParameters = TokenValidator.GetTokenValidationParameters();
                x.Events = new JwtBearerEvents
                {
                    OnAuthenticationFailed = context =>
                    {
                        if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
                        {
                            context.Response.Headers.Add("Token-Expired", "true");
                        }

                        return(Task.CompletedTask);
                    }
                };
            });
        }
        private ClaimsPrincipal GetPrincipalFromExpiredToken(string token)
        {
            var tokenValidationParameters = TokenValidator.GetTokenValidationParameters(authorizationConfigs.TokenKey);

            //here we are saying that we don't care about the token's expiration date
            tokenValidationParameters.ValidateLifetime = false;

            var tokenHandler     = new JwtSecurityTokenHandler();
            var principal        = tokenHandler.ValidateToken(token, tokenValidationParameters, out SecurityToken securityToken);
            var jwtSecurityToken = securityToken as JwtSecurityToken;

            if (jwtSecurityToken == null || !jwtSecurityToken.Header.Alg.Equals(SecurityAlgorithms.HmacSha256, StringComparison.InvariantCultureIgnoreCase))
            {
                throw new SecurityTokenException("Invalid token");
            }

            return(principal);
        }
예제 #3
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    Version = "v1",
                    Title   = "User Management System API",
                });

                c.AddSecurityDefinition("Bearer",
                                        new OpenApiSecurityScheme
                {
                    In          = ParameterLocation.Header,
                    Description = "Please enter into field the word 'Bearer' following by space and JWT",
                    Name        = "Authorization",
                    Type        = SecuritySchemeType.ApiKey
                });

                var openApiSecurityScheme = new OpenApiSecurityScheme
                {
                    Reference = new OpenApiReference
                    {
                        Id   = "Bearer",
                        Type = ReferenceType.SecurityScheme,
                    },
                };

                c.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    { openApiSecurityScheme, new List <string>() },
                });
            });


            services.AddCors(options => options.AddPolicy(UserManagementPolicy, builder =>
            {
                builder.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader()
                .WithExposedHeaders("Token-Expired");
            }));

            var authorizationConfigs = new AuthorizationConfigs();

            Configuration.Bind("Authorization", authorizationConfigs);
            services.AddSingleton(authorizationConfigs);

            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata      = false;
                x.SaveToken                 = true;
                x.TokenValidationParameters = TokenValidator.GetTokenValidationParameters(authorizationConfigs.TokenKey);
                x.Events = new JwtBearerEvents
                {
                    OnAuthenticationFailed = context =>
                    {
                        if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
                        {
                            context.Response.Headers.Add("Token-Expired", bool.TrueString);
                        }

                        return(Task.CompletedTask);
                    }
                };
            });

            BLLModule.Load(services, Configuration);
        }