public static ClientAssertion CreateJwt(X509Certificate2 cert, string issuer, string aud) { ClientAssertionCertificate certificate = new ClientAssertionCertificate(issuer, cert); JsonWebToken jwtToken = new JsonWebToken(certificate, aud); return jwtToken.Sign(certificate); }
public bool Check(JsonWebToken token) { issuer = token.Claims.Get(KnownClaims.Issuer).Value; var trusted = _config.TrustedIssuers.FirstOrDefault(i => i.Name == issuer); if(null == trusted) { FailureMessage = issuer + " is not a trusted issuer"; return false; } if(null == token.Header) { if (_config.AllowUnsignedTokens) return true; FailureMessage = "No header was included in the token, unable to validate keys."; return false; } if(token.Header.Algorithm.IsHmac()) { return true; } var pattern = new Regex(trusted.KeyUriPattern); if(false == pattern.IsMatch(token.Header.KeyUri.ToString())) { FailureMessage = "The Uri " + token.Header.KeyUri + " is not trusted for the issuer " + issuer; return false; } return true; }
public static ClientAssertion CreateJwt(byte[] cert, string password, string issuer, string aud) { ClientAssertionCertificate certificate = new ClientAssertionCertificate(issuer, cert, password); JsonWebToken jwtToken = new JsonWebToken(certificate, aud); return jwtToken.Sign(certificate); }
public String GenerateWsJwt(JsonWebToken.Payload.WebserviceResponse response) { String header = UrlSafeBase64Encode(CreateSerializedHeader()); String body = UrlSafeBase64Encode(CreateWSPayload(response)); String content = header + "." + body; String signature = CreateSignature(content); return content + "." + signature; }
public bool Verify(JsonWebToken token) { var issuer = token.Claims.Get(KnownClaims.Issuer).Value; var verifier = GetAlgorithm(_algorithm, _keyProvider.GetConsumerKey(_algorithm, issuer)); var expectedHash = verifier.ComputeHash(token.Payload); return CompareSignatures(token.Signature, expectedHash); }
public void Verify_None_Algorithm_Serialization() { var token = new JsonWebToken { Issuer = "joe", ExpirationTime = 1300819380 }; token.AddClaim("http://example.com/is_root", true); var serializer = new JWSCompactSerializer(); var strToken = serializer.Serialize(token.ToJson()); var deserializedToken = serializer.Deserialize(strToken); Assert.AreEqual(token.ToJson(), deserializedToken.ToJson()); }
public void Should_Token_Not_Yet_Valid() { var token = new JsonWebToken { Issuer = "joe", NotBefore = DateTimeOffset.UtcNow.AddMinutes(5).ToUnixTimeSeconds() }; token.AddClaim("http://example.com/is_root", true); Assert.IsFalse(token.IsValid); var serializer = new JWSCompactSerializer(new HS256Algorithm("1To680X8yGFe8wEFu5Ye8bW735CF9j6D")); var deserializedToken = serializer.Deserialize(serializer.Serialize(token.ToJson())); Assert.IsFalse(deserializedToken.IsValid); }
public async Task Verify_HS256_Algorithm_Serialization() { var keySet = await JWKSet.GetAsync(this.keySetUri); var key = keySet["hs-256"]; var token = new JsonWebToken { Issuer = "joe", ExpirationTime = 1300819380 }; token.AddClaim("http://example.com/is_root", true); var serializer = new JWSCompactSerializer(new HS256Algorithm(key)); var strToken = serializer.Serialize(token.ToJson()); var deserializedToken = serializer.Deserialize(strToken); Assert.AreEqual(token.ToJson(), deserializedToken.ToJson()); }
public bool Check(JsonWebToken token) { var expiry = token.Claims.Get(KnownClaims.Expiry); if(expiry is NullClaim<UnixTimeStamp>) { FailureMessage = "The token did not contain a parseable expiry date."; return false; } if(expiry.Value.ToDateTime() < DateTime.UtcNow) { FailureMessage = "The expiry date '" + expiry.Value.ToDateTime() + "' (unix:" + expiry.Value.Value +") is in the past."; return false; } return true; }
public bool TryConsume(string tokenString, out JsonWebToken token) { JsonWebToken candidateToken; try { candidateToken = _reader.Read(tokenString); } catch (InvalidTokenFormatException e) { token = null; FailureReason = new TokenUnparseable { FailureMessage = e.Message }; return false; } catch(InvalidBase64StringFormatException e) { token = null; FailureReason = new TokenUnparseable {FailureMessage = e.Message}; return false; } catch(JsonException e) { token = null; FailureReason = new TokenUnparseable {FailureMessage = e.Message}; return false; } foreach(var rule in _rules) { if(false == rule.Check(candidateToken)) { FailureReason = rule; token = null; return false; } } token = candidateToken; return true; }
private static void StreamFile(HttpContext context) { var id = context.Request[FilesLinkUtility.FileId]; var auth = context.Request[FilesLinkUtility.AuthKey]; int version; int.TryParse(context.Request[FilesLinkUtility.Version] ?? "", out version); var validateResult = EmailValidationKeyProvider.ValidateEmailKey(id + version, auth ?? "", Global.StreamUrlExpire); if (validateResult != EmailValidationKeyProvider.ValidationResult.Ok) { var exc = new HttpException((int)HttpStatusCode.Forbidden, FilesCommonResource.ErrorMassage_SecurityException); Global.Logger.Error(string.Format("{0} {1}: {2}", FilesLinkUtility.AuthKey, validateResult, context.Request.Url), exc); context.Response.StatusCode = (int)HttpStatusCode.Forbidden; context.Response.Write(FilesCommonResource.ErrorMassage_SecurityException); return; } if (!string.IsNullOrEmpty(FileUtility.SignatureSecret)) { try { var header = context.Request.Headers[FileUtility.SignatureHeader]; if (string.IsNullOrEmpty(header) || !header.StartsWith("Bearer ")) { throw new Exception("header is null"); } header = header.Substring("Bearer ".Length); JsonWebToken.JsonSerializer = new DocumentService.JwtSerializer(); JsonWebToken.Decode(header, FileUtility.SignatureSecret); } catch (Exception ex) { Global.Logger.Error("Download stream header", ex); context.Response.StatusCode = (int)HttpStatusCode.Forbidden; context.Response.Write(FilesCommonResource.ErrorMassage_SecurityException); return; } } try { using (var fileDao = Global.DaoFactory.GetFileDao()) { fileDao.InvalidateCache(id); var file = version > 0 ? fileDao.GetFile(id, version) : fileDao.GetFile(id); using (var stream = fileDao.GetFileStream(file)) { context.Response.AddHeader("Content-Length", stream.CanSeek ? stream.Length.ToString(CultureInfo.InvariantCulture) : file.ContentLength.ToString(CultureInfo.InvariantCulture)); stream.StreamCopyTo(context.Response.OutputStream); } } } catch (Exception ex) { Global.Logger.Error("Error for: " + context.Request.Url, ex); context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; context.Response.Write(ex.Message); return; } try { context.Response.Flush(); context.Response.End(); } catch (HttpException) { } }
private static ClaimsPrincipal ValidateToken(string token, string secret, bool checkExpiration) { var jsonSerializer = new JavaScriptSerializer(); var payloadJson = JsonWebToken.Decode(token, secret); var payloadData = jsonSerializer.Deserialize <Dictionary <string, object> >(payloadJson); object exp; if (payloadData != null && (checkExpiration && payloadData.TryGetValue("exp", out exp))) { var validTo = FromUnixTime(long.Parse(exp.ToString())); if (DateTime.Compare(validTo, DateTime.UtcNow) <= 0) { throw new Exception( string.Format("Token is expired. Expiration: '{0}'. Current: '{1}'", validTo, DateTime.UtcNow)); } } var subject = new ClaimsIdentity("Federation", ClaimTypes.Name, ClaimTypes.Role); var claims = new List <Claim>(); if (payloadData != null) { foreach (var pair in payloadData) { var claimType = pair.Key; var source = pair.Value as ArrayList; if (source != null) { claims.AddRange(from object item in source select new Claim(claimType, item.ToString(), ClaimValueTypes.String)); continue; } switch (pair.Key) { case "name": claims.Add(new Claim(ClaimTypes.Name, pair.Value.ToString(), ClaimValueTypes.String)); break; case "surname": claims.Add(new Claim(ClaimTypes.Surname, pair.Value.ToString(), ClaimValueTypes.String)); break; case "email": claims.Add(new Claim(ClaimTypes.Email, pair.Value.ToString(), ClaimValueTypes.Email)); break; case "role": claims.Add(new Claim(ClaimTypes.Role, pair.Value.ToString(), ClaimValueTypes.String)); break; case "userId": claims.Add(new Claim(ClaimTypes.UserData, pair.Value.ToString(), ClaimValueTypes.Integer)); break; default: claims.Add(new Claim(claimType, pair.Value.ToString(), ClaimValueTypes.String)); break; } } } subject.AddClaims(claims); return(new ClaimsPrincipal(subject)); }
public object Authenticate(IDictionary <string, string> headers) { for (int i = 0; i < 8 && rsaSecurityKey == null; i++) { Thread.Sleep(1000); } if (headers.ContainsKey(HeaderName) == false) { throw new AuthenticationException("Authentication failed"); } var token = headers[HeaderName]; try { if (token.StartsWith("Bearer ")) { token = token.Substring(7); } JsonWebToken exampleJWT = new JsonWebToken(token); var jwtTokenHandler = new JwtSecurityTokenHandler(); var vaild = jwtTokenHandler.ValidateToken(token, new TokenValidationParameters { IssuerSigningKey = rsaSecurityKey, RequireExpirationTime = false, RequireSignedTokens = true, ValidateAudience = false, ValidateIssuer = false, ValidateLifetime = true, }, out SecurityToken validatedSecurityToken); var ret = vaild; if (Callback != null) { AuthenticationParameter authParameter = new AuthenticationParameter(token); authParameter.Content = ret; if (!Callback(authParameter)) { _logger?.LogDebug("身份验证回调处理不通过"); throw new AuthenticationException("Authentication failed"); } return(authParameter.Content); } return(ret); } catch (AuthenticationException ex) { _logger?.LogDebug("身份验证发生异常:{0}", ex.Message); if (Callback != null) { AuthenticationParameter authParameter = new AuthenticationParameter(token); if (Callback(authParameter)) { return(authParameter.Content); } } throw ex; } catch (Exception ex) { _logger?.LogDebug("身份验证发生异常:{0}", ex.Message); if (Callback != null) { AuthenticationParameter authParameter = new AuthenticationParameter(token); if (Callback(authParameter)) { return(authParameter.Content); } } throw new AuthenticationException("Authentication failed"); } }
/// <summary> /// 使用RefreshToken获取新的JwtToken信息 /// </summary> /// <param name="refreshToken">刷新Token字符串</param> /// <returns>JwtToken信息</returns> public virtual async Task <JsonWebToken> RefreshToken(string refreshToken) { Check.NotNull(refreshToken, nameof(refreshToken)); TokenValidationParameters parameters = new TokenValidationParameters() { ValidIssuer = _jwtOptions.Issuer ?? "osharp identity", ValidAudience = _jwtOptions.Audience ?? "osharp client", IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtOptions.Secret)) }; JwtSecurityToken jwtSecurityToken = _tokenHandler.ReadJwtToken(refreshToken); string clientId = jwtSecurityToken.Claims.FirstOrDefault(m => m.Type == "clientId")?.Value; if (clientId == null) { throw new OsharpException("RefreshToken 中不包含 ClientId 声明"); } string userId = jwtSecurityToken.Claims.FirstOrDefault(m => m.Type == "nameid")?.Value; if (userId == null) { throw new OsharpException("RefreshToken 的数据中无法找到 UserId 声明"); } RequestClientType?clientType = jwtSecurityToken.Claims.FirstOrDefault(m => m.Type == "clientType")?.Value.CastTo <RequestClientType>() ?? RequestClientType.Browser; UserManager <TUser> userManager = _provider.GetService <UserManager <TUser> >(); RefreshToken existRefreshToken = await userManager.GetRefreshToken(userId, clientId); if (existRefreshToken == null || existRefreshToken.Value != refreshToken || existRefreshToken.EndUtcTime <= DateTime.UtcNow) { if (existRefreshToken != null && existRefreshToken.EndUtcTime <= DateTime.UtcNow) { //删除过期的Token IUnitOfWork unitOfWork = _provider.GetUnitOfWork(true); userManager = _provider.GetRequiredService <UserManager <TUser> >(); var result = await userManager.RemoveRefreshToken(userId, clientId); if (result.Succeeded) { #if NET5_0_OR_GREATER await unitOfWork.CommitAsync(); #else unitOfWork.Commit(); #endif } } throw new OsharpException("RefreshToken 不存在或已过期"); } ClaimsPrincipal principal = _tokenHandler.ValidateToken(refreshToken, parameters, out _); string userName = principal.Claims.FirstOrDefault(m => m.Type == ClaimTypes.Name)?.Value; if (userName == null) { throw new OsharpException("RefreshToken 的数据中无法找到 UserName 声明"); } JsonWebToken token = await CreateToken(userId, userName, clientType.Value, existRefreshToken); return(token); }
public void GetPayloadValues() { var context = new CompareContext(); TestUtilities.WriteHeader($"{this}.GetPayloadValues"); var token = new JsonWebToken("{}", jObject); var intarray = token.GetPayloadValue <int[]>("intarray"); IdentityComparer.AreEqual(new int[] { 1, 2, 3 }, intarray, context); var array = token.GetPayloadValue <object[]>("array"); IdentityComparer.AreEqual(new object[] { 1L, "2", 3L }, array, context); // only possible internally within the library since we're using Microsoft.IdentityModel.Json.Linq.JObject var jobject = token.GetPayloadValue <JObject>("jobject"); IdentityComparer.AreEqual(JObject.Parse(@"{ ""string1"":""string1value"", ""string2"":""string2value"" }"), jobject, context); var name = token.GetPayloadValue <string>("string"); IdentityComparer.AreEqual("bob", name, context); var floatingPoint = token.GetPayloadValue <float>("float"); IdentityComparer.AreEqual(42.0, floatingPoint, context); var integer = token.GetPayloadValue <int>("integer"); IdentityComparer.AreEqual(42, integer, context); var nill = token.GetPayloadValue <object>("nill"); IdentityComparer.AreEqual(nill, null, context); var boolean = token.GetPayloadValue <bool>("bool"); IdentityComparer.AreEqual(boolean, true, context); var dateTimeValue = token.GetPayloadValue <string>("dateTime"); IdentityComparer.AreEqual(dateTimeValue, dateTime.ToString(), context); var dateTimeIso8061Value = token.GetPayloadValue <DateTime>("dateTimeIso8061"); IdentityComparer.AreEqual(dateTimeIso8061Value, dateTime, context); try // Try to retrieve a value that doesn't exist in the header. { token.GetPayloadValue <int>("doesnotexist"); } catch (Exception ex) { ExpectedException.ArgumentException("IDX14304:").ProcessException(ex, context); } try // Try to retrieve an integer when the value is actually a string. { token.GetPayloadValue <int>("string"); } catch (Exception ex) { ExpectedException.ArgumentException("IDX14305:", typeof(System.FormatException)).ProcessException(ex, context); } TestUtilities.AssertFailIfErrors(context); }
/// <summary> /// Encode before web api return json result /// </summary> /// <param name="objectResult">Any Object need to encode</param> /// <returns>return string json</returns> public static string Encode(Object objectResult) { return(JsonWebToken.Encode(objectResult, Constant.SecretKey, JwtHashAlgorithm.HS256)); }
public Result(bool succeeded, JsonWebToken token = null) { Succeeded = succeeded; Token = token; }
public DecodeTests() { defaultSerializer = new JsonWebToken(SerializerType.DefaultSerializer); newtonsoftSerializer = new JsonWebToken(SerializerType.NewtonsoftJsonSerializer); serviceStackSerializer = new JsonWebToken(SerializerType.ServiceStackJsonSerializer); }
public static Result ReturnToken(JsonWebToken Tokens) { return(new Result(true, new string[] { }, null, Tokens)); }
private string BuildToken(Dictionary <string, object> headers, Dictionary <string, object> payload) { return(JsonWebToken.Encode(headers, payload, _secret, Algorithm)); }
public string GenerateJwt(AuthenticatedModel authenticated) { var roles = authenticated.Roles.Select(role => role.ToString()).ToArray(); return(JsonWebToken.Encode(authenticated.UserId.ToString(), roles)); }
public void ManualWriteRoundtripDuplicateClaimTypes() { var signinKey = SymmetricKeyGenerator.Create(32); var jwt = new JsonWebToken { Header = new JwtHeader { SignatureAlgorithm = JwtConstants.SignatureAlgorithms.HMACSHA256, SigningCredentials = new HmacSigningCredentials(signinKey) }, Audience = new Uri("http://foo.com"), Issuer = "dominick", ExpirationTime = 50000000000, }; jwt.AddClaim(ClaimTypes.Name, "dominick"); jwt.AddClaim(ClaimTypes.Email, "*****@*****.**"); jwt.AddClaim(ClaimTypes.Role, "bar"); jwt.AddClaim(ClaimTypes.Role, "foo"); var handler = new JsonWebTokenHandler(); var token = handler.WriteToken(jwt); Trace.WriteLine(token); // token should not be empty Assert.IsTrue(!string.IsNullOrWhiteSpace(token)); // token with signature needs to be 3 parts var parts = token.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(token); 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 identity = handler.ValidateToken(jwtToken).First(); Assert.IsTrue(identity.Claims.Count() == 4); Assert.IsTrue(identity.Claims.First().Issuer == "dominick"); }
/// <summary> /// Parses a JWT string encoded. /// </summary> /// <param name="jwt">The string encoded.</param> /// <param name="algorithm">The signature algorithm.</param> /// <param name="verify">true if verify the signature; otherwise, false.</param> /// <returns>A JSON web token object.</returns> /// <exception cref="ArgumentNullException">jwt was null or empty. -or- algorithm was null and verify is true.</exception> /// <exception cref="ArgumentException">jwt did not contain any information.</exception> /// <exception cref="FormatException">jwt was in incorrect format.</exception> /// <exception cref="InvalidOperationException">Verify failure.</exception> public static JsonWebToken <T> Parse(string jwt, ISignatureProvider algorithm, bool verify = true) { if (string.IsNullOrWhiteSpace(jwt)) { throw new ArgumentNullException(nameof(jwt), "jwt should not be null or empty."); } var prefix = $"{TokenInfo.BearerTokenType} "; if (jwt.IndexOf(prefix) == 0) { if (jwt.Length == prefix.Length) { throw new ArgumentException("jwt should not contain a scheme only.", nameof(jwt)); } jwt = jwt.Substring(prefix.Length); } var arr = jwt.Split('.'); if (arr.Length < 3) { throw new FormatException("jwt is not in the correct format."); } if (verify) { var bytes = Encoding.ASCII.GetBytes($"{arr[0]}.{arr[1]}"); var sign = WebFormat.Base64UrlDecode(arr[2]); if (algorithm != null) { if (!algorithm.Verify(bytes, sign)) { throw new InvalidOperationException("jwt signature is incorrect."); } } else { if (sign.Length > 0) { throw new ArgumentNullException(nameof(algorithm), "algorithm should not be null."); } } } var header = WebFormat.Base64UrlDecodeTo <JsonWebTokenHeader>(arr[0]); if (header == null) { throw new ArgumentException("jwt should contain header in Base64Url.", nameof(jwt)); } var payload = WebFormat.Base64UrlDecodeTo <T>(arr[1]); if (payload == null) { throw new ArgumentException("jwt should contain payload in Base64Url.", nameof(jwt)); } var obj = new JsonWebToken <T>(payload, algorithm) { headerBase64Url = arr[0], signatureCache = arr[2] }; obj.header.Type = header.Type; obj.header.AlgorithmName = header.AlgorithmName; return(obj); }
public void AddToParameters(IDictionary<string, string> parameters) { if (this.ClientId != null) { parameters[OAuthParameter.ClientId] = this.ClientId; } if (this.Credential != null) { parameters[OAuthParameter.ClientSecret] = this.Credential.ClientSecret; } else if (this.Assertion != null) { parameters[OAuthParameter.ClientAssertionType] = this.Assertion.AssertionType; parameters[OAuthParameter.ClientAssertion] = this.Assertion.Assertion; } else if (this.Certificate != null) { JsonWebToken jwtToken = new JsonWebToken(this.Certificate, this.Authenticator.SelfSignedJwtAudience); ClientAssertion clientAssertion = jwtToken.Sign(this.Certificate); parameters[OAuthParameter.ClientAssertionType] = clientAssertion.AssertionType; parameters[OAuthParameter.ClientAssertion] = clientAssertion.Assertion; } }
public void Initialize(IPipelines pipelines) { StatelessAuthentication.Enable(pipelines, new StatelessAuthenticationConfiguration(ctx => { if (ctx.Request.Method == "OPTIONS") { return(null); } var manterUsuario = new ManterUsuario(); var manterUsuarioTrilha = new ManterUsuarioTrilha(); var manterTrilhaNivel = new ManterTrilhaNivel(); var manterFornecedor = new ManterFornecedor(); try { var jwtToken = ctx.Request.Headers.Authorization; if (string.IsNullOrEmpty(jwtToken)) { return(null); } var payload = JsonWebToken.DecodeToObject(jwtToken, "", false) as IDictionary <string, object>; if (payload != null) { var usuario = manterUsuario.ObterTodosIQueryable().Where(x => x.ID == (int)payload["id"]) .Select(x => new Usuario { ID = x.ID, Nome = x.Nome, CPF = x.CPF, TrilhaTokenExpiry = x.TrilhaTokenExpiry, TrilhaToken = x.TrilhaToken, Senha = x.Senha }) .FirstOrDefault(); if (usuario != null && usuario.TrilhaTokenExpiry > DateTime.Now) { JsonWebToken.Decode(jwtToken, usuario.TrilhaToken); TrilhaNivel nivel = manterTrilhaNivel.ObterTrilhaNivelPorID((int)payload["nid"]); UsuarioTrilha matricula = null; if (payload.ContainsKey("experimenta") && !payload["experimenta"].Equals("experimente")) { if (!nivel.UsuarioPossuiMatricula((int)payload["id"])) { return(null); } matricula = manterUsuarioTrilha.ObterPorUsuarioNivel(usuario.ID, nivel.ID); if (matricula == null) { return(null); } } else { matricula = new UsuarioTrilha { ID = 0, TrilhaNivel = nivel, StatusMatricula = Dominio.Enumeracao.enumStatusMatricula.Inscrito }; } manterUsuario.AdicionarTempoTokenTrilha(usuario); return(new UserIdentity { UserName = usuario.CPF, Usuario = usuario, Matricula = matricula, Nivel = nivel, Payload = payload, JwtToken = jwtToken }); } // Se chegou até aqui, verifica se o acesso é de fornecedor. // Trazer os fornecedores apenas com os campos que interessam. var fornecedores = manterFornecedor.ObterTodosIQueryable().Select(x => new Fornecedor { ID = x.ID, Nome = x.Nome, TextoCriptografia = x.TextoCriptografia }).ToList(); // Tentar decodificar o JWT para verificar se o acesso é de fornecedor. foreach (var fornecedor in fornecedores) { try { JsonWebToken.Decode(jwtToken, fornecedor.TextoCriptografia); return(new UserIdentity() { UserName = fornecedor.Nome, Fornecedor = fornecedor, Payload = payload }); } catch { // Ignored. } } } return(null); } catch (Exception ex) { return(null); } finally { manterUsuario.Dispose(); manterUsuarioTrilha.Dispose(); manterTrilhaNivel.Dispose(); manterFornecedor.Dispose();; } })); }
/// <summary>Converts the Json Web Token to a list of <see cref="Claim"/>.</summary> /// <param name="jwt">The token to act on.</param> /// <returns>The claims.</returns> public static IEnumerable <Claim> ToClaims(this JsonWebToken jwt) { return(jwt.Payload.Select(x => new Claim(x.Key, x.Value.ToString()))); }
public AuthModule() : base("Auth") { Get["/"] = p => { return("Token Valid!"); }; Post["Login"] = p => { var dadosAcesso = this.Bind <DTODadosAcesso>(); var usuario = new ManterUsuario().ObterTodosIQueryable().Where(x => x.CPF == dadosAcesso.Login) .Select(x => new Usuario { ID = x.ID, Senha = x.Senha }) .FirstOrDefault(); if (usuario == null) { return("Usuário não existe."); } if (usuario.Senha != dadosAcesso.Senha) { return("Senha inválida."); } var nivel = manterTrilhaNivel.ObterTrilhaNivelPorID(dadosAcesso.NivelID); if (nivel == null || !nivel.UsuarioPossuiMatricula(usuario.ID)) { return(null); } return (Response.AsJson(JsonWebToken.Encode(new { id = usuario.ID, nid = nivel.ID }, manterUsuario.GerarTokenTrilha(usuario), JwtHashAlgorithm.HS256))); }; Post["LoginFornecedor"] = p => { var dadosAcesso = this.Bind <DTODadosAcesso>(); var usuario = manterUsuario.ObterPorCPF(dadosAcesso.Login); if (usuario == null) { return("Usuário não existe."); } if (usuario.Senha != dadosAcesso.Senha) { return("Senha inválida."); } var nivel = manterTrilhaNivel.ObterTrilhaNivelPorID(dadosAcesso.NivelID); if (!nivel.UsuarioPossuiMatricula(usuario.ID)) { return(null); } var manterFornecedor = new ManterFornecedor(); var fornecedor = manterFornecedor.ObterFornecedorPorID(25); if (fornecedor == null) { return("Fornecedor não existe."); } return(Response.AsJson(JsonWebToken.Encode(new { id = usuario.ID, fase = 1, itrid = 1, nid = nivel.ID }, fornecedor.TextoCriptografia, JwtHashAlgorithm.HS256), HttpStatusCode.OK)); }; }
/// <summary> /// Decode before get data from api /// </summary> /// <param name="sResult">string object parameter</param> /// <returns>return Json Object</returns> public static JObject Decode(string sResult) { return(JObject.Parse(JsonWebToken.Decode(sResult, Constant.SecretKey, true))); }
public async Task <Result> RefreshTokenAsync(JsonWebToken model) { var validatedToken = _jwtHandler.ValidateToken(model.Token); if (validatedToken == null) { return(Result.GeneralFailure("Invalid Token")); } if (validatedToken.ValidTo > DateTime.UtcNow) { return(Result.GeneralFailure("This Token Has Not Expired Yet")); } var userId = validatedToken.Claims.First(claim => claim.Type == TokenClaims.UserId).Value; var userRefreshToken = await _context.RefreshTokens.Where(x => x.Token == model.RefreshToken) .Include(c => c.Users) .Where(v => v.Users.Id == userId) .FirstOrDefaultAsync(); if (userRefreshToken == null) { return(Result.GeneralFailure("No refresh token for this user")); } if (userRefreshToken.Token != model.RefreshToken) { return(Result.GeneralFailure("Invalid Refresh Token")); } if (userRefreshToken.IsExpired) { return(Result.GeneralFailure("Expired Token")); } if (userRefreshToken.Revoked != null) { return(Result.GeneralFailure("This Token has Been Used and Revoked")); } if (userRefreshToken.IsActive) { var userRole = await _userManager.GetRolesAsync(userRefreshToken.Users); var newRefreshToken = _jwtHandler.CreateRefreshToken(userId); var token = _jwtHandler.CreateToken(userRefreshToken.Users, userRole.FirstOrDefault()); var jwt = new JsonWebToken { Token = token, RefreshToken = newRefreshToken.Token, }; userRefreshToken.Revoked = DateTime.UtcNow; var updateResult = _context.RefreshTokens.Update(userRefreshToken); var addNewRefreshToken = await _context.RefreshTokens.AddAsync(newRefreshToken); var saveChanges = await _context.SaveChangesAsync(); if (updateResult.IsKeySet || addNewRefreshToken.IsKeySet || saveChanges == 1) { return(Result.ReturnToken(jwt)); } } return(Result.GeneralFailure("SomeThing Wrong")); }
public void TryGetPayloadValues() { var context = new CompareContext(); TestUtilities.WriteHeader($"{this}.TryGetPayloadValues"); var token = new JsonWebToken("{}", jObject); var success = token.TryGetPayloadValue("intarray", out int[] intarray); IdentityComparer.AreEqual(new int[] { 1, 2, 3 }, intarray, context); IdentityComparer.AreEqual(true, success, context); success = token.TryGetPayloadValue("array", out object[] array); IdentityComparer.AreEqual(new object[] { 1L, "2", 3L }, array, context); IdentityComparer.AreEqual(true, success, context); // only possible internally within the library since we're using Microsoft.IdentityModel.Json.Linq.JObject success = token.TryGetPayloadValue("jobject", out JObject jobject); IdentityComparer.AreEqual(JObject.Parse(@"{ ""string1"":""string1value"", ""string2"":""string2value"" }"), jobject, context); IdentityComparer.AreEqual(true, success, context); success = token.TryGetPayloadValue("string", out string name); IdentityComparer.AreEqual("bob", name, context); IdentityComparer.AreEqual(true, success, context); success = token.TryGetPayloadValue("float", out float floatingPoint); IdentityComparer.AreEqual(42.0, floatingPoint, context); IdentityComparer.AreEqual(true, success, context); success = token.TryGetPayloadValue("integer", out int integer); IdentityComparer.AreEqual(42, integer, context); IdentityComparer.AreEqual(true, success, context); success = token.TryGetPayloadValue("nill", out object nill); IdentityComparer.AreEqual(nill, null, context); IdentityComparer.AreEqual(true, success, context); success = token.TryGetPayloadValue("bool", out bool boolean); IdentityComparer.AreEqual(boolean, true, context); IdentityComparer.AreEqual(true, success, context); var dateTimeValue = token.GetPayloadValue <string>("dateTime"); IdentityComparer.AreEqual(dateTimeValue, dateTime.ToString(), context); IdentityComparer.AreEqual(true, success, context); var dateTimeIso8061Value = token.GetPayloadValue <DateTime>("dateTimeIso8061"); IdentityComparer.AreEqual(dateTimeIso8061Value, dateTime, context); IdentityComparer.AreEqual(true, success, context); success = token.TryGetPayloadValue("doesnotexist", out int doesNotExist); IdentityComparer.AreEqual(0, doesNotExist, context); IdentityComparer.AreEqual(false, success, context); success = token.TryGetPayloadValue("string", out int cannotConvert); IdentityComparer.AreEqual(0, cannotConvert, context); IdentityComparer.AreEqual(false, success, context); TestUtilities.AssertFailIfErrors(context); }
public static string GenerateJwt() { long tiemStamp = DateTimeHelper.ConvertToTimeStamp(DateTime.Now.AddDays(1)); return(JsonWebToken.Encode(new { applicationId = ApplicationId, issAt = tiemStamp }, SecretKey, JwtHashAlgorithm.HS256)); }
/// <summary> /// Processes the JWT contents /// </summary> /// <param name="context"></param> /// <param name="token">The JWT token</param> /// <returns></returns> protected virtual Task <List <Claim> > ProcessPayloadAsync(JwtRequestValidationContext context, JsonWebToken token) { // filter JWT validation values var filter = Constants.Filters.JwtRequestClaimTypesFilter.ToList(); if (context.IncludeJti) { // don't filter out the jti claim filter.Remove(JwtClaimTypes.JwtId); } var filtered = token.Claims.Where(claim => !filter.Contains(claim.Type)); return(Task.FromResult(filtered.ToList())); }
public CustomerClaimsPrincipal(ClaimsIdentityCollection identityCollection, JsonWebToken token, string encryptedToken) : base(identityCollection, token, encryptedToken) { }
public static string Encrypt <T>(T item) { return(JsonWebToken.Encode(item, SecretKey, JwtHashAlgorithm)); }
private void AddClientKey(ClientKey clientKey) { if (clientKey.ClientId != null) { this[OAuthParameter.ClientId] = clientKey.ClientId; } if (clientKey.Credential != null) { if (clientKey.Credential.ClientSecret != null) { this[OAuthParameter.ClientSecret] = clientKey.Credential.ClientSecret; } else { this.AddSecureParameter(OAuthParameter.ClientSecret, clientKey.Credential.SecureClientSecret); } } else if (clientKey.Assertion != null) { this[OAuthParameter.ClientAssertionType] = clientKey.Assertion.AssertionType; this[OAuthParameter.ClientAssertion] = clientKey.Assertion.Assertion; } else if (clientKey.Certificate != null) { JsonWebToken jwtToken = new JsonWebToken(clientKey.Certificate, clientKey.Authenticator.SelfSignedJwtAudience); ClientAssertion clientAssertion = jwtToken.Sign(clientKey.Certificate); this[OAuthParameter.ClientAssertionType] = clientAssertion.AssertionType; this[OAuthParameter.ClientAssertion] = clientAssertion.Assertion; } }
private string CreateWSPayload(JsonWebToken.Payload.WebserviceResponse response) { var iat = (int)(System.DateTime.UtcNow - new System.DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds; var jwtContainer = new JsonWebToken.Payload() { Issuer = issuer, Audience = "google", Type = "loyaltywebservice", IssuedAtTimeSeconds = iat, Objects = new JsonWebToken.Payload.Content() { loyaltyObjects = loyaltyObjects, offerObjects = offerObjects, webserviceResponse = response }, }; return NewtonsoftJsonSerializer.Instance.Serialize(jwtContainer); }
private static void EmptyFile(HttpContext context) { try { var fileName = context.Request[FilesLinkUtility.FileTitle]; if (!string.IsNullOrEmpty(FileUtility.SignatureSecret)) { try { var header = context.Request.Headers[FileUtility.SignatureHeader]; if (string.IsNullOrEmpty(header) || !header.StartsWith("Bearer ")) { throw new Exception("Invalid header " + header); } header = header.Substring("Bearer ".Length); JsonWebToken.JsonSerializer = new DocumentService.JwtSerializer(); var stringPayload = JsonWebToken.Decode(header, FileUtility.SignatureSecret); Global.Logger.Debug("DocService EmptyFile payload: " + stringPayload); //var data = JObject.Parse(stringPayload); //if (data == null) //{ // throw new ArgumentException("DocService EmptyFile header is incorrect"); //} //var signedStringUrl = data["url"] ?? (data["payload"] != null ? data["payload"]["url"] : null); //if (signedStringUrl == null) //{ // throw new ArgumentException("DocService EmptyFile header url is incorrect"); //} //var signedUrl = new Uri(signedStringUrl.ToString()); //var signedQuery = signedUrl.Query; //if (!context.Request.Url.Query.Equals(signedQuery)) //{ // throw new SecurityException(string.Format("DocService EmptyFile header id not equals: {0} and {1}", context.Request.Url.Query, signedQuery)); //} } catch (Exception ex) { Global.Logger.Error("Download stream header " + context.Request.Url, ex); context.Response.StatusCode = (int)HttpStatusCode.Forbidden; context.Response.Write(FilesCommonResource.ErrorMassage_SecurityException); return; } } var toExtension = FileUtility.GetFileExtension(fileName); var fileExtension = FileUtility.GetInternalExtension(toExtension); fileName = "new" + fileExtension; var path = FileConstant.NewDocPath + (CoreContext.Configuration.CustomMode ? "ru-RU/" : "default/") + fileName; var storeTemplate = Global.GetStoreTemplate(); if (!storeTemplate.IsFile("", path)) { context.Response.StatusCode = (int)HttpStatusCode.NotFound; context.Response.Write(FilesCommonResource.ErrorMassage_FileNotFound); return; } context.Response.AddHeader("Content-Disposition", ContentDispositionUtil.GetHeaderValue(fileName)); context.Response.ContentType = MimeMapping.GetMimeMapping(fileName); using (var stream = storeTemplate.GetReadStream("", path)) { context.Response.AddHeader("Content-Length", stream.CanSeek ? stream.Length.ToString(CultureInfo.InvariantCulture) : storeTemplate.GetFileSize("", path).ToString(CultureInfo.InvariantCulture)); stream.StreamCopyTo(context.Response.OutputStream); } } catch (Exception ex) { Global.Logger.Error("Error for: " + context.Request.Url, ex); context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; context.Response.Write(ex.Message); return; } try { context.Response.Flush(); context.Response.SuppressContent = true; context.ApplicationInstance.CompleteRequest(); } catch (HttpException he) { Global.Logger.ErrorFormat("EmptyFile", he); } }
public bool Check(JsonWebToken token) { return _cryptoBuilder.GetSignatureVerification(token.Header).Verify(token); }
public async Task <JsonWebToken> UserLogin(string username, string password, string token_noticiation) { var jwt = new JsonWebToken(); jwt.message = new messageModel(); using (var context = new StandardcanContext()) { try { var passEncrypt = Cipher.Encrypt(password, secrectKey); var empDetail = context.EmpProfile.SingleOrDefault(a => a.EmpUserName.ToUpper() == username.ToUpper()); if (empDetail != null) { jwt.Pass_isdefault = empDetail.EmpPassIsdefault.ToString(); } if (empDetail == null) { jwt.message.status = "3"; throw new Exception("The username or password is incorrect"); } else if (empDetail.EmpPassword != passEncrypt) { throw new Exception("The username or password is incorrect"); } var countBoss = context.EmpProfile.Where(a => a.EmpBossId == empDetail.EmpId).ToList().Count(); if (empDetail != null) { if (countBoss > 0) { jwt.Permission = "2"; } else { jwt.Permission = "1"; } var token = CreateToken(empDetail.EmpId.ToString(), jwt.Permission); try { SqlParameter emp_id = new SqlParameter("emp_id", empDetail.EmpId.ToString() ?? ""); SqlParameter mobile_token = new SqlParameter("mobile_token", token_noticiation ?? ""); await context.Database.ExecuteSqlCommandAsync("sp_mb_update_mobile_token @emp_id, @mobile_token", emp_id, mobile_token); } catch (Exception ex) { throw new Exception("Token Noticiation is Error"); } jwt.message.status = "1"; jwt.message.msg = "Success"; jwt.Token_login = token; } else { throw new Exception("The username or password is incorrect"); } } catch (Exception ex) { jwt.message.status = !String.IsNullOrEmpty(jwt.message.status) ? jwt.message.status : "2"; jwt.message.msg = ex.Message; } } return(jwt); }
public override LoginProfile GetLoginProfile(string accessToken) { var tokenPayloadString = JsonWebToken.Decode(accessToken, string.Empty, false); var tokenPayload = JObject.Parse(tokenPayloadString); if (tokenPayload == null) { throw new Exception("Payload is incorrect"); } var oid = tokenPayload.Value <string>("urn:esia:sbj_id"); var userInfoString = RequestHelper.PerformRequest(GosUslugiProfileUrl + oid, "application/x-www-form-urlencoded", headers: new Dictionary <string, string> { { "Authorization", "Bearer " + accessToken } }); var userInfo = JObject.Parse(userInfoString); if (userInfo == null) { throw new Exception("userinfo is incorrect"); } var profile = new LoginProfile { Id = oid, FirstName = userInfo.Value <string>("firstName"), LastName = userInfo.Value <string>("lastName"), Provider = ProviderConstants.GosUslugi, }; var userContactsString = RequestHelper.PerformRequest(GosUslugiProfileUrl + oid + "/ctts", "application/x-www-form-urlencoded", headers: new Dictionary <string, string> { { "Authorization", "Bearer " + accessToken } }); var userContacts = JObject.Parse(userContactsString); if (userContacts == null) { throw new Exception("usercontacts is incorrect"); } var contactElements = userContacts.Value <JArray>("elements"); if (contactElements == null) { throw new Exception("usercontacts elements is incorrect"); } foreach (var contactElement in contactElements.ToObject <List <string> >()) { var userContactString = RequestHelper.PerformRequest(contactElement, "application/x-www-form-urlencoded", headers: new Dictionary <string, string> { { "Authorization", "Bearer " + accessToken } }); var userContact = JObject.Parse(userContactString); if (userContact == null) { throw new Exception("usercontacts is incorrect"); } var type = userContact.Value <string>("type"); if (type != "EML") { continue; } profile.EMail = userContact.Value <string>("value"); break; } return(profile); }
/// <summary>A JsonWebToken extension method that converts a jwt to an identity.</summary> /// <param name="jwt">The token to act on.</param> /// <returns>jwt as an ISentinelIdentity.</returns> public static ISentinelIdentity ToIdentity(this JsonWebToken jwt) { return(new SentinelIdentity("", jwt)); }
private static void TrackFile(HttpContext context) { var auth = context.Request[FilesLinkUtility.AuthKey]; var fileId = context.Request[FilesLinkUtility.FileId]; Global.Logger.Debug("DocService track fileid: " + fileId); var callbackSpan = TimeSpan.FromDays(128); var validateResult = EmailValidationKeyProvider.ValidateEmailKey(fileId, auth ?? "", callbackSpan); if (validateResult != EmailValidationKeyProvider.ValidationResult.Ok) { Global.Logger.ErrorFormat("DocService track auth error: {0}, {1}: {2}", validateResult.ToString(), FilesLinkUtility.AuthKey, auth); throw new HttpException((int)HttpStatusCode.Forbidden, FilesCommonResource.ErrorMassage_SecurityException); } DocumentServiceTracker.TrackerData fileData; try { string body; using (var receiveStream = context.Request.InputStream) using (var readStream = new StreamReader(receiveStream)) { body = readStream.ReadToEnd(); } Global.Logger.Debug("DocService track body: " + body); if (string.IsNullOrEmpty(body)) { throw new ArgumentException("DocService request body is incorrect"); } var data = JToken.Parse(body); if (data == null) { throw new ArgumentException("DocService request is incorrect"); } fileData = data.ToObject <DocumentServiceTracker.TrackerData>(); } catch (Exception e) { Global.Logger.Error("DocService track error read body", e); throw new HttpException((int)HttpStatusCode.BadRequest, e.Message); } if (!string.IsNullOrEmpty(FileUtility.SignatureSecret)) { JsonWebToken.JsonSerializer = new DocumentService.JwtSerializer(); if (!string.IsNullOrEmpty(fileData.Token)) { try { var dataString = JsonWebToken.Decode(fileData.Token, FileUtility.SignatureSecret); var data = JObject.Parse(dataString); if (data == null) { throw new ArgumentException("DocService request token is incorrect"); } fileData = data.ToObject <DocumentServiceTracker.TrackerData>(); } catch (SignatureVerificationException ex) { Global.Logger.Error("DocService track header", ex); throw new HttpException((int)HttpStatusCode.Forbidden, ex.Message); } } else { //todo: remove old scheme var header = context.Request.Headers[FileUtility.SignatureHeader]; if (string.IsNullOrEmpty(header) || !header.StartsWith("Bearer ")) { Global.Logger.Error("DocService track header is null"); throw new HttpException((int)HttpStatusCode.Forbidden, FilesCommonResource.ErrorMassage_SecurityException); } header = header.Substring("Bearer ".Length); try { var stringPayload = JsonWebToken.Decode(header, FileUtility.SignatureSecret); Global.Logger.Debug("DocService track payload: " + stringPayload); var jsonPayload = JObject.Parse(stringPayload); var data = jsonPayload["payload"]; if (data == null) { throw new ArgumentException("DocService request header is incorrect"); } fileData = data.ToObject <DocumentServiceTracker.TrackerData>(); } catch (SignatureVerificationException ex) { Global.Logger.Error("DocService track header", ex); throw new HttpException((int)HttpStatusCode.Forbidden, ex.Message); } } } DocumentServiceTracker.TrackResponse result; try { result = DocumentServiceTracker.ProcessData(fileId, fileData); } catch (Exception e) { Global.Logger.Error("DocService track:", e); throw new HttpException((int)HttpStatusCode.BadRequest, e.Message); } result = result ?? new DocumentServiceTracker.TrackResponse(); context.Response.Write(DocumentServiceTracker.TrackResponse.Serialize(result)); }
public void Should_Encode_Type() { string result = JsonWebToken.Encode(_customer, "ABC", JwtHashAlgorithm.HS256); Assert.AreEqual(_token, result); }
private static void StreamFile(HttpContext context) { try { using (var fileDao = Global.DaoFactory.GetFileDao()) { var id = context.Request[FilesLinkUtility.FileId]; int version; if (!int.TryParse(context.Request[FilesLinkUtility.Version] ?? "", out version)) { version = 0; } var doc = context.Request[FilesLinkUtility.DocShareKey]; fileDao.InvalidateCache(id); File file; var linkRight = FileShareLink.Check(doc, fileDao, out file); if (linkRight == FileShare.Restrict && !SecurityContext.IsAuthenticated) { var auth = context.Request[FilesLinkUtility.AuthKey]; var validateResult = EmailValidationKeyProvider.ValidateEmailKey(id + version, auth ?? "", Global.StreamUrlExpire); if (validateResult != EmailValidationKeyProvider.ValidationResult.Ok) { var exc = new HttpException((int)HttpStatusCode.Forbidden, FilesCommonResource.ErrorMassage_SecurityException); Global.Logger.Error(string.Format("{0} {1}: {2}", FilesLinkUtility.AuthKey, validateResult, context.Request.Url), exc); context.Response.StatusCode = (int)HttpStatusCode.Forbidden; context.Response.Write(FilesCommonResource.ErrorMassage_SecurityException); return; } if (!string.IsNullOrEmpty(FileUtility.SignatureSecret)) { try { var header = context.Request.Headers[FileUtility.SignatureHeader]; if (string.IsNullOrEmpty(header) || !header.StartsWith("Bearer ")) { throw new Exception("Invalid header " + header); } header = header.Substring("Bearer ".Length); JsonWebToken.JsonSerializer = new DocumentService.JwtSerializer(); var stringPayload = JsonWebToken.Decode(header, FileUtility.SignatureSecret); Global.Logger.Debug("DocService StreamFile payload: " + stringPayload); //var data = JObject.Parse(stringPayload); //if (data == null) //{ // throw new ArgumentException("DocService StreamFile header is incorrect"); //} //var signedStringUrl = data["url"] ?? (data["payload"] != null ? data["payload"]["url"] : null); //if (signedStringUrl == null) //{ // throw new ArgumentException("DocService StreamFile header url is incorrect"); //} //var signedUrl = new Uri(signedStringUrl.ToString()); //var signedQuery = signedUrl.Query; //if (!context.Request.Url.Query.Equals(signedQuery)) //{ // throw new SecurityException(string.Format("DocService StreamFile header id not equals: {0} and {1}", context.Request.Url.Query, signedQuery)); //} } catch (Exception ex) { Global.Logger.Error("Download stream header " + context.Request.Url, ex); context.Response.StatusCode = (int)HttpStatusCode.Forbidden; context.Response.Write(FilesCommonResource.ErrorMassage_SecurityException); return; } } } if (file == null || version > 0 && file.Version != version) { file = version > 0 ? fileDao.GetFile(id, version) : fileDao.GetFile(id); } if (file == null) { context.Response.StatusCode = (int)HttpStatusCode.NotFound; return; } if (linkRight == FileShare.Restrict && SecurityContext.IsAuthenticated && !Global.GetFilesSecurity().CanRead(file)) { context.Response.StatusCode = (int)HttpStatusCode.Forbidden; return; } if (!string.IsNullOrEmpty(file.Error)) { context.Response.StatusDescription = file.Error; context.Response.StatusCode = (int)HttpStatusCode.BadRequest; return; } context.Response.AddHeader("Content-Disposition", ContentDispositionUtil.GetHeaderValue(file.Title)); context.Response.ContentType = MimeMapping.GetMimeMapping(file.Title); using (var stream = fileDao.GetFileStream(file)) { context.Response.AddHeader("Content-Length", stream.CanSeek ? stream.Length.ToString(CultureInfo.InvariantCulture) : file.ContentLength.ToString(CultureInfo.InvariantCulture)); stream.StreamCopyTo(context.Response.OutputStream); } } } catch (Exception ex) { Global.Logger.Error("Error for: " + context.Request.Url, ex); context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; context.Response.Write(ex.Message); return; } try { context.Response.Flush(); context.Response.SuppressContent = true; context.ApplicationInstance.CompleteRequest(); } catch (HttpException he) { Global.Logger.ErrorFormat("StreamFile", he); } }
public async Task Verify_RS512_Algorithm_Serialization() { var keySet = await JWKSet.GetAsync(this.keySetUri); var key = keySet["rsa-512"]; var token = new JsonWebToken { Issuer = "joe", ExpirationTime = 1300819380 }; token.AddClaim("http://example.com/is_root", true); var header = new JoseHeader() { JwkSetUrl = this.keySetUri, KeyId = "rsa-512" }; var serializer = new JWSCompactSerializer(new RS512Algorithm(privateKey: key)); var strToken = serializer.Serialize(token.ToJson(), header); var deserializedToken = await serializer.DeserializeAsync(strToken); Assert.AreEqual(token.ToJson(), deserializedToken.ToJson()); }