Как хранить токен в Asp Net Core Web App (не в WebAPI) - PullRequest
1 голос
/ 26 апреля 2020

Я хочу аутентифицировать пользователей с токенами JWT в Asp. Net Базовое веб-приложение (не WebAPI). Как сохранить токен JWT, опубликовать его в заголовке каждого запроса Http и как прочитать сохраненную информацию из cook ie в действии контроллера?
Вот мой метод Login в контроллере Auth:

[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();
}

В классе запуска я настроил аутентификацию следующим образом:

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"])
                )
            };
        });
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...