Ejemplo n.º 1
0
        public static TokenJWT Create(ETypeUser tipo)
        {
            var token = new TokenJWTBuilder()
                        .AddSecurityKey(JWTSecurityKey.Create(JwtTokenOptions.Values.Secret_Key))
                        .AddSubject(JwtTokenOptions.Values.Subject)
                        .AddIssuer(JwtTokenOptions.Values.Issuer)
                        .AddAudience(JwtTokenOptions.Values.Audience)
                        .AddClaim(tipo.ToString(), "1")
                        .AddExpiry(5)
                        .Builder();

            return(token);
        }
Ejemplo n.º 2
0
        public static IServiceCollection RegisterConfigStartupToken(this IServiceCollection services,
                                                                    string issuer,
                                                                    string audience,
                                                                    string subject,
                                                                    string secretKey)
        {
            JwtTokenOptions.Values = JwtTokenOptions.Factory(issuer, audience, secretKey, subject);

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(option =>
            {
                option.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = true,
                    ValidateAudience         = true,
                    ValidateLifetime         = true,
                    ValidateIssuerSigningKey = true,

                    ValidIssuer      = JwtTokenOptions.Values.Issuer,
                    ValidAudience    = JwtTokenOptions.Values.Audience,
                    IssuerSigningKey = JWTSecurityKey.Create(JwtTokenOptions.Values.Secret_Key)
                };

                option.Events = new JwtBearerEvents
                {
                    OnAuthenticationFailed = context =>
                    {
                        Console.WriteLine("OnAuthenticationFailed: " + context.Exception.Message);
                        return(Task.CompletedTask);
                    },
                    OnTokenValidated = context =>
                    {
                        Console.WriteLine("OnTokenValidated: " + context.SecurityToken);
                        return(Task.CompletedTask);
                    }
                };
            });

            services.AddAuthorization(options =>
            {
                options.AddPolicy("TotalAccess", policy => policy.RequireClaim("Administrador"));
            });

            return(services);
        }