0

我需要在没有授权属性的情况下创建操作,但我需要在 User.Identity.IsAuthenticated 中获取值。

启动:

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

代币:

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

控制器:

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

User.Identity.IsAuthenticated 始终为假。但是,如果我使用参数 AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme 添加 Authorize 属性,则 User.Identity.IsAuthenticated 为真。

如何解决这个问题?有变种吗?

4

1 回答 1

0

我在控制器之前添加了 Authorize with scheme,在我的方法之前添加了 AllowAnonymous。这有效

于 2019-05-15T13:12:51.747 回答