Exemple #1
0
        public static IApplicationBuilder UseSecurity(this IApplicationBuilder app, IConfiguration configuration)
        {
            var loggerFactory = app.ApplicationServices.GetRequiredService <ILoggerFactory>();
            var logger        = loggerFactory.CreateLogger(nameof(UseSecurity));

            var securitySettings = configuration.GetSection(nameof(SecuritySettings)).Get <SecuritySettings>()
                                   ?? throw new SecuritySettingNullException(loggerFactory);

            securitySettings.Validate();

            app.UseAuthentication();
            app.UseAuthorization();

            if (securitySettings.IsDevelopment)
            {
                IdentityModelEventSource.ShowPII = true;

                logger?.LogInformation("Configurando Segurança Local (IsDevelopment: true)");

                app.UseEndpoints(endpoints =>
                {
                    endpoints.MapGet("/token", async(context) =>
                    {
                        var symmetricSecurityKey = LocalSecuritySettings.GetSymmetricSecurityKey();
                        var signingCredentials   = new SigningCredentials(symmetricSecurityKey, SecurityAlgorithms.HmacSha256);
                        var token = new JwtSecurityToken(
                            LocalSecuritySettings.Issuer,
                            LocalSecuritySettings.Audience,
                            GetLocalClaims(),
                            DateTime.Now,
                            DateTime.UtcNow.AddYears(1),
                            signingCredentials);

                        await context.Response.WriteAsync($"Token: { new JwtSecurityTokenHandler().WriteToken(token) }");
                    });
                });
            }
            else
            {
                logger?.LogInformation("Configurando Segurança Remota (IsDevelopment: false)");
            }

            return(app);
        }
Exemple #2
0
        internal static IServiceCollection ConfigureLocalSecurity(this IServiceCollection services)
        {
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer("Bearer", options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = true,
                    ValidateAudience         = true,
                    ValidateLifetime         = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer   = LocalSecuritySettings.Issuer,
                    ValidAudience = LocalSecuritySettings.Audience,

                    IssuerSigningKey = LocalSecuritySettings.GetSymmetricSecurityKey()
                };

                options.Events = new JwtBearerEvents
                {
                    OnAuthenticationFailed = (context) =>
                    {
                        if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
                        {
                            var loggerFactory = context.HttpContext.RequestServices
                                                .GetRequiredService <ILoggerFactory>();

                            var logger = loggerFactory.CreateLogger("Startup");

                            logger.LogInformation("Token-Expired");
                            context.Response.Headers.Add("Token-Expired", "true");
                        }
                        return(Task.CompletedTask);
                    },

                    OnMessageReceived = (context) =>
                    {
                        return(Task.FromResult(0));
                    }
                };
            });

            return(services);
        }