Created
December 14, 2016 17:05
-
-
Save samueleresca/ec310b096a8543eb170d2fdebcbef8b7 to your computer and use it in GitHub Desktop.
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
using System; | |
using System.IdentityModel.Tokens.Jwt; | |
using System.Security.Claims; | |
using Microsoft.AspNetCore.Authentication; | |
using Microsoft.AspNetCore.Http.Authentication; | |
using Microsoft.IdentityModel.Tokens; | |
namespace CustomTokenAuthProvider | |
{ | |
public class CustomJwtDataFormat : ISecureDataFormat<AuthenticationTicket> | |
{ | |
private readonly string algorithm; | |
private readonly TokenValidationParameters validationParameters; | |
public CustomJwtDataFormat(string algorithm, TokenValidationParameters validationParameters) | |
{ | |
this.algorithm = algorithm; | |
this.validationParameters = validationParameters; | |
} | |
public AuthenticationTicket Unprotect(string protectedText) | |
=> Unprotect(protectedText, null); | |
public AuthenticationTicket Unprotect(string protectedText, string purpose) | |
{ | |
var handler = new JwtSecurityTokenHandler(); | |
ClaimsPrincipal principal = null; | |
SecurityToken validToken = null; | |
try | |
{ | |
principal = handler.ValidateToken(protectedText, this.validationParameters, out validToken); | |
var validJwt = validToken as JwtSecurityToken; | |
if (validJwt == null) | |
{ | |
throw new ArgumentException("Invalid JWT"); | |
} | |
if (!validJwt.Header.Alg.Equals(algorithm, StringComparison.Ordinal)) | |
{ | |
throw new ArgumentException($"Algorithm must be '{algorithm}'"); | |
} | |
} | |
catch (SecurityTokenValidationException) | |
{ | |
return null; | |
} | |
catch (ArgumentException) | |
{ | |
return null; | |
} | |
// Token validation passed | |
return new AuthenticationTicket(principal, new AuthenticationProperties(), "Cookie"); | |
} | |
public string Protect(AuthenticationTicket data) | |
{ | |
throw new NotImplementedException(); | |
} | |
public string Protect(AuthenticationTicket data, string purpose) | |
{ | |
throw new NotImplementedException(); | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment