Reputation: 1045
I have an API which i implemented jwt for the authentication,here is my authentication:
[Route("api/[controller]")]
[ApiController]
public class AuthController : ControllerBase
{
[HttpPost, Route("login")]
public IActionResult Login([FromBody]LoginModel user)
{
if (user == null)
{
return BadRequest("Invalid client request");
}
if (user.UserName == "test" && user.Password == "1234")
{
var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("sretKey@345"));
var signinCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256);
var tokeOptions = new JwtSecurityToken(
issuer: "https://localhost:44361",
audience: "https://localhost:44378",
claims: new List<Claim>(),
expires: DateTime.Now.AddMinutes(25),
signingCredentials: signinCredentials
);
and in postman here is the error
in my controller, I added the authorize attribute, I tested my controller without authorizing attribute and it works, the problem is why it unauthorized me with credentials
here is my startup
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(opt => {
opt.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
opt.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "https://localhost:44361",
ValidAudience = "https://localhost:44378",
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("sretKey@345"))
};
});
services.AddCors(options =>
{
options.AddPolicy("EnableCORS", builder =>
{
builder.WithOrigins("http://localhost:44378")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
services.AddDbContext<DbContextClass>(options =>
options.UseNpgsql(Configuration.GetConnectionString("DefaultConnection")));
services.AddControllers();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
Upvotes: 0
Views: 1671
Reputation: 43850
Add AllowAnonymous to your login action
[AllowAnonymous]
[HttpPost("login")]
public IActionResult Login([FromBody]LoginModel user)
{
.... your code
var token = new JwtSecurityTokenHandler().WriteToken(tokeOptions);
return Ok(token);
}
After this you have to configure the startup to use this token. And also you have to add this token to Postman for action testing. Postman has a special menu Autorization. Open it , select token option and paste your token in the field. Instead of login and pass put your input action parameters if needed
And try to add app.UseAuthentication() like this:
app.UseAuthentication();
app.UseAuthorization();
Upvotes: 1