public static TokenResponse GenerateToken(string username) { //Set issued at date DateTime issuedAt = DateTime.UtcNow; //set the time when it expires DateTime expires = DateTime.UtcNow.AddDays(7); var tokenHandler = new JwtSecurityTokenHandler(); //create a identity and add claims to the user which we want to log in ClaimsIdentity claimsIdentity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, username) }); string sec = ConfigurationManager.AppSettings["secret"].ToString(); var now = DateTime.UtcNow; var securityKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(System.Text.Encoding.Default.GetBytes(sec)); var signingCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(securityKey, Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256Signature); //create the jwt var token = (JwtSecurityToken) tokenHandler.CreateJwtSecurityToken(issuer: "http://localhost:54122", audience: "http://localhost:54122", subject: claimsIdentity, notBefore: issuedAt, expires: expires, signingCredentials: signingCredentials); var tokenString = tokenHandler.WriteToken(token); return(new TokenResponse { ExpiresAt = expires, Token = tokenString }); }
//토큰 생성하기 private string createToken(string username, string userrole) { var claims = new List <Claim> { new Claim(ClaimTypes.NameIdentifier, username), new Claim(ClaimTypes.Role, userrole) }; const string sec = "401b09eab3c013d4ca54922bb802bec8fd5318192b0a75f201d8b3727429090fb337591abd3e44453b954555b7a0812e1081c39b740293f765eae731f5a65ed1"; var securityKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(System.Text.Encoding.Default.GetBytes(sec)); var signingCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(securityKey, Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256Signature); var securityTokenDescriptor = new SecurityTokenDescriptor() { Audience = "https://localhost:44310", Issuer = "https://localhost:44310", IssuedAt = DateTime.UtcNow, Subject = new ClaimsIdentity(claims, "Bearer"), SigningCredentials = signingCredentials, NotBefore = DateTime.UtcNow.AddMinutes(-1), Expires = DateTime.UtcNow.AddHours(12) }; var tokenHandler = new JwtSecurityTokenHandler(); var token = tokenHandler.CreateJwtSecurityToken(securityTokenDescriptor); var tokenString = tokenHandler.WriteToken(token); return(tokenString); }
public JsonWebToken(Uri audience, string securityKey, string issuer, IEnumerable <Claim> claims, double lifetimeMinutes) { Issuer = issuer; Id = Guid.NewGuid().ToString(); created = DateTime.UtcNow; expires = created.AddMinutes(lifetimeMinutes); SigningKey = new SymmetricSecurityKey(Convert.FromBase64String(securityKey)); JwtSecurityTokenHandler jwt = new JwtSecurityTokenHandler(); SecurityTokenDescriptor msstd = new SecurityTokenDescriptor { Issuer = issuer, Subject = new ClaimsIdentity(claims), Expires = expires, IssuedAt = created, NotBefore = created, Audience = audience.ToString(), SigningCredentials = new SigningCredentials(SigningKey, SecurityAlgorithms.HmacSha256Signature) }; JwtSecurityToken jwtToken = jwt.CreateJwtSecurityToken(msstd); tokenString = jwt.WriteToken(jwtToken); }
public static string GenerateToken(AccountViewModel account, string role) { var identity = new ClaimsIdentity(new[] { new Claim(Claims.AccountId, account.Id.ToString()), new Claim(Claims.FirstName, account.FirstName), new Claim(Claims.LastName, account.LastName), new Claim(Claims.Email, account.Email), new Claim(Claims.IsAdmin, (account.Role == Roles.Admin).ToString()), new Claim(ClaimTypes.Role, Roles.WindowsService == role ? role : account.Role) }); var securityKey = new SymmetricSecurityKey(Convert.FromBase64String(Secret)); var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature); DateTime expiresDate = (account.Role == Roles.Admin) ? DateTime.UtcNow.AddDays(7) : (role == Roles.WindowsService) ? DateTime.UtcNow.AddDays(2) : DateTime.UtcNow.AddDays(1); var descriptor = new SecurityTokenDescriptor { Issuer = "ScraperLinkedInServer", Audience = "ScraperLinkedInServer", Subject = identity, IssuedAt = DateTime.UtcNow, Expires = expiresDate, SigningCredentials = signingCredentials }; var handler = new JwtSecurityTokenHandler(); var token = handler.CreateJwtSecurityToken(descriptor); return(handler.WriteToken(token)); }
/// <summary> /// Metodo que genera un jwt para su respectiva sesion. /// </summary> /// <returns></returns> public static string CreateToken(IConfiguration _configuration, string pUsername) { //get the configuration appseting.json var key = _configuration["Jwt:Key"]; var audienceToken = _configuration["Jwt:AudienceToken"]; var issuerToken = _configuration["Jwt:IssuerToken"]; var expireToken = _configuration["Jwt:Expire"]; var securityKey = new SymmetricSecurityKey(Encoding.Default.GetBytes(key)); var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256); // create a claimsIdentity var claimsIdentity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, pUsername) }); // create token to the user var tokenHandler = new JwtSecurityTokenHandler(); var jwtSecurityToken = tokenHandler.CreateJwtSecurityToken( audience: audienceToken, issuer: issuerToken, subject: claimsIdentity, notBefore: DateTime.UtcNow, expires: DateTime.UtcNow.AddMinutes(Convert.ToInt32(expireToken)), signingCredentials: signingCredentials); var jwtTokenString = tokenHandler.WriteToken(jwtSecurityToken); return(jwtTokenString); }
private string createToken(string username) { var minutes = Convert.ToInt32(ConfigurationManager.AppSettings["LifeTimeTokenMinutes"].ToString()); DateTime issueAt = DateTime.UtcNow; DateTime expires = DateTime.UtcNow.AddMinutes(minutes); var tokenHandler = new JwtSecurityTokenHandler(); ClaimsIdentity claimsIdentity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, username) }); const string Base64SecrectKey = "siO2ttKA2ONRF0LUHYFlG9OdTy1mYGwE0MBmBZE9EoOEAnE7rthdzeZRklpid+WKr5bgx6t3GLXURXu3JrIaYg=="; var now = DateTime.UtcNow; var securityKey = new SymmetricSecurityKey(Encoding.Default.GetBytes(Base64SecrectKey)); var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature); var token = (JwtSecurityToken)tokenHandler.CreateJwtSecurityToken ( issuer: "https://localhost:44382", audience: "https://localhost:44382", subject: claimsIdentity, notBefore: issueAt, expires: expires, signingCredentials: signingCredentials ); var tokenString = tokenHandler.WriteToken(token); return(tokenString); }
public async Task <IdentityResponseModel> Handle(CreateJwtTokenCommand request, CancellationToken cancellationToken) { if (string.IsNullOrEmpty(request.UserName) && string.IsNullOrEmpty(request.Password)) { throw new UnprocessableException("Username and password cannot be empty"); } var tokenHandler = new JwtSecurityTokenHandler(); var signingKey = new SymmetricSecurityKey( Encoding.ASCII.GetBytes(_settings.Value.SecretKey) ); var jwt = tokenHandler.CreateJwtSecurityToken ( issuer: _settings.Value.Iss, audience: _settings.Value.Aud, expires: DateTime.UtcNow.AddDays(1), signingCredentials: new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256) ); var encodedJwt = new JwtSecurityTokenHandler() .WriteToken(jwt); return(new IdentityResponseModel(encodedJwt)); }
public void OpenIdConnect() { SigningCredentials rsaSigningCredentials = new SigningCredentials( KeyingMaterial.RsaSecurityKey_2048, SecurityAlgorithms.RsaSha256Signature ); //"<RSAKeyValue><Modulus>rCz8Sn3GGXmikH2MdTeGY1D711EORX/lVXpr+ecGgqfUWF8MPB07XkYuJ54DAuYT318+2XrzMjOtqkT94VkXmxv6dFGhG8YZ8vNMPd4tdj9c0lpvWQdqXtL1TlFRpD/P6UMEigfN0c9oWDg9U7Ilymgei0UXtf1gtcQbc5sSQU0S4vr9YJp2gLFIGK11Iqg4XSGdcI0QWLLkkC6cBukhVnd6BCYbLjTYy3fNs4DzNdemJlxGl8sLexFytBF6YApvSdus3nFXaMCtBGx16HzkK9ne3lobAwL2o79bP4imEGqg+ibvyNmbrwFGnQrBc1jTF9LyQX9q+louxVfHs6ZiVw==</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>" OpenIdConnectConfiguration configuration = OpenIdConnectConfigurationRetriever.GetAsync(OpenIdConfigData.OpenIdConnectMetadataFileEnd2End, new FileDocumentRetriever(), CancellationToken.None).Result; JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler(); JwtSecurityToken jwtToken = tokenHandler.CreateJwtSecurityToken( configuration.Issuer, IdentityUtilities.DefaultAudience, ClaimSets.DefaultClaimsIdentity, DateTime.UtcNow, DateTime.UtcNow + TimeSpan.FromHours(1), DateTime.UtcNow + TimeSpan.FromHours(1), rsaSigningCredentials); tokenHandler.WriteToken(jwtToken); TokenValidationParameters validationParameters = new TokenValidationParameters { IssuerSigningKeys = configuration.SigningKeys, ValidAudience = IdentityUtilities.DefaultAudience, ValidIssuer = configuration.Issuer, }; SecurityToken securityToken = null; tokenHandler.ValidateToken(jwtToken.RawData, validationParameters, out securityToken); }
public IActionResult Login( [Required][FromBody] LoginParam loginParam ) { var handler = new JwtSecurityTokenHandler(); var claims = new[] { new Claim(ClaimTypes.Name, loginParam.Username) }; var subject = new ClaimsIdentity(claims); var credentials = new SigningCredentials( JwtSecurityConfiguration.SecurityKey, SecurityAlgorithms.HmacSha256); var token = handler.CreateJwtSecurityToken( audience: loginParam.Username, issuer: JwtSecurityConfiguration.Issuer, subject: subject, signingCredentials: credentials); var tokenText = handler.WriteToken(token); var result = new { token = tokenText }; return(Ok(result)); }
public JwtSecurityToken AuthenticateUser(string name, string password) { var user = _context.Users.Where(a => a.UserName == name && a.Password == password).FirstOrDefault(); if (user == null) { return(null); } var tokenHandler = new JwtSecurityTokenHandler(); var tokenKey = Encoding.ASCII.GetBytes(Configuration["JWT:Secret"]); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, name) }), Expires = DateTime.Now.AddDays(1), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(tokenKey), SecurityAlgorithms.HmacSha256Signature) }; //var token = tokenHandler.CreateToken(tokenDescriptor); var token = tokenHandler.CreateJwtSecurityToken(tokenDescriptor); return(token); /*tokenHandler.WriteToken(token);*/ }
public IActionResult GenerateToken(LoginModel model) { LoginModel checkUserFoundInDb = Authenticate(model); if (checkUserFoundInDb == null) { throw new HttpResponseException(HttpStatusCode.Unauthorized); } byte[] key = Convert.FromBase64String(Secret); SymmetricSecurityKey securityKey = new SymmetricSecurityKey(key); SecurityTokenDescriptor descriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, model.UserName) }), Expires = DateTime.UtcNow.AddDays(2), SigningCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature) }; JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler(); JwtSecurityToken token = handler.CreateJwtSecurityToken(descriptor); return(Ok(handler.WriteToken(token))); }
public string GenerateValidationToken(string userIdText, int role, int?Id) { var signingKey = Convert.FromBase64String(configuration[JwtConstant.SigningKey]); var expiryDuration = int.Parse(configuration[JwtConstant.ExpiryInMinutes]); var tokenDescriptor = new SecurityTokenDescriptor { Issuer = configuration[JwtConstant.Site], Audience = configuration[JwtConstant.Site], IssuedAt = DateTime.UtcNow, NotBefore = DateTime.UtcNow, Expires = DateTime.UtcNow.AddMinutes(expiryDuration), Subject = new ClaimsIdentity(new List <Claim> { new Claim(JwtConstant.UserIdText, userIdText), new Claim(JwtConstant.UserId, Convert.ToString(Id)), new Claim(JwtConstant.Role, role == 1?Constants.Role.Admin:Constants.Role.User) }), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(signingKey), SecurityAlgorithms.HmacSha256Signature) }; JwtSecurityTokenHandler jwtTokenHandler = new JwtSecurityTokenHandler(); JwtSecurityToken jwtToken = jwtTokenHandler.CreateJwtSecurityToken(tokenDescriptor); string token = jwtTokenHandler.WriteToken(jwtToken); return(token); }
/// <summary> /// /// </summary> /// <param name="username"></param> /// <returns></returns> public static string GenerateToken(string username) { // decoding the key(Secret) byte[] key = Convert.FromBase64String(Secret); //create a SymmetricSecurityKey object and passing the key(Secret) SymmetricSecurityKey securityKey = new SymmetricSecurityKey(key); // creating the descriptor object SecurityTokenDescriptor descriptor = new SecurityTokenDescriptor { // creating claims Subject = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, username) }), // the expiration date Expires = DateTime.UtcNow.AddMinutes(30), SigningCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature) }; // creating a handler JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler(); // the token is created JwtSecurityToken token = handler.CreateJwtSecurityToken(descriptor); // a string version of the token is returned return(handler.WriteToken(token)); }
/// <summary> /// Generate a JwtToken for a user /// </summary> /// <param name="user"></param> /// <returns></returns> public string GetToken(User user) { var signinKey = Convert.FromBase64String(_config["Jwt:SigninSecret"]); var expiryDuration = int.Parse(_config["Jwt:ExpiryDuration"]); var tokenDescriptor = new SecurityTokenDescriptor { Issuer = null, Audience = null, IssuedAt = DateTime.UtcNow, NotBefore = DateTime.UtcNow, Expires = DateTime.UtcNow.AddMinutes(expiryDuration), Subject = new ClaimsIdentity(new List <Claim> { new Claim("UserId", user.Id.ToString()) }), SigningCredentials = new SigningCredentials( new SymmetricSecurityKey(signinKey), SecurityAlgorithms.HmacSha256Signature ) }; var jwtTokenHandler = new JwtSecurityTokenHandler(); var jwtToken = jwtTokenHandler.CreateJwtSecurityToken(tokenDescriptor); return(jwtTokenHandler.WriteToken(jwtToken)); }
public async Task IssueAccessTokenAsync(TokenGeneratingContext context) { var accessToken = await CreateAccessTokenAsync(context); var subjectIdentity = CreateSubject(accessToken); var descriptor = new SecurityTokenDescriptor(); descriptor.Issuer = accessToken.Issuer; descriptor.Audience = accessToken.Audience; descriptor.Subject = subjectIdentity; descriptor.Expires = accessToken.Expires.UtcDateTime; descriptor.NotBefore = accessToken.NotBefore.UtcDateTime; var credentialsDescriptor = await _credentialsProvider.GetSigningCredentialsAsync(); descriptor.SigningCredentials = credentialsDescriptor.Credentials; var token = _handler.CreateJwtSecurityToken(descriptor); token.Payload.Remove(IdentityServiceClaimTypes.JwtId); token.Payload.Remove(IdentityServiceClaimTypes.IssuedAt); //token.Payload.Add(IdentityServiceClaimTypes.JwtId, accessToken.Id); context.AddToken(new TokenResult(accessToken, _handler.WriteToken(token), TokenKinds.Bearer)); }
private string GetTokenString(SecurityTokenDescriptor securityTokenDescriptor) { var handler = new JwtSecurityTokenHandler(); var token = handler.CreateJwtSecurityToken(securityTokenDescriptor); return(handler.WriteToken(token)); }
private string GetGitHubJWT(string privateKeyXML, int installationId) { log.LogInformation($"Getting JWT for installation id: {installationId}"); var provider = new RSACryptoServiceProvider(); var issuedAt = DateTime.UtcNow; var expires = DateTime.UtcNow.AddMinutes(10); RSAKeyValue rsaKeyValue; // deserialize the privateKeyXML as a RSAKeyValue var ser = new XmlSerializer(typeof(RSAKeyValue)); using (var reader = new StringReader(privateKeyXML)) { rsaKeyValue = ser.Deserialize(reader) as RSAKeyValue; } // provide those parameters to the RSACryptoServiceProvider // use ToRSAParameter to convert form base64 strings to // byte[] RSAParams provider.ImportParameters(rsaKeyValue.ToRSAParameters()); var key = new RsaSecurityKey(provider); // actually create the token (hooray!) var handler = new JwtSecurityTokenHandler(); var token = handler.CreateJwtSecurityToken($"{appId}", null, null, null, expires, issuedAt, new SigningCredentials(key, SecurityAlgorithms.RsaSha256)); var jwt = token.RawData; log.LogInformation($"jwt: {jwt}"); return(jwt); }
public static string GenerateToken(string username) { //Set issued at date DateTime issuedAt = DateTime.UtcNow; //set the time when it expires DateTime expires = DateTime.UtcNow.AddDays(7); var tokenHandler = new JwtSecurityTokenHandler(); //create a identity and add claims to the user which we want to log in ClaimsIdentity claimsIdentity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, username) }); var now = DateTime.UtcNow; var securityKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(System.Text.Encoding.Default.GetBytes(Secret)); var signingCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(securityKey, Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256Signature); //create the jwt var token = (JwtSecurityToken) tokenHandler.CreateJwtSecurityToken(subject: claimsIdentity, notBefore: issuedAt, expires: expires, signingCredentials: signingCredentials); var tokenString = tokenHandler.WriteToken(token); return(tokenString); }
public string GenerateJwtToken(UserModel user, IJwtSigningEncodingKey signingEncodingKey, IJwtEncryptingEncodingKey encryptingEncodingKey) { var claims = new Claim[] { new Claim(ClaimTypes.Name, user?.Login), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()) }; var tokenHandler = new JwtSecurityTokenHandler(); var token = tokenHandler.CreateJwtSecurityToken( issuer: JwtSettings.ValidIssuer, audience: JwtSettings.ValidAudience, subject: new ClaimsIdentity(claims), notBefore: DateTime.Now, expires: DateTime.Now.AddMinutes(5), issuedAt: DateTime.Now, signingCredentials: new SigningCredentials( signingEncodingKey.GetKey(), signingEncodingKey.SigningAlgorithm), encryptingCredentials: new EncryptingCredentials( encryptingEncodingKey.GetKey(), encryptingEncodingKey.SigningAlgorithm, encryptingEncodingKey.EncryptingAlgorithm) ); var jwteString = tokenHandler.WriteToken(token); return(jwteString); }
private string createToken(string username) { DateTime issuedAt = DateTime.UtcNow; DateTime expires = DateTime.UtcNow.AddDays(7); var tokenHandler = new JwtSecurityTokenHandler(); ClaimsIdentity claimsIdentity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, username) }); const string sec = "401b09eab3c013d4ca54922bb802bec8fd5318192b0a75f201d8b3727429090fb337591abd3e44453b954555b7a0812e1081c39b740293f765eae731f5a65ed1"; var now = DateTime.UtcNow; var securityKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(System.Text.Encoding.Default.GetBytes(sec)); var signingCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(securityKey, Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256Signature); var token = (JwtSecurityToken) tokenHandler.CreateJwtSecurityToken(issuer: "http://localhost:9870/", audience: "http://localhost:3000", subject: claimsIdentity, notBefore: issuedAt, expires: expires, signingCredentials: signingCredentials); var tokenString = tokenHandler.WriteToken(token); return(tokenString); }
private JwtPackage CreateToken(User user) { var tokenHandler = new JwtSecurityTokenHandler(); var claims = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Email, user.UserName) }); const string secretKey = "your secret key goes here"; var securityKey = new SymmetricSecurityKey(System.Text.Encoding.Default.GetBytes(secretKey)); var signinCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature); var token = (JwtSecurityToken)tokenHandler.CreateJwtSecurityToken( subject: claims, signingCredentials: signinCredentials ); var tokenString = tokenHandler.WriteToken(token); return(new JwtPackage() { UserName = user.UserName, Token = tokenString }); }
public JwtBearerToken GenerateToken(UserLogin userLogin, string roleType = "User") { var createdAt = DateTime.Now; var expiresAt = createdAt.AddTicks(ExpirationTicks); var securityTokenDescriptor = new SecurityTokenDescriptor { Issuer = _jwtBearerTokenOptions.Issuer, Audience = _jwtBearerTokenOptions.Audience, SigningCredentials = _signingOptions.SigningCredentials, Subject = GetClaimsIdentity(userLogin, roleType), IssuedAt = createdAt, NotBefore = createdAt, Expires = expiresAt, }; var jwtHandler = new JwtSecurityTokenHandler(); var securityToken = jwtHandler.CreateJwtSecurityToken(securityTokenDescriptor); var accessToken = jwtHandler.WriteToken(securityToken); return(new JwtBearerToken() { Created = createdAt.ToString("yyyy-MM-dd HH:mm:ss"), Expiration = expiresAt.ToString("yyyy-MM-dd HH:mm:ss"), AccessToken = accessToken, }); }
public static string GenerateToken(string username) { DateTime issuedAt = DateTime.UtcNow; DateTime expires = DateTime.UtcNow.AddDays(7); var tokenHandler = new JwtSecurityTokenHandler(); ClaimsIdentity claimsIdentity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, "UserName"), new Claim(ClaimTypes.Email, "*****@*****.**"), new Claim("DisplayName", "User"), new Claim(ClaimTypes.Role, "admin") }); var now = DateTime.UtcNow; var securityKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(System.Text.Encoding.Default.GetBytes(Secret)); var signingCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(securityKey, Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256Signature); var token = (JwtSecurityToken) tokenHandler.CreateJwtSecurityToken(issuer: "http://localhost:51888", audience: "http://localhost:400", subject: claimsIdentity, notBefore: issuedAt, expires: expires, signingCredentials: signingCredentials); var tokenString = tokenHandler.WriteToken(token); return(tokenString); }
public static string Sign(WebSecureToken token, SecurityMode mode, string secretKey) { byte[] bSecretKey = Encoding.ASCII.GetBytes(secretKey); string encoded = string.Empty; switch (mode) { case SecurityMode.Sign: var tokenHandler = new JwtSecurityTokenHandler(); var jwtoken = tokenHandler.CreateJwtSecurityToken(issuer: token.Issuer, audience: null, subject: new ClaimsIdentity(new[] { new Claim(WebSecureToken.GXISSUER, token.Issuer), new Claim(WebSecureToken.GXPROGRAM, token.ProgramName), new Claim(WebSecureToken.GXVALUE, token.Value), new Claim(WebSecureToken.GXEXPIRATION, token.Expiration.Subtract(new DateTime(1970, 1, 1)).TotalSeconds.ToString()) }), notBefore: DateTime.UtcNow, expires: token.Expiration, signingCredentials: new SigningCredentials(new SymmetricSecurityKey(bSecretKey), SecurityAlgorithms.HmacSha256)); return(tokenHandler.WriteToken(jwtoken)); } return(encoded); }
private string createToken(string username) { //Set issued at date DateTime issuedAt = DateTime.UtcNow; //set the time when it expires DateTime expires = DateTime.UtcNow.AddDays(7); //http://stackoverflow.com/questions/18223868/how-to-encrypt-jwt-security-token var tokenHandler = new JwtSecurityTokenHandler(); //create a identity and add claims to the user which we want to log in ClaimsIdentity claimsIdentity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, username) }); const string sec = "401b09eab3c013d4ca54922bb802bec8fd5318192b0a75f201d8b3727429090fb337591abd3e44453b954555b7a0812e1081c39b740293f765eae731f5a65ed1"; var now = DateTime.UtcNow; var securityKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(System.Text.Encoding.Default.GetBytes(sec)); var signingCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(securityKey, Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256Signature); //create the jwt var token = (JwtSecurityToken) tokenHandler.CreateJwtSecurityToken(issuer: "http://localhost:59848", audience: "http://localhost:59848", subject: claimsIdentity, notBefore: issuedAt, expires: expires, signingCredentials: signingCredentials); var tokenString = tokenHandler.WriteToken(token); return(tokenString); }
public async Task <AccessToken> GenerateAsync(User user) { var secretKey = Encoding.UTF8.GetBytes(_siteSetting.JwtSettings.SecretKey); // longer that 16 character var signingCredentials = new SigningCredentials(new SymmetricSecurityKey(secretKey), SecurityAlgorithms.HmacSha256Signature); var encryptionkey = Encoding.UTF8.GetBytes(_siteSetting.JwtSettings.Encryptkey); //must be 16 character var encryptingCredentials = new EncryptingCredentials(new SymmetricSecurityKey(encryptionkey), SecurityAlgorithms.Aes128KW, SecurityAlgorithms.Aes128CbcHmacSha256); var claims = await _getClaimsAsync(user); var descriptor = new SecurityTokenDescriptor { Issuer = _siteSetting.JwtSettings.Issuer, Audience = _siteSetting.JwtSettings.Audience, IssuedAt = DateTime.Now, NotBefore = DateTime.Now.AddMinutes(_siteSetting.JwtSettings.NotBeforeMinutes), Expires = DateTime.Now.AddMinutes(_siteSetting.JwtSettings.ExpirationMinutes), SigningCredentials = signingCredentials, EncryptingCredentials = encryptingCredentials, Subject = new ClaimsIdentity(claims) }; //JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); //JwtSecurityTokenHandler.DefaultMapInboundClaims = false; //JwtSecurityTokenHandler.DefaultOutboundClaimTypeMap.Clear(); var tokenHandler = new JwtSecurityTokenHandler(); var securityToken = tokenHandler.CreateJwtSecurityToken(descriptor); //string encryptedJwt = tokenHandler.WriteToken(securityToken); return(new AccessToken(securityToken)); }
public JsonWebToken(string securityKey, IEnumerable <Claim> claims, double?lifetimeMinutes, string issuer = null, string audience = null) { Issuer = issuer; Id = Guid.NewGuid().ToString(); created = DateTime.UtcNow; expires = created.AddMinutes(lifetimeMinutes.HasValue ? lifetimeMinutes.Value : 20); SigningKey = new SymmetricSecurityKey(Convert.FromBase64String(securityKey)); JwtSecurityTokenHandler jwt = new JwtSecurityTokenHandler(); SecurityTokenDescriptor msstd = new SecurityTokenDescriptor { Issuer = issuer, Subject = new ClaimsIdentity(claims), Expires = expires, IssuedAt = created, NotBefore = created, Audience = audience, SigningCredentials = new SigningCredentials(SigningKey, SecurityAlgorithms.HmacSha256Signature) }; try { JwtSecurityToken jwtToken = jwt.CreateJwtSecurityToken(msstd); tokenString = jwt.WriteToken(jwtToken); } catch (Exception ex) { Console.WriteLine(ex.Message); } }
public TokenDto CreateToken(AuthorizedApp authApp) { var tokenHandler = new JwtSecurityTokenHandler(); var issuedAt = DateTime.UtcNow; var expires = DateTime.UtcNow.AddDays(30); var claimsIdentity = new ClaimsIdentity(new GenericIdentity(authApp.Name), new[] { new Claim("appToken", authApp.AppToken, ClaimValueTypes.String), }); var securityKey = new SymmetricSecurityKey(System.Text.Encoding.Default.GetBytes(GlobalConfig.Secret)); var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature); //create the token var token = tokenHandler.CreateJwtSecurityToken( GlobalConfig.Issuer, GlobalConfig.Audience, claimsIdentity, issuedAt, expires, signingCredentials: signingCredentials); return(new TokenDto { Token = tokenHandler.WriteToken(token), Expires = expires, }); }
private Token GenerateTokenJWT() { var now = DateTime.Now; var secretKey = ConfigurationManager.AppSettings["JWT_SECRET_KEY"]; var audienceToken = ConfigurationManager.AppSettings["JWT_AUDIENCE_TOKEN"]; var issuerToken = ConfigurationManager.AppSettings["JWT_ISSUER_TOKEN"]; var expireTime = ConfigurationManager.AppSettings["JWT_EXPIRE_MINUTES"]; var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey)); var signingCredentrials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256); var tokenHandler = new JwtSecurityTokenHandler(); var jwtSecurityToken = tokenHandler.CreateJwtSecurityToken( audience: audienceToken, issuer: issuerToken, notBefore: now, expires: now.AddMinutes(Convert.ToInt32(expireTime)), signingCredentials: signingCredentrials ); var jwtTokenString = tokenHandler.WriteToken(jwtSecurityToken); Token token = new Token(); token.AccessToken = jwtTokenString; token.ExpiresIn = Convert.ToInt32(expireTime) * 60; return(token); }
private string CreateToken(int facadeIndex) { JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler(); ClaimsIdentity claims = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, FlyingCenterSystem.FacadeList[facadeIndex].LoginToken.User.UserName), new Claim(ClaimTypes.Role, FlyingCenterSystem.FacadeList[facadeIndex].LoginToken.User.GetType().ToString()), new Claim("FacadeListLocation", facadeIndex.ToString()) }); DateTime issuedAt = DateTime.UtcNow; DateTime expiresAt = DateTime.UtcNow.AddDays(1); SigningCredentials signingCredentials = new SigningCredentials(symmetricSecurityKey, Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256Signature); JwtSecurityToken jwtSecurityToken = (JwtSecurityToken)tokenHandler.CreateJwtSecurityToken ( issuer: "FlightSystem", subject: claims, signingCredentials: signingCredentials, issuedAt: issuedAt, expires: expiresAt ); string tokenString = tokenHandler.WriteToken(jwtSecurityToken); return(tokenString); }