public string Protect(AuthenticationTicket data) { if (data == null) { throw new ArgumentNullException("data"); } string audienceId = System.Configuration.ConfigurationManager.AppSettings["as:AudienceId"]; string symmetricKeyAsBase64 = System.Configuration.ConfigurationManager.AppSettings["as:AudienceSecret"]; var keyByteArray = TextEncodings.Base64Url.Decode(symmetricKeyAsBase64); var signingKey = new HmacSigningCredentials(keyByteArray); var issued = data.Properties.IssuedUtc; var expires = data.Properties.ExpiresUtc; var token = new System.IdentityModel.Tokens.JwtSecurityToken(_issuer, audienceId, data.Identity.Claims, issued.Value.UtcDateTime, expires.Value.UtcDateTime, signingKey); var handler = new System.IdentityModel.Tokens.JwtSecurityTokenHandler(); var jwt = handler.WriteToken(token); //this.Unprotect("eyJ0eXAiOiJKV1QiLCJhbGciOiJodHRwOi8vd3d3LnczLm9yZy8yMDAxLzA0L3htbGRzaWctbW9yZSNobWFjLXNoYTM4NCJ9.eyJuYW1laWQiOiIyZGMxZTRlMC0xNjdjLTQ4MWQtOTZjMC0zOGQzYmIxNzA5ZDgiLCJ1bmlxdWVfbmFtZSI6IlVzdWFyaW8iLCJodHRwOi8vc2NoZW1hcy5taWNyb3NvZnQuY29tL2FjY2Vzc2NvbnRyb2xzZXJ2aWNlLzIwMTAvMDcvY2xhaW1zL2lkZW50aXR5cHJvdmlkZXIiOiJBU1AuTkVUIElkZW50aXR5IiwiQXNwTmV0LklkZW50aXR5LlNlY3VyaXR5U3RhbXAiOiJiNWNiMGMxYi05OWI2LTQ1NmItOWRiMC0xODRiNjE0NzVjNDciLCJyb2xlIjoiVXNlciIsIk15VHlwZSI6IjQ1IiwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo4MDg5IiwiYXVkIjoiVHdpY2VUYWxlbnQiLCJleHAiOjE0ODk4NTMwNzgsIm5iZiI6MTQ4OTc2NjY3OH0.wuj8cRpwjCr75eyLrPpgvwUk8l0cmR07Cxetm_Ei2_Ym6At32QteM22tqT2hSaph"); return(jwt); }
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { string tokenRaw = string.Empty; try { if (!TryRetrieveToken(request, out tokenRaw)) { return base.SendAsync(request, cancellationToken); } var validationParameters = new TokenValidationParameters() { ValidIssuer = SecurityHelper.CertificateValidIssuer, ValidAudience = SecurityHelper.CertificateValidAudience, IssuerSigningToken = new X509SecurityToken(SecurityHelper.GetCertificate()), ValidateLifetime = false, ValidateAudience = true, ValidateIssuer = true, ValidateIssuerSigningKey = true, //ClockSkew = new TimeSpan(40, 0, 0) }; SecurityToken token = new JwtSecurityToken(); ClaimsPrincipal principal = new JwtSecurityTokenHandler().ValidateToken(tokenRaw, validationParameters, out token); Thread.CurrentPrincipal = principal; if (HttpContext.Current != null) { HttpContext.Current.User = Thread.CurrentPrincipal; } } catch (Exception ex) { Trace.Write(ex); } return base.SendAsync(request, cancellationToken); }
public static JwtSecurityToken CreateToken( string issuer = null, string audience = null, IEnumerable<string> scope = null, int ttl = 360, List<Claim> additionalClaims = null, X509Certificate2 signingCertificate = null) { if (additionalClaims == null) { additionalClaims = new List<Claim>(); } if (scope != null && scope.Any()) { scope.ToList().ForEach(s => additionalClaims.Add(new Claim("scope", s))); } var credential = new X509SigningCredentials(signingCertificate ?? DefaultSigningCertificate); var token = new JwtSecurityToken( issuer ?? DefaultIssuer, audience ?? DefaultAudience, additionalClaims, DateTime.UtcNow, DateTime.UtcNow.AddSeconds(ttl), credential); token.Header.Add( "kid", Base64Url.Encode(credential.Certificate.GetCertHash())); return token; }
// GET api/profileapi?accesstoken= public UserProfile Get(string accesstoken) { JwtSecurityToken jwToken = new JwtSecurityToken(accesstoken); var Issuer = ConfigurationRepository.Global.IssuerUri; if (jwToken.Issuer.ToLower().Equals(Issuer.ToLower())) { RelyingParty rp; if (RelyingPartyRepository.TryGet(jwToken.Audience, out rp)) { try { var claims = ValidateJwtToken(jwToken, rp); return UserManagementRepository.GetByUsername(claims.Name); } catch (SecurityTokenValidationException ex) { throw new UnauthorizedAccessException(); } catch (Exception e) { throw new UnauthorizedAccessException(); } } else { throw new Exception("RP is false"); } } else { throw new Exception("Issuer is false"); } }
public void CanCreateReportEmbedToken() { var workspaceId = Guid.NewGuid().ToString(); var reportId = Guid.NewGuid().ToString(); var token = PowerBIToken.CreateReportEmbedToken("Contoso", workspaceId, reportId, "TestUser", new []{ "TestRole" }); Assert.IsNotNull(token); var jwt = token.Generate(this.accessKey); Assert.IsFalse(string.IsNullOrEmpty(jwt)); var decodedToken = new JwtSecurityToken(jwt); var versionClaim = decodedToken.Claims.FirstOrDefault(c => c.Type == PowerBIToken.ClaimTypes.Version); var wcnClaim = decodedToken.Claims.FirstOrDefault(c => c.Type == PowerBIToken.ClaimTypes.WorkspaceCollectionName); var widClaim = decodedToken.Claims.FirstOrDefault(c => c.Type == PowerBIToken.ClaimTypes.WorkspaceId); var ridCliam = decodedToken.Claims.FirstOrDefault(c => c.Type == PowerBIToken.ClaimTypes.ReportId); var usernameClaim = decodedToken.Claims.FirstOrDefault(c => c.Type == PowerBIToken.ClaimTypes.Username); var rolesClaim = decodedToken.Claims.FirstOrDefault(c => c.Type == PowerBIToken.ClaimTypes.Roles); Assert.AreEqual("PowerBISDK", decodedToken.Issuer); Assert.IsTrue(decodedToken.Audiences.Contains("https://analysis.windows.net/powerbi/api")); Assert.IsTrue(decodedToken.ValidTo >= DateTime.UtcNow); Assert.IsTrue(decodedToken.ValidTo <= DateTime.UtcNow.AddHours(1)); Assert.AreEqual("0.2.0", versionClaim.Value); Assert.AreEqual("Contoso", wcnClaim.Value); Assert.AreEqual(workspaceId, widClaim.Value); Assert.AreEqual(reportId, ridCliam.Value); Assert.AreEqual("TestUser", usernameClaim.Value); Assert.AreEqual("TestRole", rolesClaim.Value); }
private static bool ValidateToken(string encodedToken, string userEmail, User.AppType appType) { JwtSecurityToken token = new JwtSecurityToken(encodedToken); if (token.Claims == null) { return false; } Dictionary<string, string> claimVals = token.Claims.ToDictionary(x => x.Type, x => x.Value); if (claimVals["iss"] != "accounts.google.com" || claimVals["azp"] != ConfidentialData.GoogleClientIdDictionary[appType] || claimVals["aud"] != ConfidentialData.GoogleWebAppClientId || claimVals["email"] != userEmail) { return false; } // Check token hasn't expired DateTime expirationDate = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); expirationDate = expirationDate.AddSeconds(int.Parse(claimVals["exp"])); // This is a valid token for this app if it's still in date! return expirationDate.ToLocalTime() >= DateTime.Now; }
public static string CreateTokenString(JwtSecurityToken token) { JwtSecurityTokenHandler.OutboundClaimTypeMap = new Dictionary<string, string>(); var handler = new JwtSecurityTokenHandler(); return handler.WriteToken(token); }
public void JwtSecurityTokenHandler_Extensibility() { DerivedJwtSecurityTokenHandler handler = new DerivedJwtSecurityTokenHandler() { DerivedTokenType = typeof(DerivedJwtSecurityToken) }; JwtSecurityToken jwt = new JwtSecurityToken ( issuer: Issuers.GotJwt, audience: Audiences.AuthFactors, claims: ClaimSets.Simple(Issuers.GotJwt, Issuers.GotJwt), signingCredentials: KeyingMaterial.DefaultSymmetricSigningCreds_256_Sha2, expires: DateTime.UtcNow + TimeSpan.FromHours(10), notBefore: DateTime.UtcNow ); string encodedJwt = handler.WriteToken(jwt); TokenValidationParameters tvp = new TokenValidationParameters() { IssuerSigningKey = KeyingMaterial.DefaultSymmetricSecurityKey_256, ValidateAudience = false, ValidIssuer = Issuers.GotJwt, }; ValidateDerived(encodedJwt, handler, tvp, ExpectedException.NoExceptionExpected); }
public async Task<IHttpActionResult> CreateToken(Token token) { var publicAndPrivate = new RSACryptoServiceProvider(); publicAndPrivate.FromXmlString(_configuration.PrivateKey.FromBase64String()); var jwtToken = new JwtSecurityToken( issuer: _configuration.Issuer, audience: "http://mysite.com" , claims: new List<Claim>() { new Claim(ClaimTypes.Name, token.username) } , notBefore: DateTime.UtcNow , expires: DateTime.UtcNow.AddMinutes(1) , signingCredentials: new SigningCredentials( new RsaSecurityKey(publicAndPrivate) ,SecurityAlgorithms.RsaSha256Signature ,SecurityAlgorithms.Sha256Digest) ); var tokenHandler = new JwtSecurityTokenHandler(); var tokenString = tokenHandler.WriteToken(jwtToken); return Ok(new { access_token = tokenString, expires_in = new TimeSpan(0,0, 1,0).TotalSeconds, expires_on = (long)(DateTime.UtcNow.AddMinutes(1) - new DateTime(1970, 1, 1)).TotalSeconds }); }
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 }); }
/// <summary> /// Creates the json web token. /// </summary> /// <param name="token">The token.</param> /// <param name="credentials">The credentials.</param> /// <returns></returns> protected virtual string CreateJsonWebToken(Token token, SigningCredentials credentials) { var jwt = new JwtSecurityToken( token.Issuer, token.Audience, token.Claims, DateTimeHelper.UtcNow, DateTimeHelper.UtcNow.AddSeconds(token.Lifetime), credentials); // amr is an array - if there is only a single value turn it into an array if (jwt.Payload.ContainsKey("amr")) { var amrValue = jwt.Payload["amr"] as string; if (amrValue != null) { jwt.Payload["amr"] = new string[] { amrValue }; } } var x509credential = credentials as X509SigningCredentials; if (x509credential != null) { jwt.Header.Add("kid", Base64Url.Encode(x509credential.Certificate.GetCertHash())); } var handler = new JwtSecurityTokenHandler(); return handler.WriteToken(jwt); }
public string CreateAssertionToken() { var now = DateTime.Now.ToUniversalTime(); var jwt = new JwtSecurityToken(_clientId, _audience, new List<Claim>() { new Claim(JwtClaimTypes.JwtId, Guid.NewGuid().ToString()), new Claim(JwtClaimTypes.Subject, _clientId), new Claim(JwtClaimTypes.IssuedAt, EpochTime.GetIntDate(now).ToString(), ClaimValueTypes.Integer64) }, now, now.AddMinutes(1), new X509SigningCredentials(_certificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest ) ); if (_embedCertificate) { var rawCertificate = Convert.ToBase64String(_certificate.Export(X509ContentType.Cert)); jwt.Header.Add(JwtHeaderParameterNames.X5c, new[] {rawCertificate}); } var tokenHandler = new JwtSecurityTokenHandler(); return tokenHandler.WriteToken(jwt); }
protected virtual SecurityToken CreateSecurityToken(ProtocolResponse oauthResponse) { string tokenType = oauthResponse.BodyParameters["token_type"]; string accessTokenString = oauthResponse.BodyParameters["access_token"]; var token = new JwtSecurityToken(accessTokenString); return token; }
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); } }
protected override ClaimsIdentity CreateClaimsIdentity(JwtSecurityToken jwt, string issuer, TokenValidationParameters validationParameters) { OrganisationIdentity result = null; ClaimsIdentity claimsIdentity = base.CreateClaimsIdentity(jwt, issuer, validationParameters); if (claimsIdentity != null) result = new OrganisationIdentity(claimsIdentity); Threading.Thread.CurrentPrincipal = new ClaimsPrincipal(result); return result; }
// // GET: /UserProfile/ public async Task<ActionResult> Index() { // // Retrieve the user's name, tenantID, and access token since they are parameters used to query the Graph API. // UserProfile profile; string jwtToken = ClaimsPrincipal.Current.FindFirst(Configuration.ClaimsJwtToken).Value; JwtSecurityToken token = new JwtSecurityToken(jwtToken); string userObjectID = ClaimsPrincipal.Current.FindFirst(Configuration.ClaimsObjectidentifier).Value; AuthenticationContext authContext = new AuthenticationContext(Configuration.Authority, new NaiveSessionCache(userObjectID)); try { ActiveDirectoryClient activeDirectoryClient = Factory.GetActiveDirectoryClientAsApplication(jwtToken); User userProfile = (User)await activeDirectoryClient.Users.GetByObjectId(userObjectID).ExecuteAsync(); List<string> membergroups = (await userProfile.GetMemberGroupsAsync(false)).ToList(); var groups = await activeDirectoryClient.Groups.ExecuteAsync(); profile = new UserProfile(); profile.Token = token; profile.MemberGroups = membergroups; profile.AllGroups = groups.CurrentPage; profile.User = userProfile; return View(profile); } catch (Exception) { // // If the call failed, then drop the current access token and show the user an error indicating they might need to sign-in again. // var todoTokens = authContext.TokenCache.ReadItems().Where(a => a.Resource == Configuration.GraphResourceId); foreach (TokenCacheItem tci in todoTokens) authContext.TokenCache.DeleteItem(tci); // // If refresh is set to true, the user has clicked the link to be authorized again. // if (Request.QueryString["reauth"] == "True") { // // Send an OpenID Connect sign-in request to get a new set of tokens. // If the user still has a valid session with Azure AD, they will not be prompted for their credentials. // The OpenID Connect middleware will return to this controller after the sign-in response has been handled. // HttpContext.GetOwinContext().Authentication.Challenge(OpenIdConnectAuthenticationDefaults.AuthenticationType); } // // The user needs to re-authorize. Show them a message to that effect. // profile = new UserProfile(); ViewBag.ErrorMessage = "AuthorizationRequired"; return View(profile); } }
private static void DecodeSessionToken(string sessionToken) { var token = new JwtSecurityToken(sessionToken); "\nSession token claims:".ConsoleYellow(); foreach (var claim in token.Claims) { Console.WriteLine(" " + claim.Type); string.Format(" {0}\n", claim.Value).ConsoleGreen(); } }
public string produce_JSONWebTokenString() { var token = new JwtSecurityToken( issuer: "http://myIssuere", audience: "http://myIssuere", claims: GetClaims(), signingCredentials: GetKey(), notBefore: DateTime.UtcNow, expires: DateTime.UtcNow.AddHours(1)); return new JwtSecurityTokenHandler().WriteToken(token); }
internal void Parse(string accessToken) { /** * ADFS does not have a user endpoint that I know of. Need to assume * token is a JWT and that claims for the user are contained therein. */ var token = new JwtSecurityToken(accessToken); AccessToken = accessToken; // only got here if token was a valid jwt Claims = token.Claims.ToArray(); Issuer = token.Issuer; }
protected virtual string CreateJsonWebToken(Token token, SigningCredentials credentials) { var jwt = new JwtSecurityToken( token.Issuer, token.Audience, token.Claims, new Lifetime(DateTime.UtcNow, DateTime.UtcNow.AddSeconds(token.Lifetime)), credentials); var handler = new JwtSecurityTokenHandler(); return handler.WriteToken(jwt); }
public GoogleAccount Post(Reques request) { var jwt = new JwtSecurityToken(request.IdToken); // do some more verification here return new GoogleAccount { Sub = jwt.Payload["sub"].ToString(), Email = jwt.Payload["email"].ToString(), }; }
public void SetJwtAuthorizationHeaderWithDurationProperlySetsTokenLifetime() { var sut = new HttpClient(); var duration = TimeSpan.FromSeconds(60); sut.SetJwtAuthorizationHeader( this.certificate, "http://www.example.com", null, "self", duration); var token = new JwtSecurityToken(sut.DefaultRequestHeaders.Authorization.Parameter); Assert.Equal(duration, token.ValidTo - token.ValidFrom); }
public static string GenerateToken(this ClaimsIdentity identity, string audienceId, string symmetricKeyAsBase64, string issuer, DateTimeOffset? issued, DateTimeOffset? expires) { var keyByteArray = TextEncodings.Base64Url.Decode(symmetricKeyAsBase64); var signingKey = new HmacSigningCredentials(keyByteArray); var token = new JwtSecurityToken(issuer, audienceId, identity.Claims, issued.Value.UtcDateTime, expires.Value.UtcDateTime, signingKey); var handler = new JwtSecurityTokenHandler(); string jwt = handler.WriteToken(token); return jwt; }
public static ClaimsPrincipal ValidateIdentityToken(string token, string issuer, string audience, X509Certificate2 signingCertificate) { var idToken = new JwtSecurityToken(token); var handler = new JwtSecurityTokenHandler(); var parameters = new TokenValidationParameters { ValidIssuer = issuer, AllowedAudience = audience, SigningToken = new X509SecurityToken(signingCertificate) }; return handler.ValidateToken(token, parameters); }
private AzureFunctionsPrincipal ParsePortalToken(string portalToken) { if (string.IsNullOrEmpty(portalToken)) { throw new ArgumentException($"{nameof(portalToken)} cannot be null or empty."); } var jwt = new JwtSecurityToken(portalToken); var principalName = jwt.Claims.FirstOrDefault(c => c.Type == Email)?.Value ?? jwt.Claims.FirstOrDefault(c => c.Type == UniqueName)?.Value; var displayName = jwt.Claims.FirstOrDefault(c => c.Type == Name)?.Value ?? jwt.Claims.FirstOrDefault(c => c.Type == GivenName)?.Value; return new AzureFunctionsPrincipal(new AzureFunctionsIdentity(principalName ?? displayName)); }
/// <summary> /// Validates that a <see cref="JwtSecurityToken"/> is valid as per http://openid.net/specs/openid-connect-core-1_0.html /// </summary> /// <param name="jwt">the <see cref="JwtSecurityToken"/>to validate.</param> /// <param name="validationContext">the <see cref="OpenIdConnectProtocolValidationContext"/> to use for validating.</param> /// <exception cref="ArgumentNullException">if 'jwt' is null.</exception> /// <exception cref="ArgumentNullException">if 'validationContext' is null.</exception> /// <exception cref="OpenIdConnectProtocolException">if the <see cref="JwtSecurityToken"/> is missing any required claims as per: http://openid.net/specs/openid-connect-core-1_0.html#IDToken </exception> /// <remarks><see cref="OpenIdConnectProtocolValidationContext.Nonce"/> and <see cref="OpenIdConnectProtocolValidationContext.AuthorizationCode"/> will be validated if they are not 'null' or 'whitespace'.</remarks> public static void Validate(JwtSecurityToken jwt, OpenIdConnectProtocolValidationContext validationContext) { if (jwt == null) throw new ArgumentNullException("jwt"); if (validationContext == null) throw new ArgumentNullException("validationContext"); // required claims if (jwt.Payload.Aud.Count == 0) throw new OpenIdConnectProtocolException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10309, JwtRegisteredClaimNames.Aud.ToLowerInvariant(), jwt)); if (!jwt.Payload.Exp.HasValue) throw new OpenIdConnectProtocolException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10309, JwtRegisteredClaimNames.Exp.ToLowerInvariant(), jwt)); if (!jwt.Payload.Iat.HasValue) throw new OpenIdConnectProtocolException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10309, JwtRegisteredClaimNames.Iat.ToLowerInvariant(), jwt)); if (jwt.Payload.Iss == null) throw new OpenIdConnectProtocolException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10309, JwtRegisteredClaimNames.Iss.ToLowerInvariant(), jwt)); OpenIdConnectProtocolValidationParameters validationParameters = validationContext.OpenIdConnectProtocolValidationParameters; // sub is optional in RC2 if (validationParameters.RequireSub && (string.IsNullOrWhiteSpace(jwt.Payload.Sub))) throw new OpenIdConnectProtocolException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10309, JwtRegisteredClaimNames.Sub.ToLowerInvariant(), jwt)); // optional claims if (validationParameters.RequireAcr && string.IsNullOrWhiteSpace(jwt.Payload.Acr)) throw new OpenIdConnectProtocolException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10312, jwt)); if (validationParameters.RequireAmr && string.IsNullOrWhiteSpace(jwt.Payload.Amr)) throw new OpenIdConnectProtocolException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10313, jwt)); if (validationParameters.RequireAuthTime && string.IsNullOrWhiteSpace(jwt.Payload.AuthTime)) throw new OpenIdConnectProtocolException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10314, jwt)); if (validationParameters.RequireAzp && string.IsNullOrWhiteSpace(jwt.Payload.Azp)) throw new OpenIdConnectProtocolException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10315, jwt)); if (validationParameters.RequireNonce && string.IsNullOrWhiteSpace(validationContext.Nonce)) throw new OpenIdConnectProtocolException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10311, jwt)); if (!string.IsNullOrWhiteSpace(validationContext.Nonce)) ValidateNonce(jwt, validationContext.Nonce); if (!string.IsNullOrWhiteSpace(validationContext.AuthorizationCode)) ValidateCHash(jwt, validationContext.AuthorizationCode, validationParameters.AlgorithmMap); }
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 ValidateJsonWebToken(string tokenString, SsoSettings settings, IList<string> audiences) { try { TokenReceived = new JwtSecurityToken(tokenString); SecurityToken securityToken; _log.DebugFormat("JWT Validation securityAlgorithm={0}, audience[0]={1}, audience[1]={2}", settings.ValidationType, audiences[0], audiences[1]); switch(settings.ValidationType) { case ValidationTypes.RSA_SHA256: RSACryptoServiceProvider publicOnly = new RSACryptoServiceProvider(); //"<RSAKeyValue><Modulus>zeyPa4SwRb0IO+KMq20760ZmaUvy/qzecdOkRUNdNpdUe1E72Xt1WkAcWNu24/UeS3pETu08rVTqHJUMfhHcSKgL7LAk/MMj2inGFxop1LipGZSnqZhnjsfj1ERJL5eXs1O9hqyAcXvY4A2wo67qqv/lbHLKTW59W+YQkbIOVR4nQlbh1lK1TIY+oqK0J/5Ileb4QfERn0Rv/J/K0fy6VzLmVt+kg9MRNxYwnVsC3m5/kIu1fw3OpZxcaCC68SRqLLb/UXmaJM8NXYKkAkHKxT4DQqSk6KbFSQG6qi49Q34akohekzxjxmmGeoO5tsFCuMJofKAsBKKtOkLPaJD2rQ==</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>" publicOnly.FromXmlString(settings.PublicKey); securityToken = new RsaSecurityToken(publicOnly); break; case ValidationTypes.HMAC_SHA256: //var key = "zeyPa4SwRb0IO+KMq20760ZmaUvy/qzecdOkRUNdNpdUe1E72Xu24/UeS3pETu"; securityToken = new BinarySecretSecurityToken(GetBytes(settings.PublicKey)); break; case ValidationTypes.X509: var certificate = new Certificate(); certificate.LoadCertificate(settings.PublicKey); securityToken = new X509SecurityToken(certificate.cert); break; default: _log.ErrorFormat("ValidationType has wrong value: {0}", settings.ValidationType); throw new ArgumentException("ValidationType has wrong value"); } TokenValidationParameters validationParameters = new TokenValidationParameters { ValidIssuer = settings.Issuer, AllowedAudiences = audiences, ValidateIssuer = true, SigningToken = securityToken }; JwtSecurityTokenHandler recipientTokenHandler = new JwtSecurityTokenHandler { MaxClockSkew = MAX_CLOCK_SKEW }; ClaimsPrincipalReceived = recipientTokenHandler.ValidateToken(TokenReceived, validationParameters); } catch (Exception e) { _log.ErrorFormat("JWT Validation error. {0}", e); } }
public String Decode(String jwtTokenOrAuthorizationHeader, String base64EncodedSecret, String validAudience, String validIssuer) { Contract.Requires(jwtTokenOrAuthorizationHeader != null); Contract.Requires(base64EncodedSecret != null); Contract.Ensures(Contract.Result<String>() != null); var jwtEncodedString = GetJwtTokenFromPossiblyHeader(jwtTokenOrAuthorizationHeader); ValidateJwtWithHs256(jwtEncodedString, base64EncodedSecret, validAudience, validIssuer); var payload = new JwtSecurityToken(jwtEncodedString).Payload; Contract.Assume(payload != null); var payloadJson = payload.SerializeToJson(); Contract.Assume(payloadJson != null); return payloadJson; }
private ClaimsIdentity ValidateJwtToken(JwtSecurityToken jwt, RelyingParty rp) { var handler = new JwtSecurityTokenHandler(); var validationParameters = new TokenValidationParameters() { //AudienceUriMode = AudienceUriMode.Never, SigningToken = new BinarySecretSecurityToken(rp.SymmetricSigningKey), ValidIssuer = ConfigurationRepository.Global.IssuerUri, AllowedAudience = jwt.Audience }; var principal = handler.ValidateToken(jwt, validationParameters); return principal.Identities.First(); }
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); }
public string GenerateJwtToken(string issuer, string audience, IEnumerable <Claim> claims, DateTime?notBefore, DateTime?expires) { string audienceSecreteKey = GlobalConstants.JwtTopSecrete512; string audienceSecreteBase64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(audienceSecreteKey)); byte[] audienceSecrete = Convert.FromBase64String(audienceSecreteBase64); SymmetricSecurityKey securityKey = new InMemorySymmetricSecurityKey(audienceSecrete); SigningCredentials signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature, SecurityAlgorithms.Sha256Digest); // HmacSha256: to be able to debug @jwt.io but you can go higher JwtPayload payload = new JwtPayload(issuer, audience, claims, notBefore, expires); System.IdentityModel.Tokens.JwtHeader header = new System.IdentityModel.Tokens.JwtHeader(signingCredentials); System.IdentityModel.Tokens.JwtSecurityToken securityToken = new System.IdentityModel.Tokens.JwtSecurityToken(header, payload); return(this.jwtSecurityTokenHandler.WriteToken(securityToken)); }
public async Task <IHttpActionResult> LogintUser([FromBody] User user) { UserApi api = new UserApi(); var userId = await api.Login(user); if (userId > 0) // user-defined function, checks against a database { System.IdentityModel.Tokens.JwtSecurityToken token = Microsoft.Azure.Mobile.Server.Login.AppServiceLoginHandler.CreateToken(new Claim[] { new Claim(JwtRegisteredClaimNames.Sub, userId.ToString()) }, "GfYVqdtZUJQfghRiaonAeRQRDjytRi47", Debugger.IsAttached ? "http://localhost/" : "https://greenhand.azurewebsites.net", Debugger.IsAttached ? "http://localhost/" : "https://greenhand.azurewebsites.net", TimeSpan.FromHours(6)); return(Ok(token.RawData)); } return(Unauthorized()); }
public void SetCurrentPrincipal(string encodedTokenString) { try { ClaimsIdentity ClaimsIdentityObject = new ClaimsIdentity(); JwtSecurityToken JwtSecurityTokenObject = new System.IdentityModel.Tokens.JwtSecurityToken(encodedTokenString); foreach (Claim ClaimObj in JwtSecurityTokenObject.Claims) { ClaimsIdentityObject.AddClaim(ClaimObj); } Thread.CurrentPrincipal = new ClaimsPrincipal(ClaimsIdentityObject); } catch (Exception ex) { throw ex; } }
public string Protect(AuthenticationTicket data) { if (data == null) { throw new ArgumentNullException("data"); } string audienceId = Utils.Configuration.TokenAudienceId; string symmetricKeyAsBase64 = Utils.Configuration.TokenAudienceSecret; var keyByteArray = TextEncodings.Base64Url.Decode(symmetricKeyAsBase64); var signingKey = new SigningCredentials(new InMemorySymmetricSecurityKey(keyByteArray), SignatureAlgorithm, DigestAlgorithm); var issued = data.Properties.IssuedUtc; var expires = data.Properties.ExpiresUtc; var token = new System.IdentityModel.Tokens.JwtSecurityToken(_issuer, audienceId, data.Identity.Claims, issued.Value.UtcDateTime, expires.Value.UtcDateTime, signingKey); var handler = new JwtSecurityTokenHandler(); var jwt = handler.WriteToken(token); return(jwt); }
public override void Run() { RunInSTAThread(() => { var webconfig = new OauthWebConfiguration { Authority = "https://login.microsoftonline.com", TenantId = "e07d220e-f4c2-441f-ad9a-9d6fa59b4e52", ClientSecret = "xuelnXKmXR8MjJ20CRie3oPvCxjFw83JRi4aRXzxvdE=", ClientId = "6b8eb9cf-3784-41e6-ac55-7b814dcf2c11", RedirectURI = "https://localhost:44300" }; // simulate the web server scenerio, user login and pass the code and id_token to server var simulaor = new OauthWebServerSimulator(webconfig); var response = simulaor.Login(); Console.WriteLine(response); var idToken = response.Value <string>("id_token"); // use id token to authenticate the user (skip the validation here) Tokens.JwtSecurityToken jwt = new Tokens.JwtSecurityToken(idToken); object uniquename; object oid; jwt.Payload.TryGetValue("unique_name", out uniquename); jwt.Payload.TryGetValue("oid", out oid); var signInUserId = uniquename as string; var userObjectId = oid as string; var code = response.Value <string>("code"); // use code to acquire the access token and cache in memory var resource = "https://graph.windows.net"; var discoveryServiceEndpointUri = "https://api.office.com/discovery/v1.0/me/"; var discoveryServiceResourceId = "https://api.office.com/discovery/"; AuthenticationContext authContext = new AuthenticationContext(webconfig.Authority, new InMemoryTokenCache(signInUserId)); ClientCredential credential = new ClientCredential(webconfig.ClientId, webconfig.ClientSecret); authContext.AcquireTokenByAuthorizationCode(code, new Uri(webconfig.RedirectURI), credential, resource); DiscoveryClient discoveryClient = new DiscoveryClient(new Uri(discoveryServiceEndpointUri), async() => { var authResult = await authContext.AcquireTokenSilentAsync(discoveryServiceResourceId, new ClientCredential(webconfig.ClientId, webconfig.ClientSecret), new UserIdentifier(userObjectId, UserIdentifierType.UniqueId)); return(authResult.AccessToken); }); var dcr = discoveryClient.DiscoverCapabilityAsync("Calendar").Result; }); }
public ActionResult Endpoint_SetSession() { //use this for implicit workflow logger.Debug("Post OIDC Endpoint_SetSession"); // set parameters string relayState = Request["relayState"]; if (string.IsNullOrEmpty(relayState) && Request.QueryString["RelayState"] != null) { relayState = Request.QueryString["RelayState"]; } else if (string.IsNullOrEmpty(relayState) && Request.QueryString["fromURI"] != null) { relayState = Request.QueryString["fromURI"]; } else if (string.IsNullOrEmpty(relayState) && TempData["relayState"] != null) { relayState = (string)TempData["relayState"]; } TempData["relayState"] = relayState; string myState = Request["state"]; string idToken = Request["id_token"]; string accessToken = Request["access_token"]; string tokenType = Request["token_type"]; string expires = Request["expires_in"]; string scope = Request["scope"]; string jsonPayload = null; string accessTokenStatus = null; string idTokenStatus = null; OidcIdToken oidcIdToken = new OidcIdToken(); if (idToken != null) { idTokenStatus = " ID Token Present"; TempData["idToken"] = idToken; string clientId = appSettings["oidc.spintnative.clientId"]; string issuer = appSettings["oidc.Issuer"]; string audience = appSettings["oidc.spintnative.clientId"]; jsonPayload = oktaOidcHelper.DecodeAndValidateIdToken(idToken, clientId, issuer, audience); if (jsonPayload.Contains("Failure")) { TempData["errMessage"] = "Invalid ID Token!"; } else { TempData["errMessage"] = "OIDC_Get Oauth Endpoint_Native SUCCESS idToken Valid "; oidcIdToken = Newtonsoft.Json.JsonConvert.DeserializeObject <OidcIdToken>(jsonPayload); System.IdentityModel.Tokens.JwtSecurityToken tokenReceived = new System.IdentityModel.Tokens.JwtSecurityToken(idToken); } } else { idTokenStatus = " ID Token Not Found"; } if (accessToken != null) { accessTokenStatus = "access_token Present"; TempData["accessToken"] = accessToken; string clientId = appSettings["oidc.spintnative.clientId"]; string issuer = appSettings["oidc.Issuer"]; //audience if different when custom Authorization Server string audience = null; if (appSettings["oidc.chooseAuthServer"] == "default") { audience = appSettings["oidc.Issuer"]; } else { audience = appSettings["oidc.customAuthServer.RedirectUri"]; } jsonPayload = oktaOidcHelper.DecodeAndValidateIdToken(accessToken, clientId, issuer, audience); System.IdentityModel.Tokens.JwtSecurityToken tokenReceived2 = new System.IdentityModel.Tokens.JwtSecurityToken(accessToken); } else { accessTokenStatus = "access_token NOT Found"; } if (accessToken != null || idToken != null) { TempData["errMessage"] = "OIDC_Get Oauth Endpoint_Native SUCCESS token_type = " + tokenType + " expires = " + expires + " scope = " + scope + " : " + idTokenStatus + " : " + accessTokenStatus + " oktaId = " + oidcIdToken.sub; TempData["oktaOrg"] = MvcApplication.apiUrl; //TempData["token"] = MvcApplication.apiToken; return(View("../AltLanding/ImplicitLanding", oidcIdToken)); } else { TempData["errMessage"] = "OIDC_Get Oauth Endpoint_Native Error token_type = " + tokenType + " expires = " + expires + " scope = " + scope + " : " + idTokenStatus + " : " + accessTokenStatus + " oktaId = " + oidcIdToken.sub; TempData["oktaOrg"] = MvcApplication.apiUrl; //TempData["token"] = MvcApplication.apiToken; return(View("../AltLanding/UnprotectedLanding")); } }
public ActionResult Endpoint_Web(string code, string state) { //use this for auth code workflow logger.Debug("Get OIDC Endpoint_Web"); // set parameters string relayState = Request["relayState"]; if (string.IsNullOrEmpty(relayState) && Request.QueryString["RelayState"] != null) { relayState = Request.QueryString["RelayState"]; } else if (string.IsNullOrEmpty(relayState) && Request.QueryString["fromURI"] != null) { relayState = Request.QueryString["fromURI"]; } else if (string.IsNullOrEmpty(relayState) && TempData["relayState"] != null) { relayState = (string)TempData["relayState"]; } TempData["relayState"] = relayState; logger.Debug(" code = " + code + " state " + state); string error = null; string error_description = null; string token_type = null; string scope = null; string id_token_status = null; string idToken = null; string access_token_status = null; string accessToken = null; string refresh_token_status = null; string refreshToken = null; string jsonPayload = null; IRestResponse <TokenRequestResponse> response = null; OidcIdToken oidcIdToken = new OidcIdToken(); OidcAccessToken oidcAccessToken = new OidcAccessToken(); string basicAuth = appSettings["oidc.spintweb.clientId"] + ":" + appSettings["oidc.spintweb.clientSecret"]; var bytesBasicAuth = System.Text.Encoding.UTF8.GetBytes(basicAuth); string encodedBasicAuth = System.Convert.ToBase64String(bytesBasicAuth); try { //var client = new RestClient(MvcApplication.apiUrl + "/oauth2/v1/token"); var client = new RestClient(appSettings["oidc.AuthServer"] + "/v1/token"); var request = new RestRequest(Method.POST); request.AddHeader("Accept", "application/json"); request.AddHeader("Content-Type", "application/x-www-form-urlencoded"); request.AddHeader("Authorization", " Basic " + encodedBasicAuth); request.AddQueryParameter("grant_type", "authorization_code"); request.AddQueryParameter("code", code); request.AddQueryParameter("redirect_uri", appSettings["oidc.spintweb.RedirectUri"]); response = client.Execute <TokenRequestResponse>(request); error = response.Data.error; error_description = response.Data.error_description; token_type = response.Data.token_type; scope = response.Data.scope; if (response.Data.id_token != null) { id_token_status = "id_token present"; idToken = response.Data.id_token; TempData["idToken"] = idToken; string clientId = appSettings["oidc.spintweb.clientId"]; string issuer = appSettings["oidc.Issuer"]; string audience = appSettings["oidc.spintweb.clientId"]; jsonPayload = oktaOidcHelper.DecodeAndValidateIdToken(idToken, clientId, issuer, audience); if (jsonPayload.Contains("Failure")) { TempData["errMessage"] = "Invalid ID Token!"; } else { // TempData["errMessage"] = jsonPayload; System.IdentityModel.Tokens.JwtSecurityToken tokenReceived = new System.IdentityModel.Tokens.JwtSecurityToken(idToken); oidcIdToken = Newtonsoft.Json.JsonConvert.DeserializeObject <OidcIdToken>(jsonPayload); } } else { id_token_status = "id_token NOT present"; } if (response.Data.access_token != null) { accessToken = response.Data.access_token; access_token_status = "access_token present"; TempData["accessToken"] = response.Data.access_token; string clientId = appSettings["oidc.spintweb.clientId"]; string issuer = appSettings["oidc.Issuer"]; //audience if different when custom Authorization Server string audience = null; if (appSettings["oidc.chooseAuthServer"] == "default") { audience = appSettings["oidc.Issuer"]; } else { audience = appSettings["oidc.customAuthServer.RedirectUri"]; } jsonPayload = oktaOidcHelper.DecodeAndValidateIdToken(accessToken, clientId, issuer, audience); System.IdentityModel.Tokens.JwtSecurityToken tokenReceived2 = new System.IdentityModel.Tokens.JwtSecurityToken(accessToken); } else { access_token_status = "access_token NOT present"; } if (response.Data.refresh_token != null) { refreshToken = response.Data.refresh_token; refresh_token_status = "refresh_token present"; TempData["refreshToken"] = response.Data.refresh_token; } else { refresh_token_status = "refresh_token NOT present"; } } catch (Exception ex) { logger.Error(ex.ToString()); } if (error != null) { TempData["errMessage"] = "OIDC_Get Oauth Endpoint_Web error " + error_description; TempData["oktaOrg"] = MvcApplication.apiUrl; //TempData["token"] = MvcApplication.apiToken; return(RedirectToAction("UnprotectedLanding", "AltLanding")); } else { TempData["errMessage"] = "OIDC_Get Oauth Endpoint_Web SUCCESS token_type = " + token_type + " scope = " + scope + " : " + id_token_status + " : " + access_token_status + " oktaId = " + oidcIdToken.sub; TempData["oktaOrg"] = MvcApplication.apiUrl; //TempData["token"] = MvcApplication.apiToken; return(RedirectToAction("AuthCodeLanding", "AltLanding")); } }