Repository navigation
Expand file tree
/
Copy pathAuthConfig.cs
More file actions
111 lines (103 loc) · 3.78 KB
/
Copy pathAuthConfig.cs
File metadata and controls
111 lines (103 loc) · 3.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using System.Net;
using System.Security.Claims;
namespace OrgAI;
public static class AuthConfig
{
private static readonly string[] _authenticationSchemes = ["Microsoft"];
public static void ConfigureAuth(this WebApplicationBuilder builder)
{
ArgumentNullException.ThrowIfNull(builder);
builder.Services
.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(o =>
{
o.Cookie.Path = "/";
o.Cookie.HttpOnly = true;
o.Cookie.SecurePolicy = CookieSecurePolicy.Always;
o.Cookie.SameSite = SameSiteMode.Lax;
o.LoginPath = "/auth/login";
o.LogoutPath = "/auth/logout";
o.ExpireTimeSpan = TimeSpan.FromDays(60);
o.SlidingExpiration = true;
o.ReturnUrlParameter = "path";
o.Events = new()
{
OnRedirectToAccessDenied = context =>
{
context.Response.StatusCode = 403;
return Task.CompletedTask;
},
OnValidatePrincipal = async context =>
{
var issued = context.Properties.IssuedUtc;
if (issued.HasValue && issued.Value > DateTimeOffset.UtcNow.AddDays(-1))
return;
if (UserExists(context.Principal.Identity.Name))
{
context.ShouldRenew = true;
}
else
{
context.RejectPrincipal();
await context.HttpContext.SignOutAsync();
}
}
};
})
.AddOpenIdConnect("Microsoft", o =>
{
o.Authority = $"https://login.microsoftonline.com/{builder.Configuration["MicrosoftTenantId"]}/v2.0/";
o.ClientId = builder.Configuration["MicrosoftClientId"];
o.ClientSecret = builder.Configuration["MicrosoftClientSecret"];
o.ResponseType = OpenIdConnectResponseType.Code;
o.ResponseMode = OpenIdConnectResponseMode.Query;
o.MapInboundClaims = false;
o.Scope.Clear();
o.Scope.Add("openid");
o.Scope.Add("profile");
o.Events = new()
{
OnTicketReceived = context =>
{
var email = context.Principal.FindFirstValue("upn")?.ToLowerInvariant();
if (UserExists(email))
{
var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
identity.AddClaim(new Claim(ClaimTypes.Name, email));
context.Principal = new ClaimsPrincipal(identity);
}
else
{
context.Fail("Unauthorised");
context.Response.Redirect("/auth/denied");
context.HandleResponse();
}
return Task.CompletedTask;
}
};
});
builder.Services.AddAuthorizationBuilder().SetFallbackPolicy(new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build());
}
private static bool UserExists(string email)
{
return !string.IsNullOrWhiteSpace(email) && UserGroup.GroupNameByUserEmail.ContainsKey(email);
}
public static void MapAuthPaths(this WebApplication app)
{
app.MapGet("/auth/login/challenge", [AllowAnonymous] ([FromQuery] string path) =>
{
var authProperties = new AuthenticationProperties { RedirectUri = path is null ? "/" : WebUtility.UrlDecode(path), AllowRefresh = true, IsPersistent = true };
return Results.Challenge(authProperties, _authenticationSchemes);
});
app.MapGet("/auth/logout", async (HttpContext context) =>
{
await context.SignOutAsync();
return Results.Redirect("/auth/login");
});
}
}