.net core 2.1 Token Based Authentication gives 401 Error

45 views Asked by At

Hello I am developing application with token based authentication.

In startup.cs added code below.

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(jwtBearerOptions =>
                {
                    jwtBearerOptions.TokenValidationParameters = new TokenValidationParameters()
                    {
                        ValidateActor = true,
                        ValidateAudience = true,
                        ValidateLifetime = true,
                        ValidateIssuerSigningKey = true,
                        ValidIssuer ="Issuer",
                        ValidAudience ="Audience",
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("ProEMLh5e_qnzdNUQrqdHPgp"))
                    };
                });

and

app.UseAuthentication();

in controller

    HttpPost("AdminLogin")]
    public IActionResult AdminLogin(Admin admin)
    {
       var result = admine.Login(admin);
       if (result!=null && result.Id>0)
       {
          var claims = new[]
          {
             new Claim(JwtRegisteredClaimNames.Sub, admin.Username),
             new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
          };
          var token = new JwtSecurityToken
          (
              issuer: "issuer", 
              audience: "Audience",
              claims: claims,
              expires: DateTime.UtcNow.AddDays(1), 
              notBefore: DateTime.UtcNow,
              signingCredentials: new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes("ProEMLh5e_qnzdNUQrqdHPgp")),
              SecurityAlgorithms.HmacSha256)
              );
              result.Token = new JwtSecurityTokenHandler().WriteToken(token);            
       }
       return Ok(result);
   }

It works and generate token and returns. My problem is that when I send request with this token . It gives 401 Authorization error. for below one

 [Authorize]
 [HttpPost("Exams")]
 public IActionResult Exams([FromBody] Exam model)
 {
   var result = exam.GEtExams(model.Id);
   return Ok(result);
 }

This image is for generating code try enter image description here

After I generated and returned I tried with postman this token like enter image description here

Where is my missing ?

Thanks in advance

0

There are 0 answers