1

I want to authenticate users with JWT tokens in Asp.Net Core Web App (not WebAPI). How can I store JWT token, post it in each Http request's header and how to read stored info from cookie in controller action?
Here is my Login method in Auth controller:

[HttpPost]
[Route("LoginStudent")]
public async Task<IActionResult> PostLoginStudent(StudentLoginDto loginDto)
{
    if (!ModelState.IsValid)
    {
        return RedirectToAction(
            actionName: "GetLoginStudent",
            routeValues: new { error = "Invalid login credentials." }
        );
    }

    // Result is instance of a class which contains 
    // - content (StudentReturnDto) of response (from Repository),
    // - message (from Repository),
    // - bool IsSucces indicates whether operation is succes.
    var result = await _repo.LoginStudent(loginDto);
    if (result.IsSuccess)
    {
        // User must be Authorized to acces this Action method.
        return RedirectToAction("GetProfile");
    }

    // If it fails return back to login page.
    return RedirectToAction(
        "GetLoginStudent",
        routeValues: new { error = result.Message }
    );
}

[HttpGet]
[Authorize]
public IActionResult GetProfile()
{
    // Reading user id from token
    return View();
}

In startup class I configured authentication like this:

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options =>
        {
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidateLifetime = true,
                ValidateIssuerSigningKey = true,
                ValidateAudience = true,
                ValidIssuer = _config["Jwt:Issuer"],
                ValidAudience = _config["Jwt:Audience"],
                IssuerSigningKey = new SymmetricSecurityKey(
                    Encoding.UTF8.GetBytes(_config["Jwt:Key"])
                )
            };
        });
TheMisir
  • 4,083
  • 1
  • 27
  • 37
Alvan Rahimli
  • 348
  • 4
  • 10
  • `want to authenticate users with JWT tokens in Asp.Net Core Web App (not WebAPI)` You can check this SO thread: https://stackoverflow.com/questions/37398276/how-can-i-validate-a-jwt-passed-via-cookies – Fei Han Apr 27 '20 at 07:16

1 Answers1

0

It turns out, in web apps it is recommended to use cookies as auth method. But if you want to use JWT, still, you should save token in cookie. Then, read token from cookie and validate it. Thanks to Fei Han, this thread explains this topic.

Alvan Rahimli
  • 348
  • 4
  • 10