12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697 |
- using System;
- using System.IdentityModel.Tokens;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Security.Claims;
- using System.ServiceModel.Security.Tokens;
- using System.Threading;
- using System.Threading.Tasks;
-
- namespace iiie.Authentication.Business.JWT
- {
- /// <summary>
- /// Handler for token authentication
- /// </summary>
- public class TokenValidationHandler : DelegatingHandler
- {
- /// <summary>
- /// Gets the token from the HTTP AUthorization header
- /// </summary>
- /// <param name="request">The HTTP request</param>
- /// <param name="token">The variable to store the token</param>
- /// <returns>True if the token has been found, false otherwise</returns>
- private static bool TryRetrieveToken(HttpRequestMessage request, out string token)
- {
- token = null;
- var auth = request.Headers.Authorization;
- if (auth == null || auth.Scheme != "Bearer")
- return false;
- token = auth.Parameter;
- return true;
- }
-
- /// <summary>
- /// Attempts to verify user token
- /// </summary>
- /// <param name="request">The HTTP request</param>
- /// <param name="cancellationToken">Token used for cancelation</param>
- /// <returns>The HTTP response</returns>
- protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
- {
- HttpStatusCode statusCode;
- string token;
-
- if (!TryRetrieveToken(request, out token))
- {
- return base.SendAsync(request, cancellationToken);
- }
-
- try
- {
- JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler
- {
- Configuration = new SecurityTokenHandlerConfiguration()
- {
- MaxClockSkew = new TimeSpan(0, 1, 0)
- }
- };
-
- var stringValidator = AuthProvider.GetValidatorString();
- TokenValidationParameters validationParameters = new TokenValidationParameters()
- {
- RequireSignedTokens = true,
- RequireExpirationTime = true,
- ValidAudience = stringValidator,
- ValidateIssuerSigningKey = true,
- ValidIssuer = "urn:" + stringValidator,
- IssuerSigningToken = new BinarySecretSecurityToken(Convert.FromBase64String(AuthProvider.GetCredentialKey()))
- };
-
- SecurityToken validateToken;
- ClaimsPrincipal claim = tokenHandler.ValidateToken(token, validationParameters, out validateToken);
- Thread.CurrentPrincipal = claim;
-
- var name = ((ClaimsIdentity)claim.Identity).Claims.FirstOrDefault(x => x.Type == ClaimTypes.Name);
- var salt = ((ClaimsIdentity)claim.Identity).Claims.FirstOrDefault(x => x.Type == ClaimTypes.Authentication);
-
- if (name == null || salt == null)
- statusCode = HttpStatusCode.Unauthorized;
- else
- {
- var user = GetUserDbo(name.Value, salt.Value);
- if (user == null)
- statusCode = HttpStatusCode.Unauthorized;
- else
- return base.SendAsync(request, cancellationToken);
- }
- }
- catch (Exception e)
- {
- statusCode = HttpStatusCode.Unauthorized;
- }
- return Task<HttpResponseMessage>.Factory.StartNew(() =>
- new HttpResponseMessage(statusCode), cancellationToken);
- }
- }
- }
|