| | 1 | | using System.Text; |
| | 2 | | using System.Security.Claims; |
| | 3 | | using Microsoft.AspNetCore.Authentication.JwtBearer; |
| | 4 | | using Microsoft.IdentityModel.Tokens; |
| | 5 | |
|
| | 6 | | namespace SharedObjects.Auth; |
| | 7 | |
|
| | 8 | | public static class AuthorizationPolicies |
| | 9 | | { |
| | 10 | | public static void AddAuth(WebApplicationBuilder builder) |
| 0 | 11 | | { |
| 0 | 12 | | AuthorizationPolicies.AddPolicies(builder.Services); |
| | 13 | |
|
| 0 | 14 | | builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options => |
| 0 | 15 | | { |
| 0 | 16 | | options.RequireHttpsMetadata = false; |
| 0 | 17 | | options.SaveToken = true; |
| 0 | 18 | | options.TokenValidationParameters = new TokenValidationParameters() |
| 0 | 19 | | { |
| 0 | 20 | | ValidateIssuer = true, |
| 0 | 21 | | ValidateAudience = true, |
| 0 | 22 | | ValidAudience = builder.Configuration["Jwt:Audience"], |
| 0 | 23 | | ValidIssuer = builder.Configuration["Jwt:Issuer"], |
| 0 | 24 | | IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"])) |
| 0 | 25 | | }; |
| 0 | 26 | | }); |
| 0 | 27 | | } |
| | 28 | |
|
| | 29 | | public static void AddPolicies(IServiceCollection services) |
| 0 | 30 | | { |
| 0 | 31 | | services.AddAuthorizationCore(options => |
| 0 | 32 | | { |
| 0 | 33 | | options.AddPolicy("MustBeAdmin", |
| 0 | 34 | | a => a.RequireAuthenticatedUser().RequireClaim(ClaimTypes.Role, "Admin")); |
| 0 | 35 | | options.AddPolicy("MustBeUser", |
| 0 | 36 | | a => a.RequireAuthenticatedUser().RequireClaim(ClaimTypes.Role, "User")); |
| 0 | 37 | | options.AddPolicy("MustBeSuperUser", |
| 0 | 38 | | a => a.RequireAuthenticatedUser().RequireClaim(ClaimTypes.Role, "SuperUser")); |
| 0 | 39 | | }); |
| 0 | 40 | | } |
| | 41 | | } |