public async Task<string> GenerateAccessToken(SecurityTokenDescriptor tokenDescriptor, TokenValidationParameters validationParameters) { if (tokenCache.ContainsKey(tokenDescriptor) && tokenDescriptor.Lifetime.Expires > DateTime.UtcNow.AddMinutes(-1)) { return tokenCache[tokenDescriptor]; } tokenDescriptor.Lifetime = new Lifetime(DateTime.UtcNow, DateTime.UtcNow.AddMinutes(10)); var accessToken = await this.innerTokenProvider.GenerateAccessToken(tokenDescriptor, validationParameters); return tokenCache.AddOrUpdate(tokenDescriptor, accessToken, (d, t) => accessToken); }
static string CreateTokenWithInMemorySymmetricSecurityKey() { var now = DateTime.UtcNow; var tokenHandler = new JwtSecurityTokenHandler(); var symmetricKey = new RandomBufferGenerator(256 / 8).GenerateBufferFromSeed(256 / 8); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, "Tugberk"), new Claim(ClaimTypes.Role, "Sales"), }), 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") }; SecurityToken token = tokenHandler.CreateToken(tokenDescriptor); string tokenString = tokenHandler.WriteToken(token); return tokenString; }
// The Method is used to generate token for user public string GenerateTokenForUser(string userName, string userId) { var now = DateTime.UtcNow; var signingCredentials = new System.IdentityModel.Tokens.SigningCredentials(signingKey, System.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256Signature, System.IdentityModel.Tokens.SecurityAlgorithms.Sha256Digest); var claimsIdentity = new ClaimsIdentity(new List <Claim>() { new Claim(ClaimTypes.Name, userName), new Claim(ClaimTypes.NameIdentifier, userId.ToString()), }, "Custom"); var securityTokenDescriptor = new System.IdentityModel.Tokens.SecurityTokenDescriptor() { AppliesToAddress = "http://www.example.com", TokenIssuerName = "self", Subject = claimsIdentity, SigningCredentials = signingCredentials, Lifetime = new Lifetime(now, now.AddYears(1)), }; var tokenHandler = new JwtSecurityTokenHandler(); var plainToken = tokenHandler.CreateToken(securityTokenDescriptor); var signedAndEncodedToken = tokenHandler.WriteToken(plainToken); return(signedAndEncodedToken); }
//http://blog.asteropesystems.com/securing-web-api-requests-with-json-web-tokens/ public string GetToken(string username, List<ActivityClaim> activityClaims) { var tokenHandler = new JwtSecurityTokenHandler(); var now = DateTime.UtcNow; var claims = new ClaimsIdentity(new[] { new Claim( ClaimTypes.UserData, "IsValid", ClaimValueTypes.String ), new Claim( ClaimTypes.Name, username, ClaimValueTypes.String ) }); claims.AddClaims(activityClaims.Select(c => new Claim(ClaimTypes.UserData, c.ToString(), ClaimValueTypes.String))); var tokenDescriptor = new SecurityTokenDescriptor { Subject = claims, TokenIssuerName = "self", AppliesToAddress = "https://api.knowthyshelf.com", Lifetime = new Lifetime(now, now.AddYears(10)), SigningCredentials = new SigningCredentials(new InMemorySymmetricSecurityKey(TOKEN_SECURITY_KEY), "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); return tokenString; }
public ActionResult MyToken() { var config = ConfigurationRepository.Configuration; var samlHandler = SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection()[config.DefaultTokenType]; var descriptor = new SecurityTokenDescriptor { AppliesToAddress = "http://self", Lifetime = new Lifetime(DateTime.UtcNow, DateTime.UtcNow.AddHours(config.DefaultTokenLifetime)), SigningCredentials = new X509SigningCredentials(ConfigurationRepository.SigningCertificate.Certificate), TokenIssuerName = config.IssuerUri, Subject = new ClaimsIdentity(GetClaims()) }; var token = samlHandler.CreateToken(descriptor); var sb = new StringBuilder(1024); samlHandler.WriteToken(XmlWriter.Create(new StringWriter(sb)), token); return new ContentResult { ContentType = "text/xml", Content = sb.ToString() }; }
/// <summary> /// Sets a JWT authorization header on the default request headers of an <see cref="HttpClient"/>. /// </summary> /// <param name="client">The client for which to set the authorization header.</param> /// <param name="signingCertificate">The signing certificate to sign the token.</param> /// <param name="appliesToAddress">The address for which the token is considered valid.</param> /// <param name="claims">The claims that define the user. Leave null for an anonymous user.</param> /// <param name="tokenIssuerName">Name of the token issuer. Defaults to "self".</param> /// <param name="tokenDuration"> /// The token duration for which it's considered valid. Defaults to 2 hours. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="signingCertificate"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="appliesToAddress"/> is <see langword="null"/> or empty. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="tokenIssuerName"/> is <see langword="null"/> or empty. /// </exception> public static void SetJwtAuthorizationHeader( this HttpClient client, X509Certificate2 signingCertificate, string appliesToAddress, IEnumerable<Claim> claims = null, string tokenIssuerName = "self", TimeSpan? tokenDuration = null) { signingCertificate.AssertNotNull("signingCertificate"); appliesToAddress.AssertNotNullOrWhitespace("appliesToAddress"); tokenIssuerName.AssertNotNullOrWhitespace("tokenIssuerName"); var now = DateTime.UtcNow; var tokenHandler = new JwtSecurityTokenHandler(); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(claims), TokenIssuerName = tokenIssuerName, AppliesToAddress = appliesToAddress, Lifetime = new Lifetime(now, now.Add(tokenDuration ?? TimeSpan.FromHours(2))), SigningCredentials = new X509SigningCredentials(signingCertificate) }; SecurityToken token = tokenHandler.CreateToken(tokenDescriptor); string tokenString = tokenHandler.WriteToken(token); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenString); }
private static void Main(string[] args) { var key = Convert.FromBase64String(SymmetricKey); var credentials = new SigningCredentials( new InMemorySymmetricSecurityKey(key), "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256", "http://www.w3.org/2001/04/xmlenc#sha256"); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, "bhogg"), new Claim(ClaimTypes.GivenName, "Boss"), new Claim(ClaimTypes.Surname, "Hogg"), new Claim(ClaimTypes.Role, "Manager"), new Claim(ClaimTypes.Role, "SeniorWorker"), }), TokenIssuerName = "corp", AppliesToAddress = "http://www.example.com", SigningCredentials = credentials, Lifetime = new Lifetime(DateTime.UtcNow, DateTime.UtcNow.AddYears(10)) }; var tokenHandler = new JwtSecurityTokenHandler(); var token = tokenHandler.CreateToken(tokenDescriptor); var tokenString = tokenHandler.WriteToken(token); Console.WriteLine(tokenString); Debug.WriteLine(tokenString); Console.ReadLine(); }
public LoginResult PostSignIn([FromBody] LoginCredential credentials) { var auth = new LoginResult() { Authenticated = false }; var userRoles = QueryableDependencies.GetLoginUserRoles(credentials.UserName, credentials.Password); if (userRoles.Count > 0) //if (userRoles.Where(r => r == "CredentialSystem").Any()) { auth.Authenticated = true; var allClaims = userRoles.Select(r => new Claim(ClaimTypes.Role, r.ToString())).ToList(); allClaims.Add(new Claim(ClaimTypes.Name, credentials.UserName)); allClaims.Add(new Claim(ClaimTypes.Role, userRoles[0].ToString())); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(allClaims), AppliesToAddress = ConfigurationManager.AppSettings["JwtAllowedAudience"], TokenIssuerName = ConfigurationManager.AppSettings["JwtValidIssuer"], SigningCredentials = new SigningCredentials(new InMemorySymmetricSecurityKey(JwtTokenValidationHandler.SymmetricKey), "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256", "http://www.w3.org/2001/04/xmlenc#sha256") }; var tokenHandler = new JwtSecurityTokenHandler(); var token = tokenHandler.CreateToken(tokenDescriptor); var tokenString = tokenHandler.WriteToken(token); auth.Token = tokenString; } return auth; }
public string Post(Credential credential) { if (credential.username == "admin" && credential.password == "123") { var tokenHandler = new JwtSecurityTokenHandler(); var securityKey = Authorization.GetBytes("anyoldrandomtext"); var now = DateTime.UtcNow; var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new[] { new Claim( ClaimTypes.UserData,"IsValid", ClaimValueTypes.String, "(local)" ) }), TokenIssuerName = "self", AppliesToAddress = "https://www.mywebsite.com", Lifetime = new Lifetime(now, now.AddMinutes(60)), 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); var tokenString = tokenHandler.WriteToken(token); return tokenString; } else { return string.Empty; } }
/// <summary> /// Creates the token response and invokes the logging callbacks. /// </summary> /// <param name="request">The request.</param> /// <param name="tokenDescriptor">The token descriptor.</param> /// <returns>A RequestSecurityTokenResponse</returns> protected override RequestSecurityTokenResponse GetResponse(RequestSecurityToken request, SecurityTokenDescriptor tokenDescriptor) { var response = base.GetResponse(request, tokenDescriptor); // see if token is encrypted EncryptedSecurityToken encryptedToken = tokenDescriptor.Token as EncryptedSecurityToken; SecurityToken token; if (encryptedToken != null) { // if so, use inner token token = encryptedToken.Token; } else { // if not, use the token directly token = tokenDescriptor.Token; } var sb = new StringBuilder(128); FederatedAuthentication.ServiceConfiguration.SecurityTokenHandlers.WriteToken(XmlWriter.Create(new StringWriter(sb)), token); try { // do logging callback OnTrace( XElement.Parse(SerializeRequest(request)), XElement.Parse(SerializeResponse(response)), XElement.Parse(sb.ToString())); } catch { } return response; }
static GenericXmlSecurityToken WrapJwt(string jwt) { var subject = new ClaimsIdentity("saml"); subject.AddClaim(new Claim("jwt", jwt)); var descriptor = new SecurityTokenDescriptor { TokenType = TokenTypes.Saml2TokenProfile11, TokenIssuerName = "urn:wrappedjwt", Subject = subject }; var handler = new Saml2SecurityTokenHandler(); var token = handler.CreateToken(descriptor); var xmlToken = new GenericXmlSecurityToken( XElement.Parse(token.ToTokenXmlString()).ToXmlElement(), null, DateTime.Now, DateTime.Now.AddHours(1), null, null, null); return xmlToken; }
public JwtAuthenticationOwinMiddlewareTests() { var signingCredentials = new SigningCredentials( new InMemorySymmetricSecurityKey(Convert.FromBase64String(Key)), "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256", "http://www.w3.org/2001/04/xmlenc#sha256"); var now = DateTime.UtcNow; var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new [] { new Claim("sub", "Alice"), new Claim("email", "*****@*****.**"), }), TokenIssuerName = Issuer, AppliesToAddress = Audience, Lifetime = new Lifetime(now, now.AddMinutes(LifetimeInMinutes)), SigningCredentials = signingCredentials, }; var tokenHandler = new JwtSecurityTokenHandler(); var token = tokenHandler.CreateToken(tokenDescriptor); _tokenString = tokenHandler.WriteToken(token); }
public override SecurityToken CreateToken(SecurityTokenDescriptor tokenDescriptor) { var sb = new StringBuilder(); CreateClaims(tokenDescriptor, sb); sb.AppendFormat("Issuer={0}&", HttpUtility.UrlEncode(tokenDescriptor.TokenIssuerName)); sb.AppendFormat("Audience={0}&", HttpUtility.UrlEncode(tokenDescriptor.AppliesToAddress)); var seconds = (tokenDescriptor.Lifetime.Expires - tokenDescriptor.Lifetime.Created); double lifeTimeInSeconds = 3600; if (seconds.HasValue) lifeTimeInSeconds = seconds.Value.TotalSeconds; sb.AppendFormat("ExpiresOn={0:0}", DateTime.UtcNow.ToEpochTime() + lifeTimeInSeconds); var unsignedToken = sb.ToString(); var key = (InMemorySymmetricSecurityKey)tokenDescriptor.SigningCredentials.SigningKey; var hmac = new HMACSHA256(key.GetSymmetricKey()); var sig = hmac.ComputeHash(Encoding.ASCII.GetBytes(unsignedToken)); var signedToken = String.Format("{0}&HMACSHA256={1}", unsignedToken, HttpUtility.UrlEncode(Convert.ToBase64String(sig))); return new SimpleWebToken(signedToken); }
public void HandlerCreateRoundtripSingleClaimTypes() { var signinKey = SymmetricKeyGenerator.Create(32); var identity = new ClaimsIdentity(new List<Claim> { new Claim(ClaimTypes.Name, "dominick"), new Claim(ClaimTypes.Email, "*****@*****.**"), }, "Custom"); var descriptor = new SecurityTokenDescriptor { Subject = identity, SigningCredentials = new HmacSigningCredentials(signinKey), TokenIssuerName = "dominick", Lifetime = new Lifetime(DateTime.UtcNow, DateTime.UtcNow.AddHours(8)), AppliesToAddress = "http://foo.com" }; var handler = new JsonWebTokenHandler(); var token = handler.CreateToken(descriptor); var tokenString = handler.WriteToken(token); Trace.WriteLine(tokenString); // token should not be empty Assert.IsTrue(!string.IsNullOrWhiteSpace(tokenString)); // token with signature needs to be 3 parts var parts = tokenString.Split('.'); Assert.IsTrue(parts.Length == 3, "JWT should have excactly 3 parts"); // signature must be 256 bits var sig = Base64Url.Decode(parts[2]); Assert.IsTrue(sig.Length == 32, "Signature is not 32 bits"); var jwtToken = handler.ReadToken(tokenString); var config = new SecurityTokenHandlerConfiguration(); var registry = new WebTokenIssuerNameRegistry(); registry.AddTrustedIssuer("dominick", "dominick"); config.IssuerNameRegistry = registry; var issuerResolver = new WebTokenIssuerTokenResolver(); issuerResolver.AddSigningKey("dominick", Convert.ToBase64String(signinKey)); config.IssuerTokenResolver = issuerResolver; config.AudienceRestriction.AllowedAudienceUris.Add(new Uri("http://foo.com")); handler.Configuration = config; var identity2 = handler.ValidateToken(jwtToken).First(); Assert.IsTrue(identity.Claims.Count() == 2); //Assert.IsTrue(identity.Claims.First().Issuer == "dominick"); }
public static string GetJwtToken(this ClaimsIdentity identity, SecurityTokenDescriptor tokenDescriptor) { if (identity == null || tokenDescriptor == null) return null; tokenDescriptor.Subject = identity; var tokenHandler = new JwtSecurityTokenHandler(); var token = tokenHandler.CreateToken(tokenDescriptor); var tokenString = tokenHandler.WriteToken(token); return tokenString; }
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; }
#pragma warning disable 1998 public override async Task<Result> Execute() { Result result = new Result(); try { Console.Out.WriteLine("Generating access token..."); // encryption key string key_s = ConfigurationManager.ConnectionStrings["JWTKey"].ConnectionString; byte[] key_b = new byte[key_s.Length * sizeof(char)]; System.Buffer.BlockCopy(key_s.ToCharArray(), 0, key_b, 0, key_b.Length); // create the token JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler(); ClaimsIdentity subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Uri, SiteUrl, ClaimValueTypes.String) }); SecurityTokenDescriptor tokenDescriptor = new SecurityTokenDescriptor { Subject = subject, TokenIssuerName = "SpSat", Lifetime = new Lifetime(DateTime.UtcNow, DateTime.UtcNow.AddHours(4)), SigningCredentials = new SigningCredentials(new InMemorySymmetricSecurityKey(key_b), "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256", "http://www.w3.org/2001/04/xmlenc#sha256") }; SecurityToken token = tokenHandler.CreateToken(tokenDescriptor); using (ClientContext context = new ClientContext(SiteUrl)) { // authenticate string usernamePassword = ConfigurationManager.ConnectionStrings["SharePoint"].ConnectionString; dynamic usernamePassword_j = Newtonsoft.Json.JsonConvert.DeserializeObject(usernamePassword); string username = usernamePassword_j.username; string password = usernamePassword_j.password; SecureString password_s = new SecureString(); Array.ForEach(password.ToCharArray(), password_s.AppendChar); context.Credentials = new SharePointOnlineCredentials(username, password_s); // write the token to the property bag PropertyValues webProperties = context.Web.AllProperties; webProperties["accessToken"] = tokenHandler.WriteToken(token); context.Web.Update(); context.ExecuteQuery(); } Console.Out.WriteLine("Completed generating access token."); result.Status = Status.Success; } catch (Exception ex) { result.Status = Status.Failure; result.Log.Add(ex.Message); } return result; }
public SamlSecurityToken CreateToken(IClaimsIdentity identity) { var description = new SecurityTokenDescriptor { Subject = identity, TokenIssuerName = _issuer }; //var handler = new Saml2SecurityTokenHandler(); //return (SamlSecurityToken)handler.CreateToken(description); return (SamlSecurityToken)CreateToken(description); }
SecurityTokenDescriptor getTokenDescriptor() { var now = DateTime.UtcNow; var tokenDescriptor = new SecurityTokenDescriptor { TokenIssuerName = "self", AppliesToAddress = "https://localhost", Lifetime = new Lifetime(now, now.AddMinutes(10)), SigningCredentials = new X509SigningCredentials(getCertificate()) }; return tokenDescriptor; }
private string CreateToken(ClaimsIdentity identity, SigningCredentials signingCredentials) { var tokenDescriptor = new SecurityTokenDescriptor { AppliesToAddress = Audience, Subject = identity, TokenIssuerName = TokenIssuerName, SigningCredentials = signingCredentials, }; var handler = new JwtSecurityTokenHandler(); var token = handler.CreateToken(tokenDescriptor); return handler.WriteToken(token); }
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 SimpleWebToken GetToken(out string keyValue) { var key = Guid.NewGuid().ToByteArray().ToList(); key.AddRange(Guid.NewGuid().ToByteArray()); keyValue = Convert.ToBase64String(key.ToArray()); var descripter = new SecurityTokenDescriptor(); descripter.Lifetime = new Lifetime(DateTime.Now, DateTime.Now.AddMinutes(5)); descripter.TokenIssuerName = "http://www.thinktecture.com"; descripter.SigningCredentials = new HmacSigningCredentials(key.ToArray()); descripter.Subject = new ClaimsIdentity(this.Claims()); descripter.AppliesToAddress = "https://www.thinktecture.com/"; var output = new SimpleWebTokenHandler().CreateToken(descripter) as SimpleWebToken; return output; }
private static SecurityToken CreateToken(AccessSecurityTokenHandler handler) { var descriptor = new SecurityTokenDescriptor { AppliesToAddress = "http://tecteacher.thinktecture.com/videos/1", Lifetime = new Lifetime(DateTime.Now, DateTime.Now.AddMinutes(60)), SigningCredentials = GetSigningCredential(), TokenType = AccessSecurityToken.TokenTypeIdentifier, Subject = new ClaimsIdentity(new List<Claim> { new Claim(WSIdentityConstants.ClaimTypes.Name, "bob") }) }; var token = handler.CreateToken(descriptor); return token; }
/// <summary> /// Generate an token. /// </summary> /// <param name="username">The username.</param> /// <returns></returns> public string Generate(string username) { var tokenHandler = new JwtSecurityTokenHandler(); var now = DateTime.UtcNow; //The contents of the JWT token var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, username) }), TokenIssuerName = JwtTokenGenerator.TokenIssuer, Lifetime = new Lifetime(now, now.AddHours(JwtTokenGenerator.LifetimeInHours)), SigningCredentials = this.credentials }; var token = tokenHandler.CreateToken(tokenDescriptor); return tokenHandler.WriteToken(token); }
private static SecurityToken GenerateHardcodedToken() { var securityTokenDescriptor = new SecurityTokenDescriptor(); securityTokenDescriptor.Subject = ClaimsPrincipal.Current.Identity as ClaimsIdentity; securityTokenDescriptor.Lifetime = new Lifetime(DateTime.Now, DateTime.Now.AddDays(2)); securityTokenDescriptor.TokenIssuerName = "http://identityserver.v2.thinktecture.com/trust/changethis"; securityTokenDescriptor.AppliesToAddress = "https://windows7:444/identity/wstrust/bearer"; securityTokenDescriptor.SigningCredentials = GenerateSigningCredentials(); Saml2SecurityTokenHandler saml2SecurityTokenHandler = new Saml2SecurityTokenHandler(); var saml2SecurityToken = saml2SecurityTokenHandler.CreateToken(securityTokenDescriptor) as Saml2SecurityToken; var authenticationMethod = "urn:oasis:names:tc:SAML:2.0:ac:classes:Password"; var authenticationContext = new Saml2AuthenticationContext(new Uri(authenticationMethod)); saml2SecurityToken.Assertion.Statements.Add(new Saml2AuthenticationStatement(authenticationContext)); return saml2SecurityToken; }
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 string CreateSaml2Token(string name) { var id = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, name) }, "SAML"); var descriptor = new SecurityTokenDescriptor { Subject = id, AppliesToAddress = "https://test", TokenIssuerName = "http://issuer", SigningCredentials = GetSamlSigningCredential(), }; var handler = new Saml2SecurityTokenHandler(); handler.Configuration = new SecurityTokenHandlerConfiguration(); var token = handler.CreateToken(descriptor); return token.ToTokenXmlString(); }
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(); }
internal static JwtSecurityToken CreateTokenFromClaims(IEnumerable<Claim> claims, string secretKey, string audience, string issuer, TimeSpan? lifetime) { DateTime created = DateTime.UtcNow; // we allow for no expiry (if lifetime is null) DateTime? expiry = (lifetime != null) ? created + lifetime : null; var tokenDescriptor = new SecurityTokenDescriptor { AppliesToAddress = audience, TokenIssuerName = issuer, SigningCredentials = new HmacSigningCredentials(secretKey), Lifetime = new Lifetime(created, expiry), Subject = new ClaimsIdentity(claims), }; var securityTokenHandler = new JwtSecurityTokenHandler() { SetDefaultTimesOnTokenCreation = false }; return securityTokenHandler.CreateToken(tokenDescriptor) as JwtSecurityToken; }
protected virtual JwtSecurityToken CreateTokenFromClaims(IEnumerable<Claim> claims, string secretKey, string audience, string issuer) { var signingKey = this.GetSigningKey(secretKey); var signingToken = new BinarySecretSecurityToken(signingKey); var signingCredentials = new SigningCredentials(new InMemorySymmetricSecurityKey(signingToken.GetKeyBytes()), "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256", "http://www.w3.org/2001/04/xmlenc#sha256"); var tokenDescriptor = new SecurityTokenDescriptor { AppliesToAddress = audience, TokenIssuerName = issuer, SigningCredentials = signingCredentials, Lifetime = new Lifetime(DateTime.UtcNow, DateTime.UtcNow + TimeSpan.FromDays(1)), Subject = new ClaimsIdentity(claims), }; var tokenHandler = new JwtSecurityTokenHandler(); var token = tokenHandler.CreateToken(tokenDescriptor) as JwtSecurityToken; return token; }
private const int LifeTimeInSeconds = 5 * 60;//5 minutes public static string CreateToken(this ClaimsIdentity identity, X509Certificate2 signingCertificate = null) { if (identity == null) { throw new ArgumentNullException("identity"); } var tokenHandler = new JwtSecurityTokenHandler(); var now = DateTime.UtcNow; var tokenDescriptor = new System.IdentityModel.Tokens.SecurityTokenDescriptor { Subject = identity, TokenIssuerName = Issuer, AppliesToAddress = Audience, Lifetime = new Lifetime(now, now.AddMinutes(LifeTimeInSeconds)), SigningCredentials = signingCertificate == null ? null : new System.IdentityModel.Tokens.X509SigningCredentials(signingCertificate) }; var token = tokenHandler.CreateToken(tokenDescriptor); var tokenString = tokenHandler.WriteToken(token); return(tokenString); }
public virtual SecurityToken CreateToken(SecurityTokenDescriptor tokenDescriptor) { throw new NotImplementedException(); }
/// <summary> /// Called by the STS to create a token given a token descriptor. /// </summary> /// <param name="tokenDescriptor">Describes the token; properties such /// as ValidFrom, AppliesTo, EncryptingCredentials, Claims, etc., are filled in /// before the call to create token. </param> /// <returns>A SecurityToken that matches the properties of the token descriptor.</returns> public virtual SecurityToken CreateToken(SecurityTokenDescriptor tokenDescriptor) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotImplementedException(SR.GetString(SR.ID4008, "SecurityTokenHandler", "CreateToken"))); }
private string CreateJwt(string userId, string role) { var key = Convert.FromBase64String(SymmetricKey); var credentials = new SigningCredentials( new InMemorySymmetricSecurityKey(key), "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256", "http://www.w3.org/2001/04/xmlenc#sha256"); var expiration = DateTime.UtcNow.AddMinutes(20).ToLongTimeString(); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, userId), new Claim(ClaimTypes.Role, role), new Claim("exp", expiration) }), TokenIssuerName = Issuer, AppliesToAddress = Audience, SigningCredentials = credentials }; var tokenHandler = new JwtSecurityTokenHandler(); var token = tokenHandler.CreateToken(tokenDescriptor); var tokenString = tokenHandler.WriteToken(token); return tokenString; }