-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAuthHelper.cs
More file actions
45 lines (37 loc) · 1.78 KB
/
Copy pathAuthHelper.cs
File metadata and controls
45 lines (37 loc) · 1.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
using Microsoft.AspNetCore.Http;
using System.Security.Claims;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
namespace HoTeach
{
public static class AuthHelper
{
public static ClaimsPrincipal ValidateToken(HttpRequest req)
{
if (!req.Headers.ContainsKey("Authorization"))
throw new UnauthorizedAccessException("Authorization header missing.");
var authHeader = req.Headers["Authorization"].ToString();
if (!authHeader.StartsWith("Bearer "))
throw new UnauthorizedAccessException("Invalid authorization header format.");
var token = authHeader.Substring("Bearer ".Length).Trim();
var handler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler();
var validationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
{
ValidIssuer = $"https://dev-m31s5020w8rygw8y.us.auth0.com/",
ValidAudience = "https://hoteachaudience.com",
IssuerSigningKeys = OpenIdConnectConfigurationRetriever
.GetAsync($"https://dev-m31s5020w8rygw8y.us.auth0.com/.well-known/openid-configuration", default)
.GetAwaiter().GetResult()
.SigningKeys
};
var principal = handler.ValidateToken(token, validationParameters, out _);
return principal;
}
public static bool HasScope(ClaimsPrincipal principal, string scope)
{
var scopeClaim = principal.FindFirst("scope")?.Value;
if (scopeClaim == null) return false;
var scopes = scopeClaim.Split(' ');
return scope.Split(' ').All(s => scopes.Contains(s, StringComparer.OrdinalIgnoreCase));
}
}
}