1

I want to know how I can return my generated JWT token to user. I mean I would like this token to be saved e.g. somewhere in the user's browser and sent to my Controller in every query after successfully login.

The token generating functions are already written. Everything works, unfortunately, I do not know how to pass it to the user and then pick it up in other functions / controllers

This is the login controller:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(LoginDto dto)
{
    if (ModelState.IsValid)
    {
        string token = _accountService.GenerateJwt(dto); //working

        if (token != null)
        {
            // how can I return token there?

            return RedirectToAction("LoginSuccess");
        }
        else
        {
            ViewBag.error = "Login failed";
            return RedirectToAction("LoginFailed");
        }
    }
}

This is the function that generates the token:

public string GenerateJwt(LoginDto dto)
{
    var user = _context.dnozasg2lp_vip_users.FirstOrDefault(u => u.Email == dto.Email);

    if (user is null)
    {
        throw new BadRequestException("Invalid username or password!");
    }

    var result = _passwordHasher.VerifyHashedPassword(user, user.Password, dto.Password);

    if (result == PasswordVerificationResult.Failed)
    {
        throw new BadRequestException("Invalid username or password!");
    }

    var claims = new List<Claim>()
        {
            new Claim(ClaimTypes.NameIdentifier, user.ID.ToString()),
            new Claim(ClaimTypes.Name, $"{user.FirstName} {user.LastName}"),
            new Claim(ClaimTypes.Email, $"{user.Email}")
        };

    var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_authenticationSettings.JwtKey));
    var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
    var expiration = DateTime.Now.AddDays(_authenticationSettings.JwtExpireDays);

    var token = new JwtSecurityToken(_authenticationSettings.JwtIssuer,
            _authenticationSettings.JwtIssuer,
            claims,
            expires: expiration,
            signingCredentials: credentials
            );

     var tokenHandler = new JwtSecurityTokenHandler();

     return tokenHandler.WriteToken(token);
}

And my startup config file:

// JWT Token config below
var authenticationSettings = new AuthenticationSettings();

services.AddSingleton(authenticationSettings);

Configuration.GetSection("Authentication").Bind(authenticationSettings);

services.AddAuthentication(option =>
        {
            option.DefaultAuthenticateScheme = "Bearer";
            option.DefaultScheme = "Bearer";
            option.DefaultChallengeScheme = "Bearer";
        }).AddJwtBearer(cfg =>{
            cfg.RequireHttpsMetadata = false;
            cfg.SaveToken = true;
            cfg.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
            {
                ValidIssuer = authenticationSettings.JwtIssuer, 
                ValidAudience = authenticationSettings.JwtIssuer,
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(authenticationSettings.JwtKey)),
            };
        });

Like I said, the JWT token is successfully generated, but how can I send it to user and then catch it (for example in a "LoginSuccess" action) ?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
tkeyy
  • 11
  • 1
  • If you want to send it to the view then just use `ViewBag` or a model. But please have a look at this question: https://stackoverflow.com/questions/27067251/where-to-store-jwt-in-browser-how-to-protect-against-csrf for security reasons. – Sebastian Siemens Sep 28 '21 at 18:37
  • Hi @tkeyy, if you just want to get the token in the next request, you can use ViewBag or TempData etc. But if you want to get the token in each request, you need use Session. Besides, if your action contains `Authorize` attribute and you want to use the jwt token to authenticate by code, you need firstly add token to Session and then get the Session data in middleware to add the token to the request header. Anyway, your scenario is not clear, more details will be helpful. – Rena Sep 29 '21 at 08:59

0 Answers0