public void AuthenticateUsingMsftJwt(string token) { try { // Use JWTSecurityTokenHandler to validate the JWT token JWTSecurityTokenHandler tokenHandler = new JWTSecurityTokenHandler(); TokenValidationParameters parms = new TokenValidationParameters() { AllowedAudience = "MyRelyingPartApp", ValidIssuers = new List <string>() { "TokenIssuer" }, SigningToken = new BinarySecretSecurityToken(Convert.FromBase64String(this.secretKey)) }; var config = new IdentityConfiguration(); Thread.CurrentPrincipal = config .ClaimsAuthenticationManager .Authenticate("TheMethodRequiringAuthZ", tokenHandler.ValidateToken(token, parms)); } catch (Exception ex) { Console.WriteLine(ex.Message); } }
/// <summary> /// /// </summary> /// <param name="token">= Token</param> /// <param name="allowedAudience">= Azure ACS Namespace</param> /// <param name="issuers">= RPs in ACS</param> /// <returns></returns> public static ClaimsPrincipal RetrieveClaims(string token, string issuer, List <string> allowedAudiences) { JWTSecurityTokenHandler tokenHandler = new JWTSecurityTokenHandler(); // Set the expected properties of the JWT token in the TokenValidationParameters TokenValidationParameters validationParameters = new TokenValidationParameters() { AllowedAudiences = allowedAudiences, ValidIssuer = issuer, SigningToken = new X509SecurityToken(new X509Certificate2(GetSigningCertificate(issuer + "FederationMetadata/2007-06/FederationMetadata.xml"))) }; return(tokenHandler.ValidateToken(token, validationParameters)); }
/// <summary> /// /// </summary> /// <param name="token">= Token</param> /// <param name="allowedAudience">= Azure ACS Namespace</param> /// <param name="issuers">= RPs in ACS</param> /// <returns></returns> public static ClaimsPrincipal RetrieveClaims(string token, string issuer, List<string> allowedAudiences) { JWTSecurityTokenHandler tokenHandler = new JWTSecurityTokenHandler(); // Set the expected properties of the JWT token in the TokenValidationParameters TokenValidationParameters validationParameters = new TokenValidationParameters() { AllowedAudiences = allowedAudiences, ValidIssuer = issuer, SigningToken = new X509SecurityToken(new X509Certificate2(GetSigningCertificate(issuer + "FederationMetadata/2007-06/FederationMetadata.xml"))) }; return tokenHandler.ValidateToken(token, validationParameters); }
public ClaimsIdentity ValidateJwtToken(string jwt) { var handler = new JWTSecurityTokenHandler(); var validationParameters = new TokenValidationParameters() { AudienceUriMode = AudienceUriMode.Never, SigningToken = new X509SecurityToken(_configuration.Keys.SigningCertificate), ValidIssuer = _configuration.Global.IssuerUri, ValidateExpiration = true }; var principal = handler.ValidateToken(jwt, validationParameters); return(principal.Identities.First()); }
public static bool IsTokenValid(JWTSecurityToken jwt, string audience, string issuer, byte[] signature) { bool result = false; // Create token validation parameters for the signed JWT // This object will be used to verify the cryptographic signature of the received JWT TokenValidationParameters validationParams = new TokenValidationParameters() { AllowedAudience = audience, ValidIssuer = issuer, ValidateExpiration = true, ValidateNotBefore = false, ValidateIssuer = true, ValidateSignature = true, //SigningToken = null SigningToken = new BinarySecretSecurityToken(signature) }; // Create JWT handler // This object is used to write/sign/decode/validate JWTs JWTSecurityTokenHandler jwtHandler = new JWTSecurityTokenHandler(); // Serialize the JWT // This is how our JWT looks on the wire: <Base64UrlEncoded header>.<Base64UrlEncoded body>.<signature> string jwtOnTheWire = jwtHandler.WriteToken(jwt); try { // Validate the token signature (we provide the shared symmetric key in `validationParams`) // This will throw if the signature does not validate // jwtHandler.ValidateToken(jwtOnTheWire, validationParams); jwtHandler.ValidateToken(jwt, validationParams); result = true; } catch { result = false; } return(result); }
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { if (!HasAuthorizationHeaderValue(request.Headers.Authorization)) return base.SendAsync(request, cancellationToken); HttpStatusCode statusCode; string token; if (!TryRetrieveToken(request, out token)) { statusCode = HttpStatusCode.Unauthorized; return Task<HttpResponseMessage>.Factory.StartNew(() => new HttpResponseMessage(statusCode)); } try { JWTSecurityTokenHandler tokenHandler = new JWTSecurityTokenHandler(); var secret = this.SymmetricKey.Replace('-', '+').Replace('_', '/'); TokenValidationParameters validationParameters = new TokenValidationParameters() { AllowedAudience = this.Audience, ValidateIssuer = this.Issuer != null ? true : false, ValidIssuer = this.Issuer, SigningToken = new BinarySecretSecurityToken(Convert.FromBase64String(secret)) }; Thread.CurrentPrincipal = tokenHandler.ValidateToken(token, validationParameters); return base.SendAsync(request, cancellationToken); } catch (SecurityTokenValidationException) { statusCode = HttpStatusCode.Unauthorized; } catch (Exception) { statusCode = HttpStatusCode.InternalServerError; } return Task<HttpResponseMessage>.Factory.StartNew(() => new HttpResponseMessage(statusCode)); }
private static void ValidateJwt(string jwt) { var handler = new JWTSecurityTokenHandler(); var validationParameters = new TokenValidationParameters() { AllowedAudience = realm, SigningToken = new X509SecurityToken(signingCert), ValidIssuer = "http://idsrv.local/trust", ValidateExpiration = true }; var principal = handler.ValidateToken(jwt, validationParameters); Console.WriteLine("Token validated. Claims from token:"); foreach (var claim in principal.Claims) { Console.WriteLine("{0}\n {1}", claim.Type, claim.Value); } Console.WriteLine(); }
protected override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { HttpStatusCode statusCode; string token; var authorisationHeader = request.Headers.Authorization; if (!TryRetrieveToken(request, out token)) { statusCode = HttpStatusCode.Unauthorized; return(Task <HttpResponseMessage> .Factory.StartNew(() => new HttpResponseMessage(statusCode))); } try { X509SecurityToken cert = new X509SecurityToken(new X509Certificate2( GetSigningCertificate(ConfigurationManager.AppSettings["ida:FederationMetadataLocation"]))); JWTSecurityTokenHandler tokenHandler = new JWTSecurityTokenHandler(); TokenValidationParameters validationParameters = new TokenValidationParameters() { AllowedAudience = ConfigurationManager.AppSettings["fa:AllowedAudience"], ValidIssuer = "https://fairlieauthentic.accesscontrol.windows.net/", SigningToken = cert }; ClaimsPrincipal cp = tokenHandler.ValidateToken(token, validationParameters); Thread.CurrentPrincipal = cp; return(base.SendAsync(request, cancellationToken)); } catch (SecurityTokenValidationException e) { statusCode = HttpStatusCode.Unauthorized; } catch (Exception) { statusCode = HttpStatusCode.InternalServerError; } return(Task <HttpResponseMessage> .Factory.StartNew(() => new HttpResponseMessage(statusCode))); }
/// <summary> /// Processes the request based on the path. /// </summary> /// <param name="context">Contains the request and response.</param> public async Task <WebApplication.Api.Controllers.AccountController.GoogleUserViewModel> VerifyGoogleAccessToken(string accessToken, string idToken) { // Validate the ID token if (idToken != null) { JWTSecurityToken token = new JWTSecurityToken(idToken); JWTSecurityTokenHandler jwt = new JWTSecurityTokenHandler(); // Configure validation Byte[][] certBytes = getCertBytes(); for (int i = 0; i < certBytes.Length; i++) { X509Certificate2 certificate = new X509Certificate2(certBytes[i]); X509SecurityToken certToken = new X509SecurityToken(certificate); // Set up token validation TokenValidationParameters tvp = new TokenValidationParameters(); tvp.AllowedAudience = CLIENT_ID; tvp.SigningToken = certToken; tvp.ValidIssuer = "accounts.google.com"; // Enable / disable tests tvp.ValidateNotBefore = false; tvp.ValidateExpiration = true; tvp.ValidateSignature = true; tvp.ValidateIssuer = true; // Account for clock skew. Look at current time when getting the message // "The token is expired" in try/catch block. // This is relative to GMT, for example, GMT-8 is: tvp.ClockSkewInSeconds = 3600 * 13; try { // Validate using the provider ClaimsPrincipal cp = jwt.ValidateToken(token, tvp); if (cp != null) { its.valid = true; its.message = "Valid ID Token."; its.aud = cp.FindFirst("aud").Value; its.azp = cp.FindFirst("azp").Value; its.email = cp.FindFirst("email").Value; its.sub = cp.FindFirst("sub").Value; } } catch (Exception e) { // Multiple certificates are tested. if (its.valid != true) { its.message = "Invalid ID Token."; } if (e.Message.IndexOf("The token is expired") > 0) { // TODO: Check current time in the exception for clock skew. } } } // Get the Google+ id for this user from the "gplus_id" claim. Claim[] claims = token.Claims.ToArray <Claim>(); for (int i = 0; i < claims.Length; i++) { if (claims[i].Type.Equals("gplus_id")) { its.gplus_id = claims[i].Value; } } } // Use the wrapper to return JSON token_status_wrapper tsr = new token_status_wrapper(); tsr.id_token_status = its; tsr.access_token_status = ats; if (its.valid) { WebApplication.Api.Controllers.AccountController.GoogleUserViewModel fbUser = new Api.Controllers.AccountController.GoogleUserViewModel(); fbUser.Email = its.email; fbUser.aud = its.aud; fbUser.azp = its.azp; fbUser.gplus_id = its.gplus_id; fbUser.sub = its.sub; return(fbUser); } return(null); }
public static bool IsTokenValid(JWTSecurityToken jwt, string audience, string issuer, byte[] signature) { bool result = false; // Create token validation parameters for the signed JWT // This object will be used to verify the cryptographic signature of the received JWT TokenValidationParameters validationParams = new TokenValidationParameters() { AllowedAudience = audience, ValidIssuer = issuer, ValidateExpiration = true, ValidateNotBefore = false, ValidateIssuer = true, ValidateSignature = true, //SigningToken = null SigningToken = new BinarySecretSecurityToken(signature) }; // Create JWT handler // This object is used to write/sign/decode/validate JWTs JWTSecurityTokenHandler jwtHandler = new JWTSecurityTokenHandler(); // Serialize the JWT // This is how our JWT looks on the wire: <Base64UrlEncoded header>.<Base64UrlEncoded body>.<signature> string jwtOnTheWire = jwtHandler.WriteToken(jwt); try { // Validate the token signature (we provide the shared symmetric key in `validationParams`) // This will throw if the signature does not validate // jwtHandler.ValidateToken(jwtOnTheWire, validationParams); jwtHandler.ValidateToken(jwt, validationParams); result = true; } catch { result = false; } return result; }
public ClaimsIdentity ValidateJwtToken(string jwt) { var handler = new JWTSecurityTokenHandler(); var validationParameters = new TokenValidationParameters() { AudienceUriMode = AudienceUriMode.Never, SigningToken = new X509SecurityToken(_configuration.Keys.SigningCertificate), ValidIssuer = _configuration.Global.IssuerUri, ValidateExpiration = true }; var principal = handler.ValidateToken(jwt, validationParameters); return principal.Identities.First(); }
/// <summary> /// Processes the request based on the path. /// </summary> /// <param name="context">Contains the request and response.</param> public void ProcessRequest(HttpContext context) { // Get the code from the request POST body. string accessToken = context.Request.Params["access_token"]; string idToken = context.Request.Params["id_token"]; // Validate the ID token if (idToken != null) { JWTSecurityToken token = new JWTSecurityToken(idToken); JWTSecurityTokenHandler jwt = new JWTSecurityTokenHandler(); // Configure validation Byte[][] certBytes = getCertBytes(); for (int i = 0; i < certBytes.Length; i++) { X509Certificate2 certificate = new X509Certificate2(certBytes[i]); X509SecurityToken certToken = new X509SecurityToken(certificate); // Set up token validation TokenValidationParameters tvp = new TokenValidationParameters(); tvp.AllowedAudience = CLIENT_ID; tvp.SigningToken = certToken; tvp.ValidIssuer = "accounts.google.com"; // Enable / disable tests tvp.ValidateNotBefore = false; tvp.ValidateExpiration = true; tvp.ValidateSignature = true; tvp.ValidateIssuer = true; // Account for clock skew. Look at current time when getting the message // "The token is expired" in try/catch block. // This is relative to GMT, for example, GMT-8 is: tvp.ClockSkewInSeconds = 3600 * 13; try { // Validate using the provider ClaimsPrincipal cp = jwt.ValidateToken(token, tvp); if (cp != null) { its.valid = true; its.message = "Valid ID Token."; } } catch (Exception e) { // Multiple certificates are tested. if (its.valid != true) { its.message = "Invalid ID Token."; } if (e.Message.IndexOf("The token is expired") > 0) { // TODO: Check current time in the exception for clock skew. } } } // Get the Google+ id for this user from the "sub" claim. Claim[] claims = token.Claims.ToArray<Claim>(); for (int i = 0; i < claims.Length; i++) { if (claims[i].Type.Equals("sub")) { its.gplus_id = claims[i].Value; } } } // Use Tokeninfo to validate the user and the client. var tokeninfo_request = new Oauth2Service().Tokeninfo(); tokeninfo_request.Access_token = accessToken; // Use Google as a trusted provider to validate the token. // Invalid values, including expired tokens, return 400 Tokeninfo tokeninfo = null; try { tokeninfo = tokeninfo_request.Fetch(); if (tokeninfo.Issued_to != CLIENT_ID){ ats.message = "Access Token not meant for this app."; }else{ ats.valid = true; ats.message = "Valid Access Token."; ats.gplus_id = tokeninfo.User_id; } } catch (Exception stve) { ats.message = "Invalid Access Token."; } // Use the wrapper to return JSON token_status_wrapper tsr = new token_status_wrapper(); tsr.id_token_status = its; tsr.access_token_status = ats; context.Response.StatusCode = 200; context.Response.ContentType = "text/json"; context.Response.Write(JsonConvert.SerializeObject(tsr)); }