Newsbot.Collector/Newsbot.Collector.Api/Startup/IdentityStartup.cs

52 lines
2.0 KiB
C#

using System.Text;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using Newsbot.Collector.Api.Domain.Consts;
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,
b => b.RequireRole(Authorization.AdministratorsRole, "true"));
options.AddPolicy(Authorization.UserPolicy,
b => b.RequireRole(Authorization.UsersRole, "true"));
});
}
}