Implemented JWT authentication in my application, with this code in the Program.cs
:
builder.Services.AddAuthentication(AuthConstants.AUTH_TOKEN)
.AddCookie(AuthConstants.AUTH_TOKEN, options =>
{
options.Cookie.Name = AuthConstants.AUTH_TOKEN;
options.LoginPath = "/Home/Login";
})
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = builder.Configuration["Jwt:Issuer"],
ValidAudience = builder.Configuration["Jwt:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))
};
});
Also, I included authentication and authorization middleware there:
app.UseAuthentication();
app.UseAuthorization();
Here is my UserController
which are all of the authorized route
[Authorize]
public class UserController : Controller
{
public IActionResult Dashboard(string token)
{
return View();
}
}
This is the Login
method in HomeController
:
[HttpPost]
public async Task<IActionResult> Login(LoginDTO loginUser)
{
if (ModelState.IsValid)
{
var token = _loginService.GenerateToken(loginUser, _configuration);
if (token != null)
{
var tokenHandler = new JwtSecurityTokenHandler();
var jwtToken = tokenHandler.ReadJwtToken(token);
CookieOptions cookieOptions = new CookieOptions
{
HttpOnly = true,
Secure = true,
Expires = jwtToken.ValidTo
};
Response.Cookies.Append(AuthConstants.AUTH_TOKEN, token, cookieOptions);
TempData["Success"] = "Login Successful";
string returnUrl = HttpContext.Request.Query["returnUrl"];
if (!String.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl))
return Redirect(returnUrl);
return RedirectToAction("Dashboard", "User");
}
TempData["Error"] = "Invalid credentials, please try again.";
}
return View(loginUser);
}
After that, this will return me to login page with return url, which means that authorize not working here.