|
using BenchmarkDotNet.Attributes; |
|
using BenchmarkDotNet.Running; |
|
using Microsoft.IdentityModel.Tokens; |
|
using System; |
|
using System.IdentityModel.Tokens.Jwt; |
|
using System.Security.Claims; |
|
using System.Text; |
|
|
|
namespace ConsoleApp6 |
|
{ |
|
public class Program |
|
{ |
|
private SigningCredentials credentials; |
|
private SymmetricSecurityKey securityKey; |
|
private JwtSecurityTokenHandler tokenHandler; |
|
private TokenValidationParameters tokenValidationParameters; |
|
private string token; |
|
private JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler(); |
|
|
|
public static void Main(string[] args) |
|
{ |
|
BenchmarkRunner.Run<Program>(); |
|
} |
|
|
|
[Setup] |
|
public void Setup() |
|
{ |
|
byte[] key = Encoding.UTF8.GetBytes("9251E97D-7962-4B49-BB87-96ECADCEE092"); |
|
securityKey = new SymmetricSecurityKey(key); |
|
tokenHandler = new JwtSecurityTokenHandler(); |
|
credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256); |
|
tokenValidationParameters = new TokenValidationParameters |
|
{ |
|
AuthenticationType = "bearer", |
|
IssuerSigningKey = securityKey, |
|
ValidAudience = "accelamerchantcenter", |
|
ValidIssuer = "accelamerchantcenter" |
|
}; |
|
|
|
token = CreateToken(); |
|
} |
|
|
|
[Benchmark] |
|
public string CreateToken() |
|
{ |
|
ClaimsIdentity subject = new ClaimsIdentity(); |
|
JwtSecurityToken jwtToken = tokenHandler.CreateJwtSecurityToken |
|
( |
|
"accelamerchantcenter", |
|
"accelamerchantcenter", |
|
subject, |
|
DateTime.UtcNow, |
|
DateTime.UtcNow.AddHours(6), |
|
DateTime.UtcNow, |
|
credentials |
|
); |
|
|
|
return handler.WriteToken(jwtToken); |
|
} |
|
|
|
[Benchmark] |
|
public ClaimsPrincipal ValidateToken() |
|
{ |
|
try |
|
{ |
|
// Validate the token, returning a generated principal if valid |
|
SecurityToken validatedToken; |
|
return tokenHandler.ValidateToken(token, tokenValidationParameters, out validatedToken); |
|
} |
|
|
|
catch (SecurityTokenValidationException) |
|
{ |
|
// Handle tokens which failed validation |
|
return null; |
|
} |
|
|
|
catch (ArgumentException) |
|
{ |
|
// Handle malformed token strings that failed validation |
|
return null; |
|
} |
|
} |
|
} |
|
} |