简体   繁体   English

此请求的授权已被拒绝:JWT承载

[英]Authorization has been denied for this request : JWT Bearer

I'm using JWT to handle authentification/Authorization in my Asp.net Web Api. 我正在使用JWT在Asp.net Web Api中处理身份验证/授权。 I've decorated my differents controller with [Authorize]. 我已经用[Authorize]装饰了我的differents控制器。 Each time I made a call, this message is Send :Authorization has been denied for this request. 每次拨打电话时,此消息均为Send:该请求的授权已被拒绝。

Here is an example of one of my controllers : 这是我的一个控制器的示例:

    [System.Web.Http.Route("api/MyParticipations")]
    [System.Web.Http.HttpGet]
    [System.Web.Http.ActionName("XAMARIN_SelectMyEvent")]
    [Authorize]
    public HttpResponseMessage Xamarin_SelectMyEvents()
    {
        string token = Request.Headers.Authorization.ToString();
        string resultToken = Utils.Util.ValidateToken(token);
        if (resultToken == null)
        {
            return Request.CreateResponse(HttpStatusCode.NotFound, "Your session has expired");
        }
        int userId = Int32.Parse(resultToken);
        var MyEvents = db.getMyEvents(userId);
        if (MyEvents == null)
        {
            return Request.CreateResponse(HttpStatusCode.NotFound, "No Events available");
        }
        else
        {
            return Request.CreateResponse(HttpStatusCode.Accepted, MyEvents);
        }
    }

Here is my Startup Class : 这是我的启动班:

    public IConfiguration _Configuration { get; }

    public Startup(IConfiguration configuration)
    {
        _Configuration = configuration;
    }
    public Startup()
    {

    }
    public void Configuration(IAppBuilder app)
    {
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=316888
    }
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseAuthentication();
        app.UseMvc();
    }
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateLifetime = true,
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(
                        Encoding.UTF8.GetBytes(_Configuration[System.Web.Configuration.WebConfigurationManager.AppSettings["JWTKEY"]]))
                };
            });
        services.AddMvc();
    }

A little problem that I didn't succeed to fix was the empty constructor in the startup Class. 我没有成功解决的一个小问题是启动类中的空构造函数。 If I delete it, I receive an error message : "no constructor without parameters defined for this object owin". 如果删除它,则会收到错误消息:“没有为此对象定义参数的构造函数。”

Here is my code that generates and validate the JWT : 这是生成并验证JWT的代码:

private static string Secret = System.Web.Configuration.WebConfigurationManager.AppSettings["JWTKEY"];

    public static string GenerateToken(int userId)
    {
        byte[] key = Convert.FromBase64String(Secret);
        SymmetricSecurityKey securityKey = new SymmetricSecurityKey(key);
        SecurityTokenDescriptor descriptor = new SecurityTokenDescriptor
        {
            Subject = new ClaimsIdentity(new[] {
                  new Claim(ClaimTypes.PrimarySid, userId.ToString())}),
            Expires = DateTime.UtcNow.AddDays(3),
            SigningCredentials = new SigningCredentials(securityKey,
            SecurityAlgorithms.HmacSha256Signature)
        };

        JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
        JwtSecurityToken token = handler.CreateJwtSecurityToken(descriptor);
        return handler.WriteToken(token);
    }

    public static ClaimsPrincipal GetPrincipal(string token)
    {
        try
        {
            JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
            JwtSecurityToken jwtToken = (JwtSecurityToken)tokenHandler.ReadToken(token);
            if (jwtToken == null)
                return null;
            byte[] key = Convert.FromBase64String(Secret);
            TokenValidationParameters parameters = new TokenValidationParameters()
            {
                RequireExpirationTime = true,
                ValidateIssuer = false,
                ValidateAudience = false,
                IssuerSigningKey = new SymmetricSecurityKey(key)
            };
            SecurityToken securityToken;
            ClaimsPrincipal principal = tokenHandler.ValidateToken(token,
                  parameters, out securityToken);
            return principal;
        }
        catch (Exception e)
        {
            return null;
        }
    }
    public static string ValidateToken(string token)
    {
        string userId = null;
        ClaimsPrincipal principal = GetPrincipal(token);
        if (principal == null)
            return null;
        ClaimsIdentity identity = null;
        try
        {
            identity = (ClaimsIdentity)principal.Identity;
        }
        catch (NullReferenceException)
        {
            return null;
        }
        Claim usernameClaim = identity.FindFirst(ClaimTypes.PrimarySid);
        userId = usernameClaim.Value;
        return userId;
    }

Can anyone see what's wrong with this code? 谁能看到这段代码有什么问题吗? I've look the others subjects but none of them gave me a solution. 我看过其他主题,但没有一个给我解决方案。

Thanks for reading, 谢谢阅读,

A desesperate student 一个绝望的学生

Make sure if you are doing all the following steps: 确保您正在执行以下所有步骤:

  1. User provides credentials (Client-Side) 用户提供凭据(客户端)
  2. Credentials are approved (Server-Side) 凭据被批准(服务器端)
  3. Token is generated (Server-Side) 令牌生成(服务器端)
  4. Token is sent to client (Server-Side) 令牌发送到客户端(服务器端)
  5. Client receives the token and adds the Authorization Header to the subsequent requests' Headers with the value of "Bearer GeneratedToken" (eg Authorizarion : "Bearer eyJhbGci..." ) (Client-Side) 客户端接收令牌,然后将Authorization Header添加到后续请求的标头中,其值为“ Bearer GeneratedToken”(例如Authorizarion : "Bearer eyJhbGci..." )(客户端)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Azure AD 带有用于 Web API 的不记名令牌身份验证的 AD 无法正常工作,抛出错误,因为“此请求的授权已被拒绝”。 - Azure AD with Bearer token authentication for Web API not working throwing error as “Authorization has been denied for this request.” 始终使用身份2中的不记名令牌获得“对此请求的授权已被拒绝”。 - Always get “Authorization has been denied for this request.” using Bearer tokens in Identity 2? 发送承载令牌时,API端点返回“此请求已拒绝授权。” - API end point returning “Authorization has been denied for this request.” when sending bearer token 此请求已被拒绝授权。 总是 - Authorization has been denied for this request. Always 此请求被拒绝获得授权 - Getting Authorization has been denied for this request 挥舞着“此请求的授权已被拒绝”消息 - Swagger “Authorization has been denied for this request” message 此请求的C#授权被拒绝 - C# Authorization has been denied for this request 此请求的授权已被拒绝。 邮差 - Authorization has been denied for this request. Postman OAuth令牌授权(请求已被拒绝) - OAuth token authorization (request has been denied) httpclient令牌对此请求的授权已被拒绝 - httpclient token Authorization has been denied for this request
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM