Varda Elentári
Varda Elentári

Reputation: 2322

Can't get Signature from JwtSecurityToken

I'm trying to use JWT Authentication in .NET and I need the result to look like this:

Header: {"alg":"HS512"}

Payload:

{"sub":"SomeSubject","nbf":1458315105,"exp":1458316305,"iat":1458315705}

I wrote the follwoing code to get the JWT Signed Token:

 public async Task<string> GetJWTToken(string user)
        {
            var now = DateTime.UtcNow;

            JwtHeader jwtHeader = new JwtHeader();

            jwtHeader.Add("alg", JwtAlgorithms.HMAC_SHA512);

            JwtPayload payload = new JwtPayload();
            payload.Add("sub", user);
            payload.Add("exp", ConvertToUnixTimestamp( now.AddMinutes(10)));
            payload.Add("nbf",ConvertToUnixTimestamp(now.AddMinutes(-10)));
            payload.Add("iat",ConvertToUnixTimestamp(now));

            JwtSecurityToken toekn = new JwtSecurityToken(jwtHeader, payload);
            SigningCredentials cred = new SigningCredentials(new InMemorySymmetricSecurityKey(Encoding.UTF8.GetBytes("SomeKey")), "http://www.w3.org/2001/04/xmldsig-more#hmac-sha512", "http://www.w3.org/2001/04/xmlenc#sha512");

            //what's next? 
            return finalResult;
          }

With this code I only get the Header and Payload encrypted, I do not get a Signature. I looked at a lot of places but couldn't find an example that produces similar payload and header.

1- How can I add the Signing Credentials to toeken ; SigningCredentials, SigningToken and SigningKeys cannot be set. Not sure where signing credentials should fit.

2- after that, how is the Signature produced?

Upvotes: 0

Views: 1670

Answers (1)

Haroon
Haroon

Reputation: 1110

The following Code show how you can create a JWT token, where "Certificate" can be self-signed certificate.

    public JwtTokenProvider(string authority)
    {
        _authority = authority;
    }
    public async Task<TokenResult> GetTokenAsync(string clientId, string resource)
    {
        return await Task.FromResult(new TokenResult
        {
            AccessTokenType = "Bearer",
            IdToken = CreateJwt(clientId, resource)
        });
    }
    private string CreateJwt(string clientId, string resource)
    {
        var certificate = new X509Certificate2(Resource.notification, CertPassword);
        var sub = new System.Security.Claims.Claim("sub", clientId);
        var jti = new System.Security.Claims.Claim("jti", Guid.NewGuid().ToString());
        var claims = new List<System.Security.Claims.Claim>() { sub, jti };
        var x509Key = new X509AsymmetricSecurityKey(certificate);
        var signingCredentials = new SigningCredentials(x509Key, SecurityAlgorithms.RsaSha256Signature,
            SecurityAlgorithms.Sha256Digest);
        var jwt = new JwtSecurityToken(_authority, resource, claims,
            DateTime.UtcNow,
            DateTime.UtcNow.AddMinutes(ExpirationInMinutes), signingCredentials);
        var sign = new SignatureProviderFactory();
        var provider = sign.CreateForSigning(x509Key, SecurityAlgorithms.RsaSha256Signature);
        var input = string.Join(".", new[] { jwt.EncodedHeader, jwt.EncodedPayload });
        var signed = provider.Sign(Encoding.UTF8.GetBytes(input));
        sign.ReleaseProvider(provider);
        return string.Join(".", new[] { jwt.EncodedHeader, jwt.EncodedPayload, Base64UrlEncoder.Encode(signed) });
    }

Upvotes: 1

Related Questions