Authorize属性なしでアクションを作成する必要がありますが、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 は常に false です。しかし、パラメーター AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme で Authorize 属性を追加すると、User.Identity.IsAuthenticated は true になります。
この問題をどのように解決しますか? バリアントはありますか?