'Authorize works in postman but not in the browser | Asp.net core 3.1 & jwt
When i make requests with token by Postman works very good but when i do it by the browser (Angular) i get the status code 404
By postman
Request Headers
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1laWQiOiJwdXB5IGZyaWFzIiwibmJmIjoxNjUyMDY1NzczLCJleHAiOjE2NTIwNjU4MzMsImlhdCI6MTY1MjA2NTc3M30.4mdgD-wbcwYb0nNKUYqEZJwhWKiixDhFRgdffW4QEs4
User-Agent: PostmanRuntime/7.29.0
Accept: */*
Cache-Control: no-cache
Postman-Token: 946f36f4-c1a1-4013-94bc-3bbebfeb452a
Host: localhost:59573
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Status Code: 200 OK
By browser
Request Headers
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate, br
Accept-Language: es-US,es;q=0.9,en-US;q=0.8,en;q=0.7,es-419;q=0.6
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1laWQiOiJwdXB5IGZyaWFzIiwibmJmIjoxNjUyMDY1NzczLCJleHAiOjE2NTIwNjU4MzMsImlhdCI6MTY1MjA2NTc3M30.4mdgD-wbcwYb0nNKUYqEZJwhWKiixDhFRgdffW4QEs4
Connection: keep-alive
Host: localhost:59573
Origin: http://localhost:4200
Referer: http://localhost:4200/
sec-ch-ua: " Not A;Brand";v="99", "Chromium";v="101", "Google Chrome";v="101"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Windows"
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.54 Safari/537.36
Status Code: 404 Not Found
This is the Startup
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
var key = Encoding.ASCII.GetBytes(Configuration.GetValue<string>("SecretKey"));
services.AddAuthentication(auth =>
{
auth.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
auth.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
auth.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(jwtB =>
{
jwtB.RequireHttpsMetadata = false;
jwtB.SaveToken = true;
jwtB.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
ValidateLifetime = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false
};
});
services.AddCors(options =>
{
options.AddPolicy("AllowWebApp", policy =>
policy.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
);
});
services.AddDbContext<contextItem>(options =>
{
options.UseSqlServer(Configuration.GetConnectionString("EFConnection"));
});
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors("AllowWebApp");
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
Generating the token
public async Task<IActionResult> Post(UserLogin data)
{
if (!ModelState.IsValid)
{
return BadRequest();
}
User user = await _context._User.Where(i => i.User_Name == data.User_name).FirstOrDefaultAsync();
if (user == null)
{
return NotFound("User doesn't exist");
}
if (data.Password != user.Password)
{
return new ObjectResult("Invalid Password") { StatusCode = 403 };
}
else
{
var secretKey = _configuration.GetValue<string>("SecretKey");
var key = Encoding.ASCII.GetBytes(secretKey);
var claims = new ClaimsIdentity();
claims.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Name));
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = claims,
Expires = DateTime.UtcNow.AddMinutes(1),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var tokenHadler = new JwtSecurityTokenHandler();
var createdToken = tokenHadler.CreateToken(tokenDescriptor);
string bearerToken = tokenHadler.WriteToken(createdToken);
return Ok(bearerToken);
}
}
The controller
[Authorize]
[Route("api/[controller]")]
[ApiController]
public class ItemsController : ControllerBase
{
private readonly contextItem _context;
public ItemsController(contextItem context)
{
_context = context;
}
[HttpGet("{id}")]
public async Task<ActionResult<object>> GetItem(int id)
{
var item = await Task.Run(() => _context.Item.FromSqlRaw($"EXEC SP_GET_ONE @ID={id}").AsEnumerable().FirstOrDefault());
if (item == null)
{
return NotFound();
}
return item;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
