/// <summary> /// Generates new JWT using specified identity and additional data. /// </summary> /// <param name="identity">identity to generate with.</param> /// <param name="data">dictionary with additional data which will be kept in jwt body.</param> /// <returns>a new instanse of <see cref="Jwt"/>.</returns> public Jwt GenerateToken(string identity, Dictionary <object, object> data = null) { if (string.IsNullOrWhiteSpace(identity)) { throw new ArgumentException($"{nameof(identity)} property is mandatory"); } //to truncate milliseconds and microseconds var timeNow = DateTime.UtcNow; var issuedAt = timeNow.AddTicks(-timeNow.Ticks % TimeSpan.TicksPerSecond); var expiresAt = issuedAt.AddMilliseconds(LifeTime.TotalMilliseconds); var jwtBody = new JwtBodyContent( AppId, identity, issuedAt, expiresAt, data); var jwtHeader = new JwtHeaderContent(AccessTokenSigner.GetAlgorithm(), ApiPublicKeyId); var unsignedJwt = new Jwt(jwtHeader, jwtBody, null); var jwtBytes = Bytes.FromString(unsignedJwt.ToString()); var signature = AccessTokenSigner.GenerateTokenSignature(jwtBytes, ApiKey); return(new Jwt(jwtHeader, jwtBody, signature)); }
/// <summary> /// To verify specified token. /// </summary> /// <param name="jwToken">An instance of <see cref="Jwt"/> to be virefied.</param> /// <returns>true if token is verified, otherwise false.</returns> public bool VerifyToken(Jwt jwToken) { if (jwToken == null) { throw new ArgumentNullException(nameof(jwToken)); } if (jwToken.HeaderContent.KeyId != ApiPublicKeyId || jwToken.HeaderContent.Algorithm != AccessTokenSigner.GetAlgorithm() || jwToken.HeaderContent.ContentType != JwtHeaderContent.VirgilContentType || jwToken.HeaderContent.Type != JwtHeaderContent.JwtType) { return(false); } return(this.AccessTokenSigner.VerifyTokenSignature( jwToken.SignatureData, jwToken.Unsigned(), ApiPublicKey)); }