首页 > 解决方案 > JWT 授权令牌在客户端生成,但在 API 中不起作用

问题描述

我已经尝试实现jwt 身份验证,因为令牌是在客户端正确生成的,但Web API没有对来自客户端的请求进行身份验证,我提供了我使用过的代码,我正在用asp 实现这个。净核心 1.1。 我已确保令牌正在使用JWT.io生成有效信息,并且一切正常。

这是 Web API 上的代码,它将验证来自另一台服务器的传入令牌

        app.UseJwtBearerAuthentication(new JwtBearerOptions()
        {
            AutomaticAuthenticate=true,
            IncludeErrorDetails=true,               
            TokenValidationParameters = new TokenValidationParameters()
            {
                ValidateIssuer = false,
                ValidateAudience = false,
                ValidAudience = "exampleissuer",
                ValidIssuer = "exampleaudience",
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("superkey_ValueforSigningTheJSONWebTokenJWT"))
            }
        });

这是应用程序中生成令牌并通过请求发送的代码。

var signinKey = new SymmetricSecurityKey(

Encoding.UTF8.GetBytes("superkey_ValueforSigningTheJSONWebTokenJWT"));

var token = new JwtSecurityToken(
    issuer: "exampleissuer",
    audience: "exampleaudience",
    signingCredentials: new SigningCredentials(signinKey, SecurityAlgorithms.HmacSha256)
);

var AuthenticationToken = new JwtSecurityTokenHandler().WriteToken(token);
            //                
_restClient.Authenticator = new JwtAuthenticator(AuthenticationToken);

req.AddHeader("WWW-Authenticate", string.Format("Bearer {0}", AuthenticationToken));

_restClient.Authenticator.Authenticate(_restClient, req);
            //

有人可以帮我在 web api 中验证令牌。

标签: restauthenticationasp.net-core-mvcjwtauthorization

解决方案


推荐阅读