public ActionResult Index(string token) { try { var validationParameters = new TokenValidationParameters { IssuerSigningToken = new BinarySecretSecurityToken( TextEncodings.Base64Url.Decode(ConfigurationManager.AppSettings["auth0:ClientSecret"])), ValidIssuer = ConfigurationManager.AppSettings["auth0:Domain"], ValidAudience = ConfigurationManager.AppSettings["auth0:ClientId"] }; var handler = new JwtSecurityTokenHandler(); SecurityToken securityToken; ClaimsPrincipal principal = handler.ValidateToken(token, validationParameters, out securityToken); ClaimsIdentity identity = principal.Identity as ClaimsIdentity; identity.AddClaim(new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "Auth0")); identity.AddClaim(new Claim(ClaimTypes.Name, identity.FindFirst(ClaimTypes.Email).Value)); var sessionToken = new SessionSecurityToken(principal, TimeSpan.FromMinutes(15)); FederatedAuthentication.SessionAuthenticationModule.WriteSessionTokenToCookie(sessionToken); return RedirectToAction("Change"); } catch (Exception ex) { return RedirectToAction("Unauthorized"); } }
public static ClaimsPrincipal AuthenticateIdToken(HttpApplication application, string id_token) { var config = OpenIdConfiguration.Current; var handler = new JwtSecurityTokenHandler(); handler.CertificateValidator = X509CertificateValidator.None; if (!handler.CanReadToken(id_token)) { throw new InvalidOperationException("No SecurityTokenHandler can authenticate this id_token!"); } var parameters = new TokenValidationParameters(); parameters.AllowedAudience = AADClientId; // this is just for Saml // paramaters.AudienceUriMode = AudienceUriMode.Always; parameters.ValidateIssuer = false; var tokens = new List<SecurityToken>(); foreach (var key in config.IssuerKeys.Keys) { tokens.AddRange(key.GetSecurityTokens()); } parameters.SigningTokens = tokens; // validate var principal = (ClaimsPrincipal)handler.ValidateToken(id_token, parameters); // verify nonce VerifyNonce(principal.FindFirst(NonceClaimType).Value); return principal; }
public ClaimsPrincipal Validate(string jwtTokenAsBase64, JwtOptions options) { var tokenHandler = new JwtSecurityTokenHandler(); string keyAsUtf8 = options.JwtSigningKeyAsUtf8; byte[] keyAsBytes = Encoding.UTF8.GetBytes(keyAsUtf8); SecurityToken signingToken = new BinarySecretSecurityToken(keyAsBytes); var tokenValidationParameters = new TokenValidationParameters { IssuerSigningToken = signingToken, ValidAudience = options.Audience, ValidIssuer = options.Issuer }; ClaimsPrincipal principal; try { SecurityToken validatedToken; principal = tokenHandler.ValidateToken(jwtTokenAsBase64, tokenValidationParameters, out validatedToken); } catch (Exception ex) { Debug.Write(ex, "error"); principal = new ClaimsPrincipal(new ClaimsIdentity(authenticationType:"")); } return principal; }
protected virtual Task<TokenValidationResult> ValidateJwtAccessTokenAsync(string jwt) { var handler = new JwtSecurityTokenHandler(); handler.Configuration = new SecurityTokenHandlerConfiguration(); handler.Configuration.CertificateValidationMode = X509CertificateValidationMode.None; handler.Configuration.CertificateValidator = X509CertificateValidator.None; var parameters = new TokenValidationParameters { ValidIssuer = _settings.GetIssuerUri(), SigningToken = new X509SecurityToken(_settings.GetSigningCertificate()), AllowedAudience = string.Format(Constants.AccessTokenAudience, _settings.GetIssuerUri()) }; try { var id = handler.ValidateToken(jwt, parameters); return Task.FromResult(new TokenValidationResult { Claims = id.Claims }); } catch (Exception ex) { _logger.ErrorFormat("JWT token validation error: {0}", ex.ToString()); return Task.FromResult(new TokenValidationResult { IsError = true, Error = Constants.ProtectedResourceErrors.InvalidToken }); } }
public IHttpActionResult DecodeToken(string access_token) { var tokenReceived = new JwtSecurityToken(access_token); var publicOnly = new RSACryptoServiceProvider(); publicOnly.FromXmlString(_configuration.PublicKey.FromBase64String()); var validationParameters = new TokenValidationParameters { ValidIssuer = _configuration.Issuer ,ValidAudience = "http://mysite.com" ,IssuerSigningToken = new RsaSecurityToken(publicOnly) ,ValidateLifetime = true }; var recipientTokenHandler = new JwtSecurityTokenHandler(); SecurityToken securityToken; var claimsPrincipal = recipientTokenHandler.ValidateToken(access_token, validationParameters, out securityToken); var currentTime = (long) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds; if (tokenReceived.Payload.Exp < currentTime) { throw new SecurityTokenValidationException(string.Format("Lifetime validation failed. The token is expired. ValidTo: '{0}' Current time: '{1}'.", tokenReceived.ValidTo, DateTime.UtcNow)); } return Ok(new { header = tokenReceived.Header, payload = tokenReceived.Payload, current = currentTime }); }
public Result<List<Claim>> ParseToken(string token) { var result = new Result<List<Claim>>(); if (String.IsNullOrEmpty(token)) return result; var tokenHandler = new JwtSecurityTokenHandler(); var validationParameters = new TokenValidationParameters() { ValidAudience = "https://api.knowthyshelf.com", IssuerSigningToken = new BinarySecretSecurityToken(TOKEN_SECURITY_KEY), ValidIssuer = "self" }; SecurityToken securityToken; var principal = tokenHandler.ValidateToken(token, validationParameters, out securityToken); var isValidClaim = principal.Claims.FirstOrDefault(); if (isValidClaim?.Value == "IsValid" && securityToken.ValidFrom <= DateTime.UtcNow && securityToken.ValidTo >= DateTime.UtcNow) { result.ResultCode = Enums.ResultCode.Ok; result.Data = principal.Claims.ToList(); } return result; }
public async Task<ActionResult> Callback(string code, string state) { CheckState(state); using (var client = new HttpClient()) { var resp = await client.PostAsync("https://accounts.google.com/o/oauth2/token", new FormUrlEncodedContent(new Dictionary<string, string> { {"code", code}, {"redirect_uri", RedirectUri}, {"grant_type", "authorization_code"}, {"client_id", ClientId}, {"client_secret", ClientSecret} })); resp.EnsureSuccessStatusCode(); var tokenResp = await resp.Content.ReadAsAsync<TokenResponse>(); var certs = await GoogleCertificates.GetCertificates(); var tokenHandler = new JwtSecurityTokenHandler { CertificateValidator = new GoogleCertificateValidator(certs.ToDictionary(t => t.Value.GetCertHashString(), t => t.Value)) }; var validationParameters = new TokenValidationParameters() { AllowedAudience = ClientId, ValidIssuer = "accounts.google.com", SigningTokens = certs.Select(p => new X509SecurityToken(p.Value)) }; var principal = tokenHandler.ValidateToken(tokenResp.id_token, validationParameters); var jwt = new JwtSecurityToken(tokenResp.id_token); var viewModel = new ViewModel { JwtHeader = jwt.Header, JwtPayload = jwt.Payload, Principal = principal }; client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenResp.access_token); resp = await client.GetAsync("https://www.googleapis.com/tasks/v1/users/@me/lists"); resp.EnsureSuccessStatusCode(); var taskLists = await resp.Content.ReadAsAsync<TaskLists>(); foreach(var list in taskLists.items) { resp = await client.GetAsync(string.Format("https://www.googleapis.com/tasks/v1/lists/{0}/tasks",list.id)); resp.EnsureSuccessStatusCode(); var taskList = await resp.Content.ReadAsAsync<TaskList>(); viewModel.Tasks.AddRange(taskList.items.Select(item => item.title)); } return View(viewModel); } }
public async Task<Client> FindClientByIdAsync(string clientId) { var clientsUri = $"admin-api/api/clients/{clientId}"; //var cert = Cert.Load(StoreName.My, StoreLocation.CurrentUser, "b512d01195667dbc7c4222ec6fd563ac64e3d450"); //var handler = new WebRequestHandler(); //handler.ClientCertificates.Add(cert); // Retrieve an access token from the IdentityAdmin /authorize OAuth endpoint using (var client = new HttpClient()) { client.BaseAddress = new Uri(this.identityAdminUri); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var cert = Cert.Load(typeof(IOwinBootstrapper).Assembly, "Cert", "idsrv3test.pfx", "idsrv3test"); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim("name", "idServer"), new Claim("role", "IdentityAdminManager"), new Claim("scope", "idadmin-api") }), TokenIssuerName = "idServer", AppliesToAddress = this.identityAdminUri, Lifetime = new Lifetime(DateTime.Now, DateTime.Now.AddMinutes(10)), SigningCredentials = new X509SigningCredentials(cert) }; var tokenHandler = new JwtSecurityTokenHandler(); var securityToken = tokenHandler.CreateToken(tokenDescriptor); var accessToken = tokenHandler.WriteToken(securityToken); var jwtParams = new TokenValidationParameters { NameClaimType = "name", RoleClaimType = "role", ValidAudience = this.identityAdminUri, ValidIssuer = "idServer", IssuerSigningToken = new X509SecurityToken(cert) }; SecurityToken validatedToken; tokenHandler.ValidateToken(accessToken, jwtParams, out validatedToken); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); var response = await client.GetAsync(clientsUri); var str = await response.Content.ReadAsStringAsync(); } return null; }
public static ClaimsPrincipal ReadToken(string token, out SecurityToken _token) { TokenValidationParameters _params = new TokenValidationParameters() { ValidateIssuer = true, ValidIssuer = TokenConstants.TokenIssuer, ValidAudience = TokenConstants.TokenAudience, IssuerSigningToken = new BinarySecretSecurityToken(TokenConstants.TokenKey), }; _token = null; var jwt = new JwtSecurityTokenHandler() { TokenLifetimeInMinutes = TokenConstants.TokenLifetimeInMinutes }; return jwt.ValidateToken(token, _params, out _token); }
public void Can_create_and_consume_jwt_tokens() { const string issuer = "http://issuer.webapibook.net"; const string audience = "*****@*****.**"; const int lifetimeInMinutes = 5; var tokenHandler = new JwtSecurityTokenHandler(); var symmetricKey = GetRandomBytes(256 / 8); var signingCredentials = new SigningCredentials( new InMemorySymmetricSecurityKey(symmetricKey), "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256", "http://www.w3.org/2001/04/xmlenc#sha256"); var now = DateTime.UtcNow; var claims = new[] { new Claim("sub", "*****@*****.**"), new Claim("email", "*****@*****.**"), new Claim("name", "Alice"), }; var token = new JwtSecurityToken(issuer, audience, claims, new Lifetime(now, now.AddMinutes(lifetimeInMinutes)), signingCredentials); var tokenString = tokenHandler.WriteToken(token); var parts = tokenString.Split('.'); Assert.Equal(3, parts.Length); var validationParameters = new TokenValidationParameters() { AllowedAudience = audience, SigningToken = new BinarySecretSecurityToken(symmetricKey), ValidIssuer = issuer, }; tokenHandler.NameClaimType = ClaimTypes.NameIdentifier; var principal = tokenHandler.ValidateToken(tokenString, validationParameters); var identity = principal.Identities.First(); Assert.Equal("*****@*****.**", identity.Name); Assert.Equal("*****@*****.**", identity.Claims.First(c => c.Type == ClaimTypes.NameIdentifier).Value); Assert.Equal("*****@*****.**", identity.Claims.First(c => c.Type == ClaimTypes.Email).Value); Assert.Equal("Alice", identity.Claims.First(c => c.Type == "name").Value); Assert.Equal(issuer, identity.Claims.First().Issuer); }
public void consume_JSONWebTokenString() { string tokenString = "";//produce_JSONWebTokenString(); //get from somewhere var token = new JwtSecurityToken(tokenString); var validationParams = new TokenValidationParameters { ValidIssuer = "http://myIssuer", ValidAudiences = new List<String>() { "HttpStyleUriParser://myResource" }, IssuerSigningToken = GetSigningKey() }; var handler = new JwtSecurityTokenHandler(); SecurityToken securityToken; var principat = handler.ValidateToken(tokenString, validationParams, out securityToken); }
private static IEnumerable<Claim> ValidateIdentityTokenAsync(string token, string audience, X509Certificate2 certificate) { var parameters = new TokenValidationParameters { ValidAudience = audience, ValidIssuer = "http://localhost:22530", IssuerSigningToken = new X509SecurityToken(certificate) }; var handler = new JwtSecurityTokenHandler(); SecurityToken jwt; var id = handler.ValidateToken(token, parameters, out jwt); return id.Claims; }
private async Task<IEnumerable<Claim>> ValidateIdentityTokenAsync(string token, string state) { var result = await Request .GetOwinContext() .Authentication .AuthenticateAsync("TempCookie"); if (result == null) { throw new InvalidOperationException("No temp cookie"); } if (state != result.Identity.FindFirst("state").Value) { throw new InvalidOperationException("invalid state"); } var parameters = new TokenValidationParameters { ValidAudience = "implicitclient", ValidIssuer = "https://idsrv3.com", IssuerSigningToken = new X509SecurityToken( X509 .LocalMachine .TrustedPeople .SubjectDistinguishedName .Find("CN=idsrv3test", false) .First()) }; var handler = new JwtSecurityTokenHandler(); SecurityToken jwt; var id = handler.ValidateToken(token, parameters, out jwt); if (id.FindFirst("nonce").Value != result.Identity.FindFirst("nonce").Value) { throw new InvalidOperationException("Invalid nonce"); } Request .GetOwinContext() .Authentication .SignOut("TempCookie"); return id.Claims; }
public static ClaimsPrincipal ReadJwtToken(this string token, SecurityTokenDescriptor tokenDescriptor ) { var tokenHandler = new JwtSecurityTokenHandler(); var certificate = (tokenDescriptor.SigningCredentials as X509SigningCredentials).Certificate; var validationParameters = new TokenValidationParameters { ValidAudience = tokenDescriptor.AppliesToAddress, ValidIssuer = tokenDescriptor.TokenIssuerName, IssuerSigningToken = new X509SecurityToken(certificate) }; var validatedToken = new JwtSecurityToken() as SecurityToken; var principal = tokenHandler.ValidateToken(token, validationParameters, out validatedToken); return principal; }
public Task<string> GenerateAccessToken(SecurityTokenDescriptor tokenDescriptor, TokenValidationParameters validationParameters) { return Task.Run(() => { tokenDescriptor.SigningCredentials = new X509SigningCredentials(this.cert); var tokenHandler = new JwtSecurityTokenHandler(); var securityToken = tokenHandler.CreateToken(tokenDescriptor); var accessToken = tokenHandler.WriteToken(securityToken); validationParameters.IssuerSigningToken = new X509SecurityToken(this.cert); SecurityToken validatedToken; tokenHandler.ValidateToken(accessToken, validationParameters, out validatedToken); return accessToken; }); }
public static ClaimsPrincipal ValidateJwtToken(string jwtToken) { var tokenHandler = new JwtSecurityTokenHandler() { RequireExpirationTime = true }; // Parse JWT from the Base64UrlEncoded wire form (<Base64UrlEncoded header>.<Base64UrlEncoded body>.<signature>) JwtSecurityToken parsedJwt = tokenHandler.ReadToken(jwtToken) as JwtSecurityToken; TokenValidationParameters validationParams = new TokenValidationParameters() { AllowedAudience = SecurityConstants.TokenAudience, ValidIssuer = SecurityConstants.TokenIssuer, ValidateIssuer = true, SigningToken = new BinarySecretSecurityToken(SecurityConstants.KeyForHmacSha256), }; return tokenHandler.ValidateToken(parsedJwt, validationParams); }
private IEnumerable<Claim> GetClaimsFromToken(string token, String audience) { const string certString = "MIIDBTCCAfGgAwIBAgIQNQb+T2ncIrNA6cKvUA1GWTAJBgUrDgMCHQUAMBIxEDAOBgNVBAMTB0RldlJvb3QwHhcNMTAwMTIwMjIwMDAwWhcNMjAwMTIwMjIwMDAwWjAVMRMwEQYDVQQDEwppZHNydjN0ZXN0MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqnTksBdxOiOlsmRNd+mMS2M3o1IDpK4uAr0T4/YqO3zYHAGAWTwsq4ms+NWynqY5HaB4EThNxuq2GWC5JKpO1YirOrwS97B5x9LJyHXPsdJcSikEI9BxOkl6WLQ0UzPxHdYTLpR4/O+0ILAlXw8NU4+jB4AP8Sn9YGYJ5w0fLw5YmWioXeWvocz1wHrZdJPxS8XnqHXwMUozVzQj+x6daOv5FmrHU1r9/bbp0a1GLv4BbTtSh4kMyz1hXylho0EvPg5p9YIKStbNAW9eNWvv5R8HN7PPei21AsUqxekK0oW9jnEdHewckToX7x5zULWKwwZIksll0XnVczVgy7fCFwIDAQABo1wwWjATBgNVHSUEDDAKBggrBgEFBQcDATBDBgNVHQEEPDA6gBDSFgDaV+Q2d2191r6A38tBoRQwEjEQMA4GA1UEAxMHRGV2Um9vdIIQLFk7exPNg41NRNaeNu0I9jAJBgUrDgMCHQUAA4IBAQBUnMSZxY5xosMEW6Mz4WEAjNoNv2QvqNmk23RMZGMgr516ROeWS5D3RlTNyU8FkstNCC4maDM3E0Bi4bbzW3AwrpbluqtcyMN3Pivqdxx+zKWKiORJqqLIvN8CT1fVPxxXb/e9GOdaR8eXSmB0PgNUhM4IjgNkwBbvWC9F/lzvwjlQgciR7d4GfXPYsE1vf8tmdQaY8/PtdAkExmbrb9MihdggSoGXlELrPA91Yce+fiRcKY3rQlNWVd4DOoJ/cPXsXwry8pWjNCo5JD8Q+RQ5yZEy7YPoifwemLhTdsBz3hlZr28oCGJ3kbnpW0xGvQb3VHSTVVbeei0CfXoW6iz1"; var cert = new X509Certificate2(Convert.FromBase64String(certString)); var parameters = new TokenValidationParameters { ValidAudience = audience, ValidIssuer = ApplicationConstants.UrlBaseAuth, IssuerSigningToken = new X509SecurityToken(cert) }; var handler = new JwtSecurityTokenHandler(); SecurityToken jwt; var id = handler.ValidateToken(token, parameters, out jwt); return id.Claims; }
static void Main(string[] args) { var securityKey = GetBytes("ThisIsAnImportantStringAndIHaveNoIdeaIfThisIsVerySecureOrNot!"); var tokenHandler = new JwtSecurityTokenHandler(); // Token Creation var now = DateTime.UtcNow; var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, "Pedro"), new Claim(ClaimTypes.Role, "Author"), }), TokenIssuerName = "self", AppliesToAddress = "http://www.example.com", Lifetime = new Lifetime(now, now.AddMinutes(2)), SigningCredentials = new SigningCredentials( new InMemorySymmetricSecurityKey(securityKey), "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256", "http://www.w3.org/2001/04/xmlenc#sha256"), }; var token = tokenHandler.CreateToken(tokenDescriptor); // Generate Token and return string var tokenString = tokenHandler.WriteToken(token); Console.WriteLine(tokenString); // Token Validation var validationParameters = new TokenValidationParameters() { AllowedAudience = "http://www.example.com", SigningToken = new BinarySecretSecurityToken(securityKey), ValidIssuer = "self" }; // from Token to ClaimsPrincipal - easy! var principal = tokenHandler.ValidateToken(tokenString, validationParameters); Console.WriteLine(principal.Claims.Single(x => x.Type == ClaimTypes.Name).Value); Console.ReadLine(); }
public void Can_create_and_validate_token() { var tokenHandler = new JwtSecurityTokenHandler(); var symmetricKey = GetRandomBytes(256 / 8); var now = DateTime.UtcNow; var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, "Pedro"), new Claim(ClaimTypes.NameIdentifier, "*****@*****.**"), new Claim(ClaimTypes.Role, "Author"), new Claim("iat", ToEpochTime(now).ToString(),ClaimValueTypes.Integer), }), TokenIssuerName = "self", AppliesToAddress = "http://www.example.com", Lifetime = new Lifetime(now, now.AddMinutes(2)), SigningCredentials = new SigningCredentials( new InMemorySymmetricSecurityKey(symmetricKey), "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256", "http://www.w3.org/2001/04/xmlenc#sha256"), }; var token = tokenHandler.CreateToken(tokenDescriptor); var tokenString = tokenHandler.WriteToken(token); Console.WriteLine(tokenString); var validationParameters = new TokenValidationParameters() { AllowedAudience = "http://www.example.com", SigningToken = new BinarySecretSecurityToken(symmetricKey), ValidIssuer = "self" }; var principal = tokenHandler.ValidateToken(tokenString, validationParameters); Assert.True(principal.Identities.First().Claims .Any(c => c.Type == ClaimTypes.Name && c.Value == "Pedro")); Assert.True(principal.Identities.First().Claims .Any(c => c.Type == ClaimTypes.Role && c.Value == "Author")); }
public static SignInMessage FromJwt(string jwt, string issuer, string audience, string key) { var message = new SignInMessage(); var handler = new JwtSecurityTokenHandler(); var parameters = new TokenValidationParameters { AllowedAudience = audience, ValidIssuer = issuer, SigningToken = new BinarySecretSecurityToken(Convert.FromBase64String(key)) }; var principal = handler.ValidateToken(jwt, parameters); var claim = principal.FindFirst("returnUrl"); if (claim != null) { message.ReturnUrl = claim.Value; } return message; }
public override ReadOnlyCollection<ClaimsIdentity> ValidateToken(SecurityToken token) { var saml = token as Saml2SecurityToken; var samlAttributeStatement = saml.Assertion.Statements.OfType<Saml2AttributeStatement>().FirstOrDefault(); var jwt = samlAttributeStatement.Attributes.Where(sa => sa.Name.Equals("jwt", StringComparison.OrdinalIgnoreCase)).SingleOrDefault().Values.Single(); var parameters = new TokenValidationParameters { ValidAudience = _issuerName.EnsureTrailingSlash() + "resources", ValidIssuer = _issuerName, IssuerSigningToken = new X509SecurityToken(_signingCert) }; SecurityToken validatedToken; var handler = new JwtSecurityTokenHandler(); var principal = handler.ValidateToken(jwt, parameters, out validatedToken); var ci = new ReadOnlyCollection<ClaimsIdentity>(new List<ClaimsIdentity> { principal.Identities.First() }); if (_requiredScopes.Any()) { bool found = false; foreach (var scope in _requiredScopes) { if (principal.HasClaim("scope", scope)) { found = true; break; } } if (found == false) { throw new SecurityTokenValidationException("Insufficient Scope"); } } return ci; }
/// <summary> /// Validates JWT tokens from different providers and returns a userId extracted from token /// </summary> public static string ValidateAndGetUserId(string tokenString) { var jwtHandler = new JwtSecurityTokenHandler(); var validationParams = new TokenValidationParameters { ValidateAudience = false, ValidateIssuer = true, ValidIssuers = JwtParsers.Keys, IssuerSigningKeyResolver = (t, securityToken, identifier, p) => { var securityKeyIdentifier = identifier.Count > 0 ? identifier[0].Id : string.Empty; return JwtParsers[((JwtSecurityToken)securityToken).Issuer].GetSecurityKey(securityKeyIdentifier); } }; SecurityToken validatedToken; var principal = jwtHandler.ValidateToken(tokenString, validationParams, out validatedToken); var jwtSecurityToken = (JwtSecurityToken)validatedToken; return JwtParsers[jwtSecurityToken.Issuer].GetUserId(principal); }
/// <summary> /// Extracts the user information from a provided access token /// </summary> public static string GetUserFromToken(string tokenString) { // Initialize the token handler and validation parameters var tokenHandler = new JwtSecurityTokenHandler(); var tokenValidation = new TokenValidationParameters() { ValidAudience = SettingsHelper.Audience, ValidIssuer = SettingsHelper.Audience, IssuerSigningToken = new X509SecurityToken(getCert()) }; try { // Try to extract the user principal from the token SecurityToken token = null; var principal = tokenHandler.ValidateToken(tokenString, tokenValidation, out token); return principal.Identity.Name; } catch (Exception) { return String.Empty; } }
public static ClaimsPrincipal Validate(string token, InMemorySymmetricSecurityKey signingKey, string issuer, string audience) { var tokenHandler = new JwtSecurityTokenHandler(); // Parse JWT from the Base64UrlEncoded wire form //(<Base64UrlEncoded header>.<Base64UrlEncoded body>.<signature>) //JwtSecurityToken parsedJwt = tokenHandler.ReadToken(token) as JwtSecurityToken; TokenValidationParameters validationParams = new TokenValidationParameters() { ValidateAudience = true, ValidateIssuer = true, ValidAudience = audience, ValidIssuer = issuer, IssuerSigningKey = signingKey, ValidateLifetime = true }; SecurityToken securityToken = null; return tokenHandler.ValidateToken(token, validationParams, out securityToken); }
static void Main(string[] args) { RSACryptoServiceProvider publicAndPrivate = new RSACryptoServiceProvider(); RsaKeyGenerationResult keyGenerationResult = GenerateRsaKeys(); publicAndPrivate.FromXmlString(keyGenerationResult.PublicAndPrivateKey); JwtSecurityToken jwtToken = new JwtSecurityToken (issuer: "http://issuer.com", audience: "http://mysite.com" , claims: new List<Claim>() { new Claim(ClaimTypes.Name, "Andras Nemes") } , lifetime: new Lifetime(DateTime.UtcNow, DateTime.UtcNow.AddHours(1)) , signingCredentials: new SigningCredentials(new RsaSecurityKey(publicAndPrivate) , SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest)); JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler(); string tokenString = tokenHandler.WriteToken(jwtToken); Console.WriteLine("Token string: {0}", tokenString); Console.ReadLine(); // Decoding JwtSecurityToken tokenReceived = new JwtSecurityToken(tokenString); RSACryptoServiceProvider publicOnly = new RSACryptoServiceProvider(); publicOnly.FromXmlString(keyGenerationResult.PublicKeyOnly); TokenValidationParameters validationParameters = new TokenValidationParameters() { ValidIssuer = "http://issuer.com" , AllowedAudience = "http://mysite.com" , SigningToken = new RsaSecurityToken(publicOnly) }; JwtSecurityTokenHandler recipientTokenHandler = new JwtSecurityTokenHandler(); ClaimsPrincipal claimsPrincipal = recipientTokenHandler.ValidateToken(tokenReceived, validationParameters); }
public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken) { var authHeader = context.Request.Headers.Authorization; if (authHeader != null && String.Equals(authHeader.Scheme, "Bearer", StringComparison.InvariantCultureIgnoreCase) && authHeader.Parameter != null) { try { var tokenEncrypted = Base64UrlEncoder.DecodeBytes(authHeader.Parameter); var tokenDecrypted = MachineKey.Unprotect(tokenEncrypted); var tokenString = Encoding.Unicode.GetString(tokenDecrypted); var tokenValidationParams = new TokenValidationParameters { IssuerSigningToken = new BinarySecretSecurityToken(Convert.FromBase64String(JsonWebTokenFactory.SymmetricKey)), ValidAudience = JsonWebTokenFactory.Audience, ValidIssuer = JsonWebTokenFactory.TokenIssuerName }; var handler = new JwtSecurityTokenHandler(); SecurityToken token; IPrincipal principal = handler.ValidateToken(tokenString, tokenValidationParams, out token); context.Principal = principal; } catch (SecurityTokenExpiredException) { context.ErrorResult = new ApiErrorResult(ApiErrorCode.ExpiredToken); } catch (Exception) { context.ErrorResult = new ApiErrorResult(ApiErrorCode.InvalidToken); } } return Task.FromResult(default(object)); }
public bool VerifyToken(string token, ClientEntity client) { var secretKey = Convert.FromBase64String(client.SecurityKey); var tokenHandler = new JwtSecurityTokenHandler(); var validationParameters = new TokenValidationParameters() { ValidIssuer = client.RowKey, ValidAudience = client.Audience, IssuerSigningToken = new BinarySecretSecurityToken(secretKey) }; try { SecurityToken securityToken; tokenHandler.ValidateToken(token, validationParameters, out securityToken); return true; } catch (Exception e) { Console.WriteLine("Error {0}", e.Message); return false; } }
/// <summary> /// Generates an access token specific to a user and file /// </summary> public static bool ValidateToken(string tokenString, string container, string docId) { // Initialize the token handler and validation parameters var tokenHandler = new JwtSecurityTokenHandler(); var tokenValidation = new TokenValidationParameters() { ValidAudience = SettingsHelper.Audience, ValidIssuer = SettingsHelper.Audience, IssuerSigningToken = new X509SecurityToken(getCert()) }; try { // Try to validate the token SecurityToken token = null; var principal = tokenHandler.ValidateToken(tokenString, tokenValidation, out token); return (principal.HasClaim("container", container) && principal.HasClaim("docid", docId)); } catch (Exception) { return false; } }
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { string token; HttpResponseMessage errorResponse = null; if (TryRetrieveToken(request, out token)) { try { var tokenHandler = new JwtSecurityTokenHandler(); var secret = this.SymmetricKey.Replace('-', '+').Replace('_', '/'); var 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); } catch (SecurityTokenValidationException ex) { errorResponse = request.CreateErrorResponse(HttpStatusCode.Unauthorized, ex); } catch (Exception ex) { errorResponse = request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex); } } return errorResponse != null ? Task.FromResult(errorResponse) : base.SendAsync(request, cancellationToken); }
/// <summary> /// A helper that will throw if the tokenString cannot be parsed or the signature is invalid /// </summary> /// <param name="tokenString">The JWT token string</param> /// <param name="secretKey">The key used to sign the token JWT token</param> private static void ValidateToken(string tokenString) { JwtSecurityToken parsedToken = new JwtSecurityToken(tokenString); TokenValidationParameters validationParams = new TokenValidationParameters { ValidateAudience = true, ValidAudience = Audience, ValidateIssuer = true, ValidIssuer = Issuer, ValidateLifetime = parsedToken.Payload.Exp.HasValue, // support tokens with no expiry IssuerSigningToken = new BinarySecretSecurityToken(HmacSigningCredentials.ParseKeyString(SigningKey)) }; JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler(); SecurityToken validatedToken = null; tokenHandler.ValidateToken(tokenString, validationParams, out validatedToken); }