2023-07-23 16:20:16 -07:00
|
|
|
using System.Text;
|
|
|
|
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
|
|
|
using Microsoft.IdentityModel.Tokens;
|
2023-08-06 13:31:00 -07:00
|
|
|
using Newsbot.Collector.Api.Domain.Consts;
|
2023-07-23 16:20:16 -07:00
|
|
|
using Newsbot.Collector.Domain.Models.Config;
|
|
|
|
|
|
|
|
namespace Newsbot.Collector.Api.Startup;
|
|
|
|
|
|
|
|
public static class IdentityStartup
|
|
|
|
{
|
|
|
|
public static void DefineJwtRequirements(IServiceCollection services, IConfiguration config)
|
|
|
|
{
|
|
|
|
// Configure JWT for auth and load it into DI so we can use it in the controllers
|
|
|
|
|
|
|
|
var jwtSettings = new JwtSettings();
|
|
|
|
config.Bind(nameof(jwtSettings), jwtSettings);
|
|
|
|
services.AddSingleton(jwtSettings);
|
|
|
|
|
|
|
|
// Configure how the Token Validation will be handled
|
|
|
|
var tokenValidationParameters = new TokenValidationParameters
|
|
|
|
{
|
|
|
|
ValidateIssuerSigningKey = true,
|
|
|
|
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtSettings.Secret ?? "")),
|
|
|
|
ValidateIssuer = false,
|
|
|
|
ValidateAudience = false,
|
|
|
|
RequireExpirationTime = false,
|
|
|
|
ValidateLifetime = true
|
|
|
|
};
|
|
|
|
services.AddSingleton(tokenValidationParameters);
|
|
|
|
|
|
|
|
// Build the Authentication that will be used
|
|
|
|
services.AddAuthentication(x =>
|
|
|
|
{
|
|
|
|
x.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
|
|
|
|
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
|
|
|
|
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
|
|
|
|
}).AddJwtBearer(x =>
|
|
|
|
{
|
|
|
|
x.SaveToken = true;
|
|
|
|
x.TokenValidationParameters = tokenValidationParameters;
|
|
|
|
});
|
|
|
|
|
|
|
|
// Build the Authorization Policy that the users will conform to.
|
|
|
|
services.AddAuthorization(options =>
|
|
|
|
{
|
|
|
|
options.AddPolicy(Authorization.AdministratorPolicy,
|
2023-08-06 13:31:00 -07:00
|
|
|
b => b.RequireRole(Authorization.AdministratorsRole, "true"));
|
|
|
|
options.AddPolicy(Authorization.UserPolicy,
|
|
|
|
b => b.RequireRole(Authorization.UsersRole, "true"));
|
2023-07-23 16:20:16 -07:00
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|