首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何从JWT token (system.identitymodel.token.jwt.jwtsecuritytoken)中获取承载token

如何从JWT token (system.identitymodel.token.jwt.jwtsecuritytoken)中获取承载token
EN

Stack Overflow用户
提问于 2021-04-18 11:37:37
回答 1查看 60关注 0票数 0

我有以下代码:

代码语言:javascript
复制
 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;
                }

            }
        }

它返回我发送给下面的散列。下面的字符串token param是我从上面的调用中得到的返回值。

代码语言:javascript
复制
 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);
            }
        }

但我需要返回一个持有者令牌。

我做错了什么?也许它被退回了,但我没有意识到。另外,我如何在整个应用程序中使用“持有者令牌”来保护其他apis的安全呢?现在,我在每个控制器的顶部调用"Authorize“属性。

结果是:

代码语言:javascript
复制
{
    "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"
}
EN

回答 1

Stack Overflow用户

发布于 2021-04-18 18:12:28

要使用JWT承载令牌作为ASP.NET核心的身份验证方法,首先需要在Startup.cs中将JWT承载配置为身份验证方法。

ConfigureService内幕

代码语言:javascript
复制
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))
            };
});

然后内部配置方法

代码语言:javascript
复制
app.UseAuthentication(); 
app.UseAuthorization();

要生成标记,请执行以下操作

代码语言:javascript
复制
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);
    }  

现在你可以获得一个JWT持有者令牌来保护你的控制器操作方法,你需要得到的令牌将它添加到每个调用头中,如下所示。

代码语言:javascript
复制
const request = req.clone({ //req is an Angular HttpRequest
     setHeaders: {
              Authorization: `Bearer ${the_token}`
          } 
     });

现在,您在ASP.NET核心应用程序中拥有了一个完全有效的JWT持有者身份验证。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67144968

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档