skip to Main Content

I have tried to implement JWT token authorisation into my system but it’s not working. I’m new to ASP.net so please go easy on me.

I can login fine and i do get the token as expected. But when I try to use the token as a Bearer token to access an [Authorize] protected End point I get 401 error.

In postman I get Bearer error="invalid_token" in header

I tried to acces my /api/Blogs endpoint which is protected using [Authorize]. I entered "Bearer token" in Swagger and also Authorization > Bearer Token in Postman. Both didn’t work and gave me 401 error.

Here’s my program.cs

//Identity
builder.Services.AddIdentity<ApplicationUser, IdentityRole>()
    .AddEntityFrameworkStores<AppDbContext>()
    .AddDefaultTokenProviders();

// JWT
var key = Encoding.UTF8.GetBytes(builder.Configuration["JWT:AccessTokenKey"]);
builder.Services.AddAuthentication(auth =>
{
    auth.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    auth.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    auth.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;

})
.AddJwtBearer(options => {
     options.SaveToken = true;
     options.RequireHttpsMetadata = false;
     options.TokenValidationParameters = new TokenValidationParameters()
     {
         ValidateIssuer = true,
         ValidateAudience = true,   
         ValidateIssuerSigningKey = true,
         ValidateLifetime = true,
         ValidIssuer = builder.Configuration["JWT:Issuer"],
         ValidAudience = builder.Configuration["JWT:Audience"],
         IssuerSigningKey = new SymmetricSecurityKey(key)
     };
     });

builder.Services.AddSwaggerGen(options =>
{
    options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
    {
        In = ParameterLocation.Header,
        Name = "Authorization",
        Type = SecuritySchemeType.ApiKey,
    });
    options.OperationFilter<SecurityRequirementsOperationFilter>();
});

builder.Services.AddScoped<IAuthenticationService, AuthenticationService>();
builder.Services.AddScoped<ITokenService, TokenService>();
builder.Services.AddScoped<IEmailService, EmailService>();
builder.Services.AddScoped<IGmailEmailProvider, GmailEmailProvider>();
builder.Services.AddScoped<IBlogService, BlogService>();

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();

var app = builder.Build();

app.UseCors(policy =>
    policy.WithOrigins("http://localhost:3000/", "https://localhost:3001")
        .AllowAnyMethod()
        .WithHeaders(HeaderNames.ContentType)
);

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();


Controller

[HttpGet]
        [Authorize]
        public async Task<IActionResult> GetAllBlogsAsync()
        {
            var result = await _blogService.GetAllBlogsAsync();
            return Ok(result);
        }

TokenService

public class TokenService : ITokenService
    {
        private readonly string _key;
        private readonly string _issuer;
        private readonly string _audience;
        public TokenService(IConfiguration configuration)
        {
            _key = configuration.GetSection("JWT:AccessTokenKey").Value!;
            _issuer = configuration.GetSection("JWT:Issuer").Value!;
            _audience = configuration.GetSection("JWT:Audience").Value!;
        }
        public string GenerateToken(ApplicationUser user, IList<string> userRoles)
        {
            var tokenHandler = new JwtSecurityTokenHandler();
            var key = Encoding.UTF8.GetBytes(_key);
            
            var authClaims = new List<Claim>
            {
                new Claim(ClaimTypes.Name, user.UserName),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
            };

            foreach (var userRole in userRoles)
            {
                authClaims.Add(new Claim(ClaimTypes.Role, userRole));
            }


            var token = new JwtSecurityToken(
                issuer: _issuer,
                audience: _audience,
                claims: authClaims,
                expires: DateTime.Now.AddDays(1),
                signingCredentials: new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256)
            );
            return new JwtSecurityTokenHandler().WriteToken(token);
        }

    }

Thank you for the help

2

Answers


  1. Chosen as BEST ANSWER

    I solved my issue. Turns out I hadn't installed the

    System.IdentityModel.Tokens.Jwt
    

    Nuget package. Silly mistake. Thank you all for the help.


  2. I had your issue, and I tried to implement my middleware using reflection in asp .net core

    For login scenario:

    firstly When you want to generate token use :

         if (user is not null)
         {
    
         var claims = new List<Claim>
         {
         new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
         new Claim(ClaimTypes.Name, user.Username),
         new Claim("isAdmin", user.isAdmin.ToString()) ,
         new Claim("isVerified", user.isVerified.ToString()) ,
         new Claim(ClaimTypes.Role,user.Role.ToString())
        
         
     };
    Response.Cookies.Append("Token", GenerateToken(claims ));
    }
    

    Then Try to generate token by claims:

    internal static string GenerateToken(List<Claim> claims)
    {
    
        try
        {
                ///use your Own Secrete key
                var signingKey = new SymmetricSecurityKey(SecreteKeyJWT);
    
                var tokenDescriptor = new SecurityTokenDescriptor
                {
                    Subject = new ClaimsIdentity(claims),
                    Expires = DateTime.UtcNow.AddHours(1), // Token expiration time
                    SigningCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256Signature),
                    
                };
    
                var tokenHandler = new JwtSecurityTokenHandler();
                var token = tokenHandler.CreateToken(tokenDescriptor);
    
                return tokenHandler.WriteToken(token);
             
        }
    
        catch (Exception ex)
        {
    
            return "";
        }
    }
    

    Now the jwt is set in users cookie

    For authorization Check create

    public class JwtAuthorization : Attribute, IAuthorizationFilter
    {
        private readonly string[] _roles;
    
        public JwtAuthorization(params string[] roles)
        {
            _roles = roles;
        }
    
        public void OnAuthorization(AuthorizationFilterContext context)
        {
            if (context.HttpContext.Request.Cookies.TryGetValue("Token", out var token))
            {
                try
                {
                    var tokenHandler = new JwtSecurityTokenHandler();
                    var validationParameters = GetValidationParameters();
                     
                    // Validate token. This throws an exception if the token is invalid.
                    var principal = tokenHandler.ValidateToken(token, validationParameters, out var validatedToken);
                    var claimsIdentity = context.HttpContext.User.Identity as ClaimsIdentity;
                    // Extract roles from the token claims
                    var roles = principal.Claims.Where(c => c.Type == ClaimTypes.Role).Select(c => c.Value).ToList();
    
                    // Check if the user has any of the required role(s)
                    if (roles.Contains("admin")) { return; }
                    if (_roles.Any(role => roles.Contains(role)))
                    {
                        return; // User has the required role
                    }
                    else
                    {
                        context.Result = new ForbidResult(); // User does not have the required role
                        return;
                    }
                }
                catch (Exception)
                {
                    // Token validation failed
                    context.HttpContext.Response.Cookies.Delete("Token");
                   
                    context.Result = new RedirectToActionResult("Login", "Authentication",null);
                   
                    return;
                }
            } 
            context.Result = new RedirectToActionResult("Login", "Authentication", null);
    
            return;
        }
    
        private TokenValidationParameters GetValidationParameters()
        {
            return new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
    /// your secrete key
                IssuerSigningKey = new SymmetricSecurityKey(SecreteKeyJWT),
                ValidateIssuer = false,
                ValidateAudience = false,
                ClockSkew = TimeSpan.Zero // Optional: prevent clock skew issues
            };
        }
    }
    

    Finally When you want to set method to be authorized use at top of the method:

      [JwtAuthorization("user")]
    
    

    For example:

       [JwtAuthorization("admin")]
       public async Task<string> VerifyUser([FromBody] VerifyUserInAdminModel phone)
       {
    
           var veruser = await UserDAL.VerifyUser(phone.phone.ToString());
           if (veruser)
           {
               return "Ok";
           }
           return "Error";
       }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search