简体   繁体   中英

Authorization has been denied for this request : JWT Bearer

I'm using JWT to handle authentification/Authorization in my Asp.net Web Api. I've decorated my differents controller with [Authorize]. Each time I made a call, this message is Send :Authorization has been denied for this request.

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 :

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)

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