public void DecodeToObject_Should_DecodeToken_On_Exp_Claim_After_Year2038() { var key = _fixture.Create <string>(); var dateTimeProvider = new UtcDateTimeProvider(); var serializer = new JsonNetSerializer(); var validator = new JwtValidator(serializer, dateTimeProvider); var urlEncoder = new JwtBase64UrlEncoder(); var decoder = new JwtDecoder(serializer, validator, urlEncoder); // Why 2038? See https://en.wikipedia.org/wiki/Year_2038_problem var post2038 = new DateTime(2038, 1, 19, 3, 14, 8, DateTimeKind.Utc); var exp = (post2038 - new DateTime(1970, 1, 1)).TotalSeconds; var payload = new { exp }; var encoder = new JwtEncoder(new HMACSHA256Algorithm(), serializer, urlEncoder); var validToken = encoder.Encode(payload, key); var expected = serializer.Serialize(payload); var actual = decoder.Decode(validToken, key, true); expected.Should() .Be(actual, "because the token should be correctly decoded"); }
public void DecodeToObject_Should_Throw_Exception_On_Invalid_Expiration_Claim_MultipleKeys() { var key = _fixture.Create <string>(); var keys = _fixture.Create <string[]>(); keys[0] = key; var serializer = new JsonNetSerializer(); var validator = new JwtValidator(serializer, new UtcDateTimeProvider()); var urlEncoder = new JwtBase64UrlEncoder(); var decoder = new JwtDecoder(serializer, validator, urlEncoder); var encoder = new JwtEncoder(new HMACSHA256Algorithm(), serializer, urlEncoder); var token = encoder.Encode(new { exp = _fixture.Create <string>() }, key); Action encodingAJwtWithWrongExpField = () => decoder.DecodeToObject <Customer>(token, keys, verify: true); encodingAJwtWithWrongExpField.Should() .Throw <SignatureVerificationException>("because the invalid 'exp' must result in an exception on decoding"); }
public AuthenticationStatus GenerateToken(User user, out string token) { AuthenticationStatus result = AuthenticationStatus.Success; token = null; if (_jwtSettings.IsEnabled) { DateTime unixEpoch = UnixEpoch.Value; IDateTimeProvider provider = new UtcDateTimeProvider(); DateTimeOffset now = provider.GetNow().AddSeconds(_jwtSettings.ExpirationSpan); double secondsSinceEpoch = Math.Round((now - unixEpoch).TotalSeconds); Dictionary <string, object> payload = new Dictionary <string, object> { { "exp", secondsSinceEpoch.ToString(CultureInfo.InvariantCulture) }, { "Id", user.Id }, { "Email", user.Email }, { "Role", user.Role } }; IJwtAlgorithm algorithm = new HMACSHA256Algorithm(); IJsonSerializer serializer = new JsonNetSerializer(); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder); token = encoder.Encode(payload, _jwtSettings.SignatureSecret); } else { result = AuthenticationStatus.ClientDisabled; } return(result); }
public string Encode <T>(T data, string secret, out DateTime exp) { var json = JsonConvert.SerializeObject(data, Formatting.Indented); var payload = JsonConvert.DeserializeObject <Dictionary <string, object> >(json); var exp2 = DateTimeOffset.UtcNow.AddDays(1); exp = exp2.UtcDateTime; if (!payload.ContainsKey("exp")) { payload.Add("exp", exp2.ToUnixTimeSeconds()); } IJwtAlgorithm algorithm = new HMACSHA256Algorithm(); IJsonSerializer serializer = new JsonNetSerializer(); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder); var token = encoder.Encode(payload, secret); return(token); }
public LoginResult Post([FromBody] LoginRequest request) { LoginResult rs = new LoginResult(); //这是是获取用户名和密码的,这里只是为了模拟 if (request.UserName == "wangshibang" && request.Password == "123456") { AuthInfo info = new AuthInfo { UserName = "******", Roles = new List <string> { "Admin", "Manage" }, IsAdmin = true }; try { const string secret = "To Live is to change the world"; //secret需要加密 IJwtAlgorithm algorithm = new HMACSHA256Algorithm(); IJsonSerializer serializer = new JsonNetSerializer(); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder); var token = encoder.Encode(info, secret); rs.Message = "XXXXX"; rs.Token = token; rs.Success = true; } catch (Exception ex) { rs.Message = ex.Message; rs.Success = false; } } else { rs.Message = "fail"; rs.Success = false; } return(rs); }
public IHttpActionResult Login([FromBody] LoginViewModel model) { if (model == null) { model = new LoginViewModel(); Validate(model); } if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var user = DbSet.Users.FirstOrDefault(c => c.Username == model.Username && c.Password == model.Password); if (user != null) { const string secret = "gjhgjhgmjgjmhgjhtjmjmgjmgjmgjhm"; IJwtAlgorithm algorithm = new HMACSHA256Algorithm(); IJsonSerializer serializer = new JsonNetSerializer(); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder); var payload = new Dictionary <string, object> { { "Id", user.Id } }; var token = encoder.Encode(payload, secret); var result = new TokenModel() { AccessToken = token, Type = "Bearer", LifeTime = 0 }; return(Ok(result)); } return(Unauthorized()); }
/// <summary> /// 获取JWT token /// </summary> /// <param name="token"></param> /// <param name="expireTime">过期时间</param> /// <returns></returns> public static bool GetToken(out JwtResult jwtResult, int expireTime = 20) { try { DateTime UTC = DateTime.Now; Dictionary <string, object> payload = new Dictionary <string, object> { { "iat", ConvertDateTimeInt(UTC) }, { "iss", "ERP@Oversea" }, { "exp", ConvertDateTimeInt(UTC.AddMinutes(expireTime)) } }; IJwtAlgorithm algorithm = new HMACSHA256Algorithm(); IJsonSerializer serializer = new JsonNetSerializer(); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder); string result = encoder.Encode(payload, secret); string token = DESEncrypt.DesEncrypt(result); jwtResult = new JwtResult() { JwtCode = token, IsSuccess = true, Message = "success" }; return(true); } catch (Exception e) { Utility.Log.WriteTextLog("JWTGetToken", "JWT.GetToken:", e.Message, "", ""); jwtResult = new JwtResult() { JwtCode = "", IsSuccess = false, Message = e.Message }; return(false); } }
public TokenInfo GetToken([FromBody] LoginRequest loginRequest) { TokenInfo tokenInfo = new TokenInfo(); if (loginRequest != null) { string userName = loginRequest.UserName; string passWord = loginRequest.Password; bool isAdmin = (userName == "SWD") ? true : false; AuthInfo authInfo = new AuthInfo { UserName = userName, Roles = new List <string>(), IsAdmin = isAdmin, ExpiryDateTime = DateTime.Now.AddDays(1) }; const string secretKey = "ShunKai";// try { byte[] key = Encoding.UTF8.GetBytes(secretKey); IJwtAlgorithm algorithm = new HMACSHA256Algorithm(); IJsonSerializer serializer = new JsonNetSerializer(); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder); var token = encoder.Encode(authInfo, key); tokenInfo.Success = true; tokenInfo.Token = token; tokenInfo.Message = "OK"; } catch (Exception ex) { tokenInfo.Success = false; tokenInfo.Message = ex.Message.ToString(); } } else { tokenInfo.Success = false; tokenInfo.Message = "用户信息为空"; } return(tokenInfo); }
public static string GenerateToken(string key, string data, int duration = 48) { IDateTimeProvider provider = new UtcDateTimeProvider(); var expiry = provider.GetNow().AddHours(duration); var unixEpoch = JwtValidator.UnixEpoch; var secondsSinceEpoch = Math.Round((expiry - unixEpoch).TotalSeconds); var payload = new Dictionary <string, object> { { key, data }, { "exp", secondsSinceEpoch } }; var secret = Config.Secret; IJwtAlgorithm algorithm = new HMACSHA256Algorithm(); IJsonSerializer serializer = new JsonNetSerializer(); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder); var token = encoder.Encode(payload, secret); return(token); }
private static string createJWT(string username, string[] groups, string name) { var payload = new Dictionary <string, object> { { "username", username.Replace("\\\\", "\\") }, { "id", username }, { "name", name }, { "groups", groups } }; string secret = ConfigurationManager.AppSettings["jwtSecret"]; IJwtAlgorithm algorithm = new HMACSHA256Algorithm(); IJsonSerializer serializer = new JsonNetSerializer(); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder); var token = encoder.Encode(payload, secret); return(token); }
//生成access_token private string GetToken(string username) { IDateTimeProvider provider = new UtcDateTimeProvider(); var now = provider.GetNow(); var unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); // or use JwtValidator.UnixEpoch var secondsSinceEpoch = Math.Round((now - unixEpoch).TotalSeconds); var payload = new Dictionary <string, object> { { "name", username }, //{"exp",secondsSinceEpoch+(20) } { "exp", secondsSinceEpoch + (3600 * 24 * 30) } //超时时间,单位:秒 }; var secret = "GQDstcKsx0NHjPOuXOYg5MbeJ1XT0uFiwDVvVBrk"; IJwtAlgorithm algorithm = new HMACSHA256Algorithm(); IJsonSerializer serializer = new JsonNetSerializer(); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder); var token = encoder.Encode(payload, secret); return(token); }
public static string Generate(string userName) { var secret = ConfigurationManager.AppSettings["JWTSecret"]; var expireMinutes = ConfigurationManager.AppSettings["JWTExpireMinutes"]; IDateTimeProvider provider = new UtcDateTimeProvider(); var now = provider.GetNow(); var unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); // or use JwtValidator.UnixEpoch var secondsSinceEpoch = Math.Round((now.AddMinutes(int.Parse(expireMinutes)) - unixEpoch).TotalSeconds); var payload = new Dictionary <string, object> { { "user", userName }, { "exp", secondsSinceEpoch } }; IJwtAlgorithm algorithm = new HMACSHA256Algorithm(); IJsonSerializer serializer = new JsonNetSerializer(); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder); var token = encoder.Encode(payload, secret); return(token); }
private static string Encoder(object obj, string type) { IJwtAlgorithm algorithm = new HMACSHA256Algorithm(); IJsonSerializer serializer = new JsonNetSerializer(); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder); string secret; switch (type) { case "header": secret = Service.key_header; break; default: secret = Service.key_data; break; } ; string token = encoder.Encode(obj, secret); return(token); }
public const string SECRETKEY = "jwttest"; //加密的密钥 /// <summary> /// 使用自定义密钥加密,HS512签名 /// </summary> /// <param name="strSecretKey">密钥</param> /// <param name="strJson">需要加密的JSON</param> /// <returns></returns> public static string EncodeByJwt(string strSecretKey, string strJson) { try { var payload = new Dictionary <string, object> { { "Crypt", strJson } }; IJwtAlgorithm algorithm = new HMACSHA512Algorithm(); IJsonSerializer serializer = new JsonNetSerializer(); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder); var token = encoder.Encode(payload, strSecretKey); return(token); } catch (Exception ex) { throw; } }
public string GetToken() { // setup payload var payload = new { iss = "appnotch.com", sub = _subject, iat = DateTime.UtcNow.ToUnixTimestamp(), jti = Guid.NewGuid().ToString("N") }; IJwtAlgorithm algorithm = new HMACSHA256Algorithm(); IJsonSerializer serializer = new JsonNetSerializer(); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder); // convert the secret to base64 string and use as key var base64Secret = Convert.FromBase64String(_secret); var token = encoder.Encode(payload, base64Secret); return(token); }
public string TesteJwt() { var header = new Header(); var paylod = new Payload() { uuid = "2", srcDateTime = DateTime.Now.ToString("yyyy-MM-dd'T'HH:mm:ssZ"), srcId = 123, srcAgencyNumber = "2568", srcAccountNumber = "5005565", srcClientName = "Ryoji", srcCpfCnpj = "885588999555", amount = 5058, urlConfirm = "http://google.com.br", withdrawStatus = "aprovado" }; var privateKey = new X509Certificate2("my-key.p12", "password", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet); var extraHeaders = new Dictionary <string, object> { { "partner", 0000 }, { "versionKey", 1 } }; IJwtAlgorithm algorithm = new RS256Algorithm(privateKey); IJsonSerializer serializer = new JsonNetSerializer(); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder); var jsonWebToken = encoder.Encode(extraHeaders, paylod, privateKey.PrivateKey.ToString()); return(jsonWebToken); }
public void Fail() { var payload = FixtureFactory.Create <Payload>(); var key = LitJWT.Algorithms.HS256Algorithm.GenerateRandomRecommendedKey(); var encoder = new JwtEncoder(new LitJWT.Algorithms.HS256Algorithm(key)); var result = encoder.Encode(payload, null, (x, writer) => writer.Write(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(x)))); var decoder = new JwtDecoder(new LitJWT.Algorithms.HS256Algorithm(key)); { var span = result.ToCharArray().AsSpan(); span[4] = '?'; var decodeResult = decoder.TryDecode(span, x => JsonConvert.DeserializeObject <Payload>(Encoding.UTF8.GetString(x)), out var decodedPayload); decodeResult.Should().Be(DecodeResult.InvalidBase64UrlHeader); } { var span = result.ToCharArray().AsSpan(); var decoder2 = new JwtDecoder(new LitJWT.Algorithms.HS384Algorithm(key)); var decodeResult = decoder2.TryDecode(span, x => JsonConvert.DeserializeObject <Payload>(Encoding.UTF8.GetString(x)), out var decodedPayload); decodeResult.Should().Be(DecodeResult.AlgorithmNotExists); } { var span = result.ToCharArray().AsSpan(); span[span.Length - 10] = 'A'; span[span.Length - 11] = 'B'; span[span.Length - 12] = 'C'; // maybe break signature var decodeResult = decoder.TryDecode(span, x => JsonConvert.DeserializeObject <Payload>(Encoding.UTF8.GetString(x)), out var decodedPayload); decodeResult.Should().Be(DecodeResult.FailedVerifySignature); } }
public const string jti = "jti"; //jwt的唯一身份标识,主要用来作为一次性token,从而回避重放攻击。 /// <summary> /// jwt的第三部分是一个签证信息,这个签证信息由三部分组成: /// 1、header (base64后的) /// 2、payload (base64后的) /// 3、signature (这个部分需要base64加密后的header和base64加密后的payload使用.连接组成的字符串,然后通过header中声明的加密方式进行加secret组合加密,然后就构成了jwt的第三部分) /// 将这三部分用.连接成一个完整的字符串,构成了最终的jwt /// </summary> /// <param name="payload">载荷, 就是存放有效信息的地方</param> /// <param name="expire">过期时间, 单位:秒</param> /// <returns></returns> public static string Encode(Dictionary <string, object> payload, double expire = 24 * 60 * 60) { //var payload = new Dictionary<string, object> //{ // { "claim1", 0 }, // { "claim2", "claim2-value" } //}; if (expire != 0) { //添加过期时间 IDateTimeProvider provider = new UtcDateTimeProvider(); var now = provider.GetNow(); var unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); // or use JwtValidator.UnixEpoch var secondsSinceEpoch = Math.Round((now - unixEpoch).TotalSeconds) + expire; if (payload.ContainsKey(exp)) { payload[exp] = secondsSinceEpoch; } else { payload.Add(exp, secondsSinceEpoch); } } IJwtAlgorithm algorithm = new HMACSHA256Algorithm(); IJsonSerializer serializer = new CustomJsonSerializer(); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder); var token = encoder.Encode(payload, secret); return(token); }
private string GetToken(Dictionary <string, object> payload) { var secret = _options.SecretKey; payload.Add("iss", _options.Issuer); payload.Add("aud", _options.Audience); payload.Add("nbf", ConvertToUnixTimestamp(DateTime.Now)); payload.Add("iat", ConvertToUnixTimestamp(DateTime.Now)); payload.Add("exp", ConvertToUnixTimestamp(DateTime.Now.AddDays(7))); IJwtAlgorithm algorithm = new HMACSHA256Algorithm(); IJsonSerializer serializer = new JsonNetSerializer(); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder); return(encoder.Encode(payload, secret)); //List<Claim> claims = new List<Claim>(); //foreach (var item in payload) //{ // claims.Add(new Claim(item.Key.ToString(), item.Value.ToString())); //} //claims.Add(new Claim("nbf", ConvertToUnixTimestamp(DateTime.Now).ToString())); //claims.Add(new Claim("iat", ConvertToUnixTimestamp(DateTime.Now).ToString())); //SigningCredentials signingCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret)), SecurityAlgorithms.HmacSha256); //var token = new JwtSecurityToken(_options.Issuer, // _options.Audience, // claims, // expires: DateTime.Now.Add(TimeSpan.FromDays(7)), // signingCredentials: signingCredentials); //return new JwtSecurityTokenHandler().WriteToken(token); }
public void SignIn(TBody body) { // 获取 密钥 string secret = SecretBuilder.Build(); if (string.IsNullOrWhiteSpace(secret)) { throw new Exception("应用程序密钥(AppSecret)为空或null"); } // 生成加密token; IAlgorithmFactory algorithmFactory = new HMACSHAAlgorithmFactory(); IJwtAlgorithm algorithm = algorithmFactory.Create(AuthConfigProvider.AuthConfig.JwtAlgorithmType); IJsonSerializer serializer = new JsonNetSerializer(); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder); string token = encoder.Encode(body, secret); // 写入Cookie ICookieFactory cookieFactory = new CookieFactory(); ICookieClient cookieClient = cookieFactory.Create(); cookieClient.SetCookie(AuthConfigProvider.AuthConfig.CookieName, token, AuthConfigProvider.AuthConfig.Expires); }
private string CreateJWTToken(Dictionary <string, string> cachingServiceParameters, ITracingService trace, IOrganizationService service) { if (trace == null) { throw new InvalidPluginExecutionException(ValidationMessages.TraceIsNull); } if (cachingServiceParameters == null) { throw new InvalidPluginExecutionException(ValidationMessages.CachingParameterIsNull); } if (service == null) { throw new InvalidPluginExecutionException(ValidationMessages.OrganizationServiceIsNull); } trace.Trace("Start - CreateJWTToken"); if (string.IsNullOrWhiteSpace(this.SecretKey)) { throw new InvalidPluginExecutionException(ValidationMessages.CachingSecretKeyIsNullOrEmpty); } var payload = new Dictionary <string, object>() { { JwtPayloadParameters.IssuedAtTime, GetIssuedAtTime(cachingServiceParameters, trace).ToString() }, { JwtPayloadParameters.NotBeforeTime, GetNotBeforeTime(cachingServiceParameters, trace).ToString() }, { JwtPayloadParameters.Expiry, GetExpiry(cachingServiceParameters, trace).ToString() } }; IJwtAlgorithm algorithm = new HMACSHA256Algorithm(); IJsonSerializer serializer = new JsonNetSerializer(); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder); return(encoder.Encode(payload, this.SecretKey)); }
public static string SetJwtEncode(Dictionary <string, object> payload) { IDateTimeProvider provider = new UtcDateTimeProvider(); var now = provider.GetNow(); var unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); var secondsSinceEpoch = Math.Round((now - unixEpoch).TotalSeconds); payload.Add("exp", secondsSinceEpoch + 2); payload.Add("iat", now.ToString()); payload.Add("issuer", "eduplat"); payload.Add("audience", ""); payload.Add("jti", Guid.NewGuid().ToString()); IJwtAlgorithm algorithm = new HMACSHA256Algorithm(); IJsonSerializer serializer = new JsonNetSerializer(); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder); var token = encoder.Encode(payload, secret); var key = EncryptionAlgorithm.Hash(token); return(token); }
public string CreateToken() { IDateTimeProvider provider = new UtcDateTimeProvider(); IJwtAlgorithm algorithm = new HMACSHA256Algorithm(); IJsonSerializer serializer = new JsonNetSerializer(); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder); var now = provider.GetNow(); var unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); var expiry = Math.Round((now.AddHours(12) - unixEpoch).TotalSeconds); //12 hours expiry //add claims in payload for now we will leave it blank var payload = new Dictionary <string, object> { { "exp", expiry }, { "user", User } }; var secret = ConfigurationManager.AppSettings["jwtSecret"]; return(encoder.Encode(payload, secret)); }
public IActionResult Register(string username, string password) { if (UserExists(username)) { return(Conflict()); } else { //先存,拿到自增的id User user = new User(); user.Name = username; user.Password = password; _context.Users.Add(user); _context.SaveChanges(); var user_new = _context.Users.Single(u => u.Name == username); //将id写到JWT中,二次存储 var payload = new Dictionary <string, object> { { "iss", "RecordProAPI" }, { "iat", DateTime.Now.ToString() }, { "name", username }, { "id", user_new.id } }; const string secret = "ezio0124"; IJwtAlgorithm algorithm = new HMACSHA256Algorithm(); // symmetric IJsonSerializer serializer = new JsonNetSerializer(); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder); var token = encoder.Encode(payload, secret); //刷新token user_new.Token = token; _context.Update <User>(user_new); _context.SaveChanges(); return(CreatedAtAction("Register", new { id = user.id }, user)); } }
public static string CreateToken(CustomRouteData route) { var host = GetHostDatas().First(o => o.Name == route.MicroService); IDateTimeProvider provider = new UtcDateTimeProvider(); var now = provider.GetNow(); var unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); // or use JwtValidator.UnixEpoch var secondsSinceEpoch = Math.Round((now - unixEpoch).TotalSeconds) + 60; //60S后过期 var payload = new Dictionary <string, object> { { "app_id", host.ApplicationId }, { "exp", secondsSinceEpoch } }; var secret = host.ApplicationKey; IJwtAlgorithm algorithm = new HMACSHA256Algorithm(); IJsonSerializer serializer = new JsonNetSerializer(); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder); var token = encoder.Encode(payload, secret); return(token); }
/// <summary> /// 生成JwtToken /// </summary> /// <param name="payload">不敏感的用户数据</param> /// <returns></returns> public static string SetJwtEncode(AuthInfo authInfo) { //格式如下 //var payload = new Dictionary<string, object> //{ // { "username","admin" }, // { "pwd", "claim2-value" } //}; IJwtAlgorithm algorithm = new HMACSHA256Algorithm(); IJsonSerializer serializer = new JsonNetSerializer(); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder); var jwtcreated = Math.Round((DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds + 5); var jwtcreatedOver = Math.Round((DateTime.UtcNow.AddDays(7) - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds + 5);//TOKEN声明周期一周 var payload = new Dictionary <string, dynamic> { { "iss", authInfo.iss }, //非必须。issuer 请求实体,可以是发起请求的用户的信息,也可是jwt的签发者。 { "iat", jwtcreated }, //非必须。issued at。 token创建时间,unix时间戳格式 { "exp", jwtcreatedOver }, //非必须。expire 指定token的生命周期。unix时间戳格式 { "aud", authInfo.aud }, //非必须。接收该JWT的一方。 { "sub", authInfo.sub }, //非必须。该JWT所面向的用户 { "jti", authInfo.jti }, //非必须。JWT ID。针对当前token的唯一标识 { "userInfo", authInfo.userInfo } //自定义字段 用于存放当前登录人账户信息 //{"userId", authInfo.userId},//自定义字段 用于存放当前登录人账户信息 //{"userName", authInfo.userName},//自定义字段 用于存放当前登录人账户信息 //{"userPwd", authInfo.userPwd},//自定义字段 用于存放当前登录人登录密码信息 //{"userRole", authInfo.userRoles},//自定义字段 用于存放当前登录人登录权限信息 }; var token = encoder.Encode(payload, secret); return(token); }
private static string secretKey = "GQDstcKsx0NHjPOuXOYg5MbeJ1XT0uFiwDVvVBrk"; // This secret key is configurable public static string CreateJSONWebToken(string userId, string password, string vendor) { var now = Math.Round((DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds); var exp = Math.Round((DateTime.UtcNow.AddMinutes(30) - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds); var payload = new Dictionary <string, object>() { { "id", userId }, { "password", password }, { "vendor", vendor }, { "iat", now }, { "exp", exp } }; const string secret = "GQDstcKsx0NHjPOuXOYg5MbeJ1XT0uFiwDVvVBrk"; IJwtAlgorithm algorithm = new HMACSHA256Algorithm(); IJsonSerializer serializer = new JsonNetSerializer(); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder); var token = encoder.Encode(payload, secretKey); return(token); }
public String GetToken() { var payload = new Dictionary <string, object> { { "userId", UserId }, { "userName", UserName }, { "exp", ConvertToUnixTimestamp(ExpiresAt) }, { "iat", ConvertToUnixTimestamp(IssuedAt) } }; foreach (var customClaim in CustomClaims) { payload.Add(customClaim.Key, customClaim.Value); } IJwtAlgorithm algorithm = new HMACSHA256Algorithm(); IJsonSerializer serializer = new JsonNetSerializer(); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder); var token = encoder.Encode(payload, this.SecretKey); return(token); }
public void DecodeToObject_Should_Throw_Exception_On_Expired_Claim() { const string key = TestData.Secret; const int timeDelta = -1; var dateTimeProvider = new UtcDateTimeProvider(); var serializer = new JsonNetSerializer(); var validator = new JwtValidator(serializer, dateTimeProvider); var urlEncoder = new JwtBase64UrlEncoder(); var decoder = new JwtDecoder(serializer, validator, urlEncoder, TestData.HMACSHA256Algorithm); var now = dateTimeProvider.GetNow(); var exp = UnixEpoch.GetSecondsSince(now.AddHours(timeDelta)); var encoder = new JwtEncoder(TestData.HMACSHA256Algorithm, serializer, urlEncoder); var token = encoder.Encode(new { exp }, key); Action action = () => decoder.DecodeToObject <Customer>(token, key, verify: true); action.Should() .Throw <TokenExpiredException>("because decoding an expired token should raise an exception when verified"); }