public void NoSignatureToken_Should_Fail() { var payload = GetPayload(); var token = JWT.Encode(payload, null, JwsAlgorithm.none); var settings = BuildDefaultTokenValidationSettings(); var validationParameters = settings.BuildTokenValidationParameters(); Assert.Throws<SecurityTokenInvalidSignatureException>(() => { var claims = new JwtSecurityTokenHandler().ValidateToken(token, validationParameters, out SecurityToken securityToken); }); }
public static byte[] EncodeJwt(string username, AsymmetricCipherKeyPair newKey, bool isEmulator) { long iat = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); long exp = DateTimeOffset.UtcNow.AddDays(1).ToUnixTimeSeconds(); ECDsa signKey = ConvertToSingKeyFormat(newKey); string b64Key = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(newKey.Public).GetEncoded().EncodeBase64(); var certificateData = new CertificateData { Exp = exp, Iat = iat, ExtraData = new ExtraData { Xuid = "", DisplayName = username, Identity = isEmulator ? Guid.NewGuid().ToString() : "85e4febd-3d33-4008-b044-1ad9fb85b26c", TitleId = "89692877" }, Iss = "self", IdentityPublicKey = b64Key, CertificateAuthority = true, Nbf = iat, RandomNonce = new Random().Next(), }; // string txt = $@"{{ // ""exp"": 1467508449, // ""extraData"": {{ // ""displayName"": ""gurunxx"", // ""identity"": ""4e0199c6-7cfd-3550-b676-74398e0a5f1a"" // }}, // ""identityPublicKey"": ""{b64Key}"", // ""nbf"": 1467508448 //}}"; string val = JWT.Encode(certificateData, signKey, JwsAlgorithm.ES384, new Dictionary <string, object> { { "x5u", b64Key } }); Log.Debug(JWT.Payload(val)); Log.Debug(string.Join(";", JWT.Headers(val))); //val = "eyJhbGciOiJFUzM4NCIsIng1dSI6Ik1IWXdFQVlIS29aSXpqMENBUVlGSzRFRUFDSURZZ0FFREVLck5xdk93Y25iV3I5aUtVQ0MyeklFRmZ6Q0VnUEhQdG5Kd3VEdnZ3VjVtd1E3QzNkWmhqd0g0amxWc2RDVTlNdVl2QllQRktCTEJkWU52K09ZeW1MTFJGTU9odVFuSDhuZFRRQVV6VjJXRTF4dHdlVG1wSVFzdXdmVzRIdzAifQo.eyJleHAiOjE0Njc1MDg0NDksImV4dHJhRGF0YSI6eyJkaXNwbGF5TmFtZSI6Imd1cnVueHgiLCJpZGVudGl0eSI6IjRlMDE5OWM2LTdjZmQtMzU1MC1iNjc2LTc0Mzk4ZTBhNWYxYSJ9LCJpZGVudGl0eVB1YmxpY0tleSI6Ik1IWXdFQVlIS29aSXpqMENBUVlGSzRFRUFDSURZZ0FFREVLck5xdk93Y25iV3I5aUtVQ0MyeklFRmZ6Q0VnUEhQdG5Kd3VEdnZ3VjVtd1E3QzNkWmhqd0g0amxWc2RDVTlNdVl2QllQRktCTEJkWU52K09ZeW1MTFJGTU9odVFuSDhuZFRRQVV6VjJXRTF4dHdlVG1wSVFzdXdmVzRIdzAiLCJuYmYiOjE0Njc1MDg0NDh9Cg.jpCqzTo8nNVEW8ArK1NFBaqLx6kyJV6wPF8cAU6UGav6cfMc60o3m5DjwspN-JcyC14AlcNiPdWX8TEm1QFhtScb-bXo4WOJ0dNYXV8iI_eCTCcXMFjX4vgIHpb9xfjv"; val = $@"{{ ""chain"": [""{val}""] }}"; return(Encoding.UTF8.GetBytes(val)); }
/// <summary> /// Get an access token. Will return an valid existing token or retrieves a new one if expired. /// Note that the token could still be invalid when revoked remotely or because of clock skew for example. /// </summary> /// <param name="cancellationToken"></param> /// <param name="useExpiryCheck">True to return an existing token if not expired, false to force retrieval of new token</param> /// <returns>An access token</returns> private async Task <string> GetTokenAsync(CancellationToken cancellationToken, bool useExpiryCheck) { // Use access token if still valid if (useExpiryCheck && _token != null && DateTime.UtcNow < _token.ExpirationDate) { return(_token.AccessToken); } // Access token not valid (anymore), request new one var rsaCryptoServiceProvider = Opensslkey.GetRsaFromPemKey(_accountCredential.PrivateKey); var payload = new Dictionary <string, object> { { "iss", _accountCredential.ClientEmail }, { "scope", _scopes }, { "aud", _accountCredential.TokenUri }, { "sub", _emailAddress }, { "iat", DateTime.UtcNow.ToUnixTime() }, { "exp", DateTime.UtcNow.AddHours(1).ToUnixTime() } }; string jwt = JWT.Encode(payload, rsaCryptoServiceProvider, JwsAlgorithm.RS256); var content = new Dictionary <string, string> { { "assertion", jwt }, { "grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer" } }; var responseMessage = await _client.PostAsync(_accountCredential.TokenUri, new FormUrlEncodedContent(content), cancellationToken); if (!responseMessage.IsSuccessStatusCode) { //TODO: parse error response string contentString = await responseMessage.Content.ReadAsStringAsync(); GmailException ex = ErrorResponseParser.Parse(responseMessage.StatusCode, contentString); throw ex; } using (var stream = await responseMessage.Content.ReadAsStreamAsync()) using (var streamReader = new StreamReader(stream)) using (var jsonTextReader = new JsonTextReader(streamReader)) { _token = _jsonSerializer.Deserialize <OAuth2Token>(jsonTextReader); } _token.ExpirationDate = DateTime.UtcNow.AddSeconds(_token.ExpiresIn); return(_token.AccessToken); }
public async Task <IActionResult> GerarToken([FromBody] ViewModelLogin login) { if (ModelState.IsValid) { using (var context = new Context()) { var usuario = await context.Usuarios.FirstOrDefaultAsync(x => x.Email.Trim().ToLower() == login.Email.Trim().ToLower() && x.Senha == login.Senha); if (usuario != null) { var roles = new string[0]; var expireDate = DateTime.UtcNow.AddHours(1); var exp = new DateTimeOffset(expireDate); var payload = new Dictionary <string, object>() { { "unique_name", usuario.UsuarioId }, { "roles", roles }, //{ "company-roles",roles } , { "exp", exp.ToUnixTimeSeconds() }, { "iss", "flexxo.iss" }, { "aud", "flexxo.aud" } }; var headers = new Dictionary <string, object>(); try { var token = JWT.Encode(payload, Convert.FromBase64String(_configuration["TokenSecretKey"]), JwsAlgorithm.HS256, headers); return(Ok(new { token, usuario })); } catch (Exception e) { throw new Exception("Erro ao gerar token JWT", e); } } ModelState.AddModelError("", "Usuário ou senha inválidos"); } } return(BadRequest(ModelState)); }
public string CreateSignedToken(string data, string pemFile) { TimeSpan utcNow = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0); double totalMilliseconds = utcNow.TotalMilliseconds + 30000; Dictionary <string, object> strs = new Dictionary <string, object>() { { "sub", "tester" }, { "exp", totalMilliseconds }, { "datas", this.GetMd5(data).ToLower() } }; Dictionary <string, object> strs1 = strs; RSACryptoServiceProvider rSACryptoServiceProvider = Crypto.DecodeRsaPrivateKey(File.ReadAllText(pemFile), ""); return(JWT.Encode(strs1, rSACryptoServiceProvider, JwsAlgorithm.PS256, null)); }
public static RestRequest BuildRequestAuthorization(this RestClient webClient, ZoomClientOptions options, string resource, Method method) { var request = new RestRequest(resource, method); var payload = new Dictionary <string, object>() { { "iss", options.ZoomApiKey }, { "exp", new DateTimeOffset(DateTime.UtcNow.AddMinutes(1)).ToUnixTimeSeconds() } }; webClient.Authenticator = new JwtAuthenticator(JWT.Encode(payload, Encoding.UTF8.GetBytes(options.ZoomApiSecret), JwsAlgorithm.HS256)); request.JsonSerializer = new NewtonsoftJsonSerializer(); return(request); }
public string GenerateToken(string Account, string Role) { JwtObject payload = new JwtObject() { Account = Account, Role = Role, Expire = DateTime.Now.AddMinutes(Convert.ToInt32(WebConfigurationManager.AppSettings["ExpireMinutes"])).ToString() }; string SecretKey = WebConfigurationManager.AppSettings["SecretKey"].ToString(); string token = JWT.Encode(payload, Encoding.UTF8.GetBytes(SecretKey), JwsAlgorithm.HS512); return(token); }
private static string GenerateToken(Guid checkGuid, string sessionKey, Action action, int step, long userId) { var payload = new Dictionary <string, object>() { { "checkGuid", checkGuid.ToString() }, { "sessionKey", sessionKey }, { "action", action }, { "userId", userId }, //{ "branchId", branchId }, { "step", step }, { "exp", DateTime.UtcNow.AddMinutes(30) } }; return(JWT.Encode(payload, secretKey, JweAlgorithm.A256GCMKW, JweEncryption.A256CBC_HS512)); }
public void PassCorrectToken(JwsAlgorithm algorithm, string key) { IdentityModelEventSource.ShowPII = true; var payload = GetPayload(); var signKey = GetKey(key, algorithm); var token = JWT.Encode(payload, signKey, algorithm); var settings = BuildDefaultTokenValidationSettings(); var validationParameters = settings.BuildTokenValidationParameters(); var claims = new JwtSecurityTokenHandler().ValidateToken(token, validationParameters, out _); Assert.NotNull(claims); }
public void IfBearerTokenIsMadeWithCorrectSecretDecodesItAndReturnsJsonPayload() { var payload = new JObject() { { "sub", "*****@*****.**" }, { "exp", 1300819380 } }; var token = JWT.Encode(payload, workingSecret, JweAlgorithm.PBES2_HS256_A128KW, JweEncryption.A256CBC_HS512); new JWTService(_logger.Object) .Decode(workingSecret, token) .Should() .BeEquivalentTo(payload); }
public string Encode(User User) { this.User = User; var payload = new Dictionary <string, object>() { { "Id", User.Id }, { "email", User.email }, { "iat", ToUnixTime(issued).ToString() }, { "exp", ToUnixTime(expire).ToString() } }; this.token = JWT.Encode(payload, secretKey, JwsAlgorithm.HS256); Console.Write(token); return(this.token); }
private String GerarJwtToken(Usuario usuario) { Int32 timestampExpiracao = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds; timestampExpiracao += 43200; //12h var payload = new Dictionary <string, object> { { "sub", usuario.login }, { "exp", timestampExpiracao } }; var secretKey = Encoding.UTF8.GetBytes(ConfigurationManager.AppSettings["Chave"]); return(JWT.Encode(payload, secretKey, JwsAlgorithm.HS512)); }
public void IfSecretIsNullReturnsNull() { var payload = new JObject() { { "sub", "*****@*****.**" }, { "exp", 1300819380 } }; var token = JWT.Encode(payload, workingSecret, JweAlgorithm.PBES2_HS256_A128KW, JweEncryption.A256CBC_HS512); new JWTService(_logger.Object) .Decode(null, token) .Should() .BeNull(); }
public string CreateJwtToken <T>(string privateKey, T payloadObj) where T : JsonWebTokenPayloadBase { var payload = payloadObj.GeneratePayload(); var header = new Dictionary <string, object> { { "alg", "RS256" }, { "typ", "JWT" } }; var rsa = new RSACryptoServiceProvider(); rsa.FromXmlString(privateKey); return(JWT.Encode(payload, rsa, JwsAlgorithm.RS256, header)); }
public async Task <string> Login(LoginDTO login) { var dbUser = await _user.SingleOrDefaultAsync(x => x.Mail == login.Mail && x.Password == login.Password); if (dbUser == null) { return(null); } dbUser.Password = null; return(JWT.Encode(_mapper.Map <CurrentUserDTO>(dbUser), Encoding.UTF8.GetBytes(_jwtKey), JwsAlgorithm.HS256)); }
public static string Encode(string key, string issuer, double expiration) { var payload = new Dictionary <string, object>() { { "iss", issuer }, { "iat", DateTime.UtcNow }, { "exp", DateTime.UtcNow.AddMinutes(expiration) } }; return(JWT.Encode( payload, Convert.FromBase64String(key), JweAlgorithm.A256GCMKW, JweEncryption.A256CBC_HS512)); }
public void IfBearerTokenIsMadeWithAnotherSecretFailsToDecode() { var payload = new Dictionary <string, object>() { { "sub", "*****@*****.**" }, { "exp", 1300819380 } }; var token = JWT.Encode(payload, "a different secret", JweAlgorithm.PBES2_HS256_A128KW, JweEncryption.A256CBC_HS512); new JWTService(_logger.Object) .Decode(workingSecret, token) .Should() .BeNull(); }
/// <summary> /// 创建Token /// </summary> /// <param name="data"></param> /// <returns></returns> public static string CreatToken(LoginDataDto data) { var secret = ConfigurationManager.AppSettings["TokenSecret"]; var payload = new { id = data.UserId, name = data.UserName.Trim().ToLower(), iss = "CCServer.Api", aud = "www.liaoyu.com", sub = "CCServer.APP", time = DateTime.Now.ToString("yyyy-MM-dd") }; return(JWT.Encode(payload, Encoding.UTF8.GetBytes(secret), JwsAlgorithm.HS256)); }
private static string GenerateJWT() { var header = new Dictionary <string, object>() { { "typ", "JWT" }, { "alg", "ES256" } }; var payload = new Dictionary <string, object>() { { "userID", _localID }, { "appID", _appID }, { "keyID", _keyID }, { "iat", DateTime.UtcNow.ToUnixTimeStampSeconds() }, { "nbf", DateTime.UtcNow.AddMinutes(-5).ToUnixTimeStampSeconds() }, { "exp", DateTime.UtcNow.AddHours(1).ToUnixTimeStampSeconds() }, { "jti", _jti } }; try { string eccKey = @"ecc-key.p12"; if (File.Exists(eccKey)) { if (new FileInfo(eccKey).Length != 0) { return(JWT.Encode(payload, new X509Certificate2(eccKey, (string)Config.localSettings.Values["secret"]).GetECDsaPrivateKey(), JwsAlgorithm.ES256, extraHeaders: header)); } else { Debug.WriteLine("[Error] File is empty."); return(string.Empty); } } else { Debug.WriteLine("[Error] File does not exist."); return(string.Empty); } } catch (Exception ex) { Debug.WriteLine($"[Error] GenerateJWT: {ex.Message}"); return(string.Empty); } }
public void WrongSignatureToken_Should_Fail(JwsAlgorithm algorithm, string key) { var payload = GetPayload(); var signKey = GetKey(key, algorithm); var token = JWT.Encode(payload, signKey, algorithm); var settings = BuildDefaultTokenValidationSettings(); var validationParameters = settings.BuildTokenValidationParameters(); Assert.Throws<SecurityTokenInvalidSignatureException>(() => { var claims = new JwtSecurityTokenHandler().ValidateToken(token, validationParameters, out SecurityToken securityToken); }); }
public string GetDetailedToken(string userName, string email, string name) { string token = null; try { DetailedJwtPayload payload = new DetailedJwtPayload(userName, email, name); token = JWT.Encode(payload, Encoding.ASCII.GetBytes(_jwtConfig.SecretKey), _jwtConfig.jwsAlgorithm); } catch { return(null); } return(token); }
public string GetBasicToken(string userName) { string token = null; try { BasicJwtPayload payload = new BasicJwtPayload(userName); token = JWT.Encode(payload, Encoding.ASCII.GetBytes(_jwtConfig.SecretKey), _jwtConfig.jwsAlgorithm); } catch { return(null); } return(token); }
public string GetJwt(string user, string pass) //function for JWT Token { byte[] secretKey = Base64UrlDecode("Hi"); //pass key to secure and decode it DateTime issued = DateTime.Now; var User = new Dictionary <string, object>() { { "user", user }, { "pass", pass }, { "iat", ToUnixTime(issued).ToString() } }; string token = JWT.Encode(User, secretKey, JwsAlgorithm.HS256); return(token); }
private string get_token() { DateTime issued = DateTime.Now; string iss = Guid.NewGuid().ToString(); long iat = ToUnixTime(issued); string jti = Guid.NewGuid().ToString(); var payload = new Dictionary <string, object>() { { "iss", iss }, { "iat", iat }, { "jti", jti } }; return(JWT.Encode(payload, Encoding.ASCII.GetBytes(_client_key), JwsAlgorithm.HS256)); }
public static void createEncryptionToken() { var payload = new Dictionary <string, object>() { { "sub", "*****@*****.**" }, { "exp", 1300819380 } }; var publicKey = new X509Certificate2(clientCert, "1234%%abcd").PublicKey.Key as RSACryptoServiceProvider; string token = JWT.Encode(payload, publicKey, JweAlgorithm.RSA_OAEP, JweEncryption.A256GCM); var privateKey = new X509Certificate2(clientCert, "1234%%abcd", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet).PrivateKey as RSACryptoServiceProvider; string json = JWT.Decode(token, privateKey); Console.WriteLine(json); }
public async Task <string> Login(LoginDto model) { var user = await _context .Users .AsNoTracking() .SingleOrDefaultAsync(x => x.Username == model.Username); if (user == null || !BCrypt.Net.BCrypt.Verify(model.Password, user.Password)) { return(null); } return(JWT.Encode(_mapper.Map <CurrentUserDto>(user), Encoding.UTF8.GetBytes(_jwtKey), JwsAlgorithm.HS256)); }
public static string GetJwtToken(User userToGenerateFor) { var secret = Encoding.UTF8.GetBytes(ConfigurationManager.AppSettings["as:AudienceSecret"]); var issuer = ConfigurationManager.AppSettings["as:Issuer"]; var audienceId = ConfigurationManager.AppSettings["as:AudienceId"]; var currentSeconds = Math.Round(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds); var payload = new Dictionary <string, string> { { "iss", issuer }, { "aud", audienceId }, { "exp", (currentSeconds + 20000).ToString(CultureInfo.InvariantCulture) }, { "userid", userToGenerateFor.UserId.ToString() } }; return(JWT.Encode(payload, secret, JwsAlgorithm.HS256)); }
public string Create <TPayload>(TPayload payload, string key) where TPayload : Payload { var payloadJsonObject = JObject.FromObject(payload); payloadJsonObject["CreationTime"] = DateTime.UtcNow; payloadJsonObject["Lifetime"] = _configuration.Lifetime; var uniqueKey = key + _configuration.SecretKey; var registerMapper = JWT.DefaultSettings.RegisterMapper(_jsonMapper); var token = JWT.Encode(payloadJsonObject, Encoding.Unicode.GetBytes(uniqueKey), JwsAlgorithm.HS512, settings: registerMapper); return(token); }
public string CreateToken(int userId) { var unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); var expiry = Math.Round((DateTime.UtcNow.AddSeconds(30) - unixEpoch).TotalSeconds); var payload = new Dictionary <string, object> { { "userId", userId }, { "sub", userId }, { "exp", expiry } }; var token = JWT.Encode(payload, _secretKey, JwsAlgorithm.HS256);; return(token); }
public string Build(string secretKey) { var secretKeyBytes = Guid.ParseExact(secretKey, "D").ToRFC4122ByteArray(); var now = DateTimeOffset.Now; var payload = new Dictionary <string, object>() { { "iat", now.ToUnixTimeSeconds() }, { "nbf", now.ToUnixTimeSeconds() }, }; if (expiration.HasValue) { payload["exp"] = new DateTimeOffset(expiration.Value).ToUnixTimeSeconds(); } if (viewIdentifiers.Count > 0) { payload[ViewIdentifiersClaimName] = viewIdentifiers; } if (parameters.Count > 0) { payload[ParametersClaimName] = parameters; } if (attributes.Count > 0) { payload[AttributesClaimName] = attributes; } var headers = new Dictionary <string, object>() { { "cty", "JWT" }, { "kid", accessKey }, }; return(JWT.Encode( payload: payload, key: secretKeyBytes, alg: JweAlgorithm.DIR, enc: JweEncryption.A128GCM, compression: JweCompression.DEF, extraHeaders: headers, settings: settings)); }