Created
May 24, 2020 07:04
-
-
Save deepumi/9dfd3c1368c447174fd8daff5776bc3b to your computer and use it in GitHub Desktop.
Bearer Authentication policy for ASP.NET Core 5.0
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public sealed class BearerPolicyEvaluator : IPolicyEvaluator | |
{ | |
private const string Scheme = "Bearer"; | |
public Task<AuthenticateResult> AuthenticateAsync(AuthorizationPolicy _, HttpContext context) | |
{ | |
if (!context.Request.Headers.ContainsKey("Authorization")) | |
return Task.FromResult(AuthenticateResult.Fail("No Authorization header found!")); | |
string authHeader = context.Request.Headers["Authorization"]; | |
string bearerToken = authHeader?.Replace("Bearer ", string.Empty); | |
if (!string.Equals(bearerToken, "authToken", StringComparison.Ordinal)) | |
{ | |
return Task.FromResult(AuthenticateResult.Fail("Invalid token")); | |
} | |
var claims = new[] | |
{ | |
new Claim(ClaimTypes.NameIdentifier, "1000"), | |
new Claim(ClaimTypes.Name, "Deepu Madhusoodanan") | |
}; | |
var identity = new ClaimsIdentity(claims, Scheme); | |
var principal = new ClaimsPrincipal(identity); | |
var ticket = new AuthenticationTicket(principal, Scheme); | |
var authenticateResult = AuthenticateResult.Success(ticket); | |
return Task.FromResult(authenticateResult); | |
} | |
public Task<PolicyAuthorizationResult> AuthorizeAsync(AuthorizationPolicy _, | |
AuthenticateResult authenticationResult, HttpContext context, | |
object resource) | |
{ | |
var authorizeResult = authenticationResult.Succeeded | |
? PolicyAuthorizationResult.Success() | |
: PolicyAuthorizationResult.Challenge(); | |
return Task.FromResult(authorizeResult); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment