63 lines
2.2 KiB
C#
Executable File
63 lines
2.2 KiB
C#
Executable File
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
|
using Microsoft.IdentityModel.Tokens;
|
|
using Auth.Contracts.Permissions;
|
|
|
|
namespace Auth.API.Config;
|
|
|
|
public static class Authentication
|
|
{
|
|
public static IServiceCollection Authenticate(this IServiceCollection services, ConfigurationManager configuration)
|
|
{
|
|
services.AddAuthentication(x =>
|
|
{
|
|
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
|
|
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
|
|
}).AddJwtBearer(o =>
|
|
{
|
|
|
|
var Key = Encoding.UTF8.GetBytes(configuration["JWT:Key"]);
|
|
o.SaveToken = true;
|
|
o.TokenValidationParameters = new TokenValidationParameters
|
|
{
|
|
ValidateIssuer = false, // on production make it true
|
|
ValidateAudience = false, // on production make it true
|
|
ValidateLifetime = true,
|
|
ValidateIssuerSigningKey = true,
|
|
ValidIssuer = configuration["JWT:Issuer"],
|
|
ValidAudience = configuration["JWT:Audience"],
|
|
IssuerSigningKey = new SymmetricSecurityKey(Key),
|
|
ClockSkew = TimeSpan.Zero
|
|
};
|
|
o.Events = new JwtBearerEvents
|
|
{
|
|
OnAuthenticationFailed = context =>
|
|
{
|
|
if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
|
|
{
|
|
context.Response.Headers.Add("IS-TOKEN-EXPIRED", "true");
|
|
}
|
|
return Task.CompletedTask;
|
|
}
|
|
};
|
|
});
|
|
|
|
return services;
|
|
}
|
|
|
|
public static IServiceCollection AddPermissionPolicies(this IServiceCollection services)
|
|
{
|
|
services.AddAuthorization(options =>
|
|
{
|
|
foreach (var permission in AuthPermissions.GetAllPermissions())
|
|
{
|
|
options.AddPolicy(permission, policy => policy.RequireClaim("Permission", permission));
|
|
}
|
|
});
|
|
return services;
|
|
}
|
|
} |