简体   繁体   中英

Why User.Identity.IsAuthenticated false?

I need create action without Authorize atribute but I need get value in User.Identity.IsAuthenticated.

Startup:

services.AddAuthentication(options =>
  {
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultSignInScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
  }).AddJwtBearer(options =>
  {
    options.RequireHttpsMetadata = false;
    options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
    {
      ValidateIssuer = true,
      ValidIssuer = AuthOptions.ISSUER,

      ValidateAudience = true,
      ValidAudience = AuthOptions.AUDIENCE,
      ValidateLifetime = true,

      IssuerSigningKey = AuthOptions.GetSymmetricSecurityKey(),
      ValidateIssuerSigningKey = true,
    };
  });


app.UseAuthentication();

Token:

[HttpPost("/token")]
public async Task Token([FromBody] User user)
{
  var username = user.Login;
  var password = user.Password;
  var identity = await GetIdentityAsync(username, password);
  if (identity == null)
  {
    Response.StatusCode = 400;
    await Response.WriteAsync("Invalid username or password.");
    return;
  }
  var now = DateTime.UtcNow;
  var jwt = new JwtSecurityToken(
          issuer: AuthOptions.ISSUER,
          audience: AuthOptions.AUDIENCE,
          notBefore: now,
          claims: identity.Claims,
          expires: now.Add(TimeSpan.FromMinutes(AuthOptions.LIFETIME)),
          signingCredentials: new SigningCredentials(AuthOptions.GetSymmetricSecurityKey(),
            SecurityAlgorithms.HmacSha256));

  var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

  var response = new
  {
    access_token = encodedJwt,
    user = new
    {
      login = user.Login,
      role = identity.FindFirst(ClaimsIdentity.DefaultRoleClaimType).Value
    }
  };

  Response.ContentType = "application/json";
  await Response.WriteAsync(JsonConvert.SerializeObject(response,
    new JsonSerializerSettings { Formatting = Formatting.Indented }));
}

async Task<ClaimsIdentity> GetIdentityAsync(string userName, string password)
{
  var result = await _signInManager.PasswordSignInAsync(userName, password, false, false);
  if (result.Succeeded)
  {
    var user = await _userManager.FindByNameAsync(userName);
    if (user != null)
    {
      var role = (await _userManager.GetRolesAsync(user)).SingleOrDefault();

      var claims = new List<Claim>
      {
        new Claim(ClaimsIdentity.DefaultNameClaimType, user.UserName),
        new Claim(ClaimsIdentity.DefaultRoleClaimType, role)
      };

      return new ClaimsIdentity(claims, "Token", ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType);
    }
  }
  return null;
}

Controller:

[HttpGet]
public IEnumerable<Book> Get()
{
  var isAuth = User.Identity.IsAuthenticated;
}

User.Identity.IsAuthenticated always false. But if I add Authorize attribute with parametr AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme then User.Identity.IsAuthenticated is true.

How resolve this problem? Is any variants?

I add Authorize with scheme before controller and AllowAnonymous before my method. And this works

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM