//public AuthenticationTicket Unprotect(string protectedText) //{ // throw new NotImplementedException(); // //return new AuthenticationTicket(identity, authenticationProperties); //} /// <summary> /// method which is responsible for validation of the JWT and returning and authentication ticket: /// </summary> /// <param name = "protectedText" ></ param > /// < returns ></ returns > public AuthenticationTicket Unprotect(string protectedText) { Microsoft.IdentityModel.Tokens.SecurityToken validatedToken; if (string.IsNullOrWhiteSpace(protectedText)) { throw new ArgumentNullException("protectedText"); } //Fwk.Security.Identity.jwtSecurityProvider sec_provider = null; var tokenHandler = new JwtSecurityTokenHandler(); var jwtSecurityToken = tokenHandler.ReadJwtToken(protectedText); var securityProviderNameClaim = jwtSecurityToken.Claims.FirstOrDefault(c => c.Type == "securityProviderName"); if (securityProviderNameClaim == null) { throw new ArgumentNullException("securityProviderName claims in jwt"); } var sec_provider = helper.get_secConfig().GetByName(securityProviderNameClaim.Value); if (sec_provider == null) { throw new ArgumentNullException("No se encuentra configurado el proveedor (securityProviderName) en securityConfig.json"); } string audienceId = sec_provider.audienceId; string symmetricKeyAsBase64 = sec_provider.audienceSecret; var keyByteArray = TextEncodings.Base64Url.Decode(symmetricKeyAsBase64); var securityKey = new SymmetricSecurityKey(keyByteArray); var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature); //TODO : CustomJwtFormat Esta lista de issuers debe ser flexible ///Establezco los issuers validos var issuers = new List <string>() { "http://localhost:44345/" }; var validationParams = new TokenValidationParameters() { ValidAudience = sec_provider.audienceId, ValidIssuers = issuers, ValidateLifetime = true, ValidateAudience = true, ValidateIssuer = true, RequireSignedTokens = true, RequireExpirationTime = true, ValidateIssuerSigningKey = true, ClockSkew = TimeSpan.Zero, //IssuerSigningKeys = DefaultX509Key_Public_2048 IssuerSigningKey = signingCredentials.Key }; try { var principal = tokenHandler.ValidateToken(protectedText, validationParams, out validatedToken); var identity = principal.Identities.First(); // Fill out the authenticationProperties issued and expires times if the equivalent claims are in the JWT var authenticationProperties = new AuthenticationProperties(); //issued if (validatedToken.ValidFrom != DateTime.MinValue) { authenticationProperties.IssuedUtc = validatedToken.ValidFrom.ToUniversalTime(); } //expires if (validatedToken.ValidTo != DateTime.MinValue) { authenticationProperties.ExpiresUtc = validatedToken.ValidTo.ToUniversalTime(); } return(new AuthenticationTicket(identity, authenticationProperties)); } catch (Exception ex) { //var statusCode = HttpStatusCode.Unauthorized; //return Task<HttpResponseMessage>.Factory.StartNew(() => new HttpResponseMessage(statusCode) { }); var ec = new Fwk.Exceptions.FunctionalException((int)HttpStatusCode.Unauthorized, " No autorizado ", ex); throw ec; } }
static AuthenticationTicket Unprotect(string protectedText) { Microsoft.IdentityModel.Tokens.SecurityToken validatedToken; if (string.IsNullOrWhiteSpace(protectedText)) { throw new ArgumentNullException("protectedText"); } //Fwk.Security.Identity.jwtSecurityProvider sec_provider = null; var tokenHandler = new JwtSecurityTokenHandler(); var jwtSecurityToken = tokenHandler.ReadJwtToken(protectedText); var secretKey = ConfigurationManager.AppSettings["JWT_SECRET_KEY"]; var audienceId = ConfigurationManager.AppSettings["JWT_AUDIENCE_TOKEN"]; var issuerToken = ConfigurationManager.AppSettings["JWT_ISSUER_TOKEN"]; var securityKey = new SymmetricSecurityKey(System.Text.Encoding.Default.GetBytes(secretKey)); var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature); //string audienceId = sec_provider.audienceId; //string symmetricKeyAsBase64 = sec_provider.audienceSecret; //var keyByteArray = TextEncodings.Base64Url.Decode(symmetricKeyAsBase64); //var securityKey = new SymmetricSecurityKey(keyByteArray); //TODO : CustomJwtFormat Esta lista de issuers debe ser flexible ///Establezco los issuers validos var issuers = new List <string>() { "pelsoft", "issuerA", "issuerB", "http://localhost:50009" }; var validationParams = new TokenValidationParameters() { ValidAudience = audienceId, ValidIssuers = issuers, ValidateLifetime = true, ValidateAudience = true, ValidateIssuer = true, RequireSignedTokens = true, RequireExpirationTime = true, ValidateIssuerSigningKey = true, ClockSkew = TimeSpan.Zero, //IssuerSigningKeys = DefaultX509Key_Public_2048 IssuerSigningKey = signingCredentials.Key }; try { var principal = tokenHandler.ValidateToken(protectedText, validationParams, out validatedToken); var identity = principal.Identities.First(); // Fill out the authenticationProperties issued and expires times if the equivalent claims are in the JWT var authenticationProperties = new AuthenticationProperties(); //issued if (validatedToken.ValidFrom != DateTime.MinValue) { authenticationProperties.IssuedUtc = validatedToken.ValidFrom.ToUniversalTime(); } //expires if (validatedToken.ValidTo != DateTime.MinValue) { authenticationProperties.ExpiresUtc = validatedToken.ValidTo.ToUniversalTime(); } return(new AuthenticationTicket(identity, authenticationProperties)); } catch (Exception ex) { //return Task<HttpResponseMessage>.Factory.StartNew(() => new HttpResponseMessage(statusCode) { }); //throw new UnauthorizedAccessException(ex.Message); var ec = new Fwk.Exceptions.FunctionalException((int)HttpStatusCode.Unauthorized, " No autorizado " + ex.Message); throw ec; } }