简体   繁体   中英

how to get bearer token out of JWT token (system.identitymodel.token.jwt.jwtsecuritytoken)

I have the following code:

 public AuthToken Authenticate(Auth auth)
        {
            using (var ctx = CiderQuestionaireContext.Create())
            {
                try
                {
                    var user = ctx.Users.SingleOrDefault(e => e.Email == auth.Email);

                    if (user == null) return null;

                    var token = generateJwtToken(user);

                    return new AuthToken
                    {
                        UserId = user.Id,
                        Token = token
                    };
                }
                catch (Exception e)
                {
                    throw e;
                }

            }
        }

which returns a hash that I send in to the following. The string token param below is the return I get from my above call.

 public JwtSecurityToken Validated(string token)
        {//must return bearertoken
            try
            {
                var key = Encoding.ASCII.GetBytes(_appSettings.Secret);
                new JwtSecurityTokenHandler().ValidateToken(token, new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(key),
                    ValidateIssuer = false,
                    ValidateAudience = false,
                    // set clockskew to zero so tokens expire exactly at token expiration time (instead of 5 minutes later)
                    ClockSkew = TimeSpan.Zero
                }, out SecurityToken validatedToken);

                var jwtToken = (JwtSecurityToken)validatedToken;
                var userId = int.Parse(jwtToken.Claims.First(x => x.Type == "id").Value);
                var user = GetById(userId);

                if (user == null)
                    return null;
                else
                    return jwtToken;
            }
            catch(Exception e)
            {
                throw e;//new Exception(Resource.InvalidToken);
            }
        }

but I need a bearer token returned.

What am I doing wrong? Or maybe it is returned and I don't realize. Also, then how do I use the "bearer token" throughout the application to keep other apis safe? Right now, I call the "Authorize" attribute at the top of every controller....

the return is:

{
    "actor": null,
    "audiences": [],
    "claims": [
        {
            "issuer": "LOCAL AUTHORITY",
            "originalIssuer": "LOCAL AUTHORITY",
            "properties": {},
            "subject": null,
            "type": "id",
            "value": "6",
            "valueType": "http://www.w3.org/2001/XMLSchema#string"
        },
        {
            "issuer": "LOCAL AUTHORITY",
            "originalIssuer": "LOCAL AUTHORITY",
            "properties": {},
            "subject": null,
            "type": "nbf",
            "value": "1618714791",
            "valueType": "http://www.w3.org/2001/XMLSchema#integer"
        },
        {
            "issuer": "LOCAL AUTHORITY",
            "originalIssuer": "LOCAL AUTHORITY",
            "properties": {},
            "subject": null,
            "type": "exp",
            "value": "1618721991",
            "valueType": "http://www.w3.org/2001/XMLSchema#integer"
        },
        {
            "issuer": "LOCAL AUTHORITY",
            "originalIssuer": "LOCAL AUTHORITY",
            "properties": {},
            "subject": null,
            "type": "iat",
            "value": "1618714791",
            "valueType": "http://www.w3.org/2001/XMLSchema#integer"
        }
    ],
    "encodedHeader": "eyJhbaaaaaaaaaaaaaaaaaaaaaaaaa6IkpXVCJ9",
    "encodedPayload": "eyJpZCI6IjYiLCJuYaaaaaaaaaaaaaaaaMSwiaWF0IjoxNjE4NzE0NzkxfQ",
    "header": {
        "alg": "HS256",
        "typ": "JWT"
    },
    "id": null,
    "issuer": null,
    "payload": {
        "id": "6",
        "nbf": 1618714791,
        "exp": 1618721991,
        "iat": 1618714791
    },
    "innerToken": null,
    "rawAuthenticationTag": null,
    "rawCiphertext": null,
    "rawData": "eyJaaaaaaaaaaaaaaaaaaaaaadt0L5_f8BR5UCPuKXk",
    "rawEncryptedKey": null,
    "rawInitializationVector": null,
    "rawHeader": "eyaaaaaaaaaaaaaaapXVCJ9",
    "rawPayload": "eyaaaaaaaaaaaaaaaI6MTYxODcyMTk5MSwiaWF0IjoxNjE4NzE0NzkxfQ",
    "rawSignature": "aaaaaaaaaaaaaaApoYZZaG7Lk5dt0L5_f8BR5UCPuKXk",
    "securityKey": null,
    "signatureAlgorithm": "HS256",
    "signingCredentials": null,
    "encryptingCredentials": null,
    "signingKey": {
        "keySize": 512,
        "keyId": null,
        "cryptoProviderFactory": {
            "cryptoProviderCache": {},
            "customCryptoProvider": null,
            "cacheSignatureProviders": true
        }
    },
    "subject": null,
    "validFrom": "2021-04-18T02:59:51Z",
    "validTo": "2021-04-18T04:59:51Z",
    "issuedAt": "2021-04-18T02:59:51Z"
}

To use JWT Bearer Token as Authenticated method for ASP.NET Core first of all you need to configure your JWT Bearer as Authentication method in Startup.cs.

Inside ConfigureService

services.AddAuthentication(options =>  
 {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
        }).AddJwtBearer(options =>
        {
            options.SaveToken = true;
            options.RequireHttpsMetadata = false;
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidateAudience = true,
                ValidIssuer = Configuration.GetSection("Issuer").Value,//getting from appsettings.json
                ValidAudience = Configuration.GetSection("Audience").Value,//getting from appsettings.json
                ValidateLifetime = true,
                ClockSkew = TimeSpan.Zero,
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration.GetSection("SecretKey").Value))
            };
});

Then inside Configure method

app.UseAuthentication(); 
app.UseAuthorization();

To generate a token

public string GetToken(IConfiguration configuration, ApplicationUser userModel)
    {
        _ = int.TryParse(configuration.GetSection("UserTokenExpireDays").Value, out var expireDays);
       
        var claims = new[]
        {
            new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
            new Claim(ClaimTypes.Email, userModel.Email),
            new Claim(ClaimTypes.Name, userModel.UserName),
            new Claim(ClaimTypes.NameIdentifier, userModel.Id),  
            new Claim(ClaimTypes.Country, userModel.CountryCode),//if any
            new Claim(ClaimTypes.Locality, userModel.Country.ToString()),//if any
            // Add more claims you if you need.
        };

        return CreateToken(configuration, expireDays, claims);
    } 

    private static string CreateToken(IConfiguration configuration, int expireDays, Claim[] claims)
    {            
        var signingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration.GetSection("SecretKey").Value)); 

        var token = new JwtSecurityToken
        (
            issuer: configuration.GetSection("Issuer").Value,
            audience: configuration.GetSection("Audience").Value,
            expires: DateTime.UtcNow.AddMonths(1),
            claims: claims,
            signingCredentials: new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256)
        );
        return new JwtSecurityTokenHandler().WriteToken(token);
    }  

Now you can get a JWT Bearer Token to secure your Controller Action methods, the Token you get you need to add it in every call header like below.

const request = req.clone({ //req is an Angular HttpRequest
     setHeaders: {
              Authorization: `Bearer ${the_token}`
          } 
     });

Now you have a fully working JWT Bearer Authentication in your ASP.NET Core app.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM