是的,可以在同一应用程序中同时使用Windows身份验证和JWT。以下是如何实现的简要步骤:
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
public class ProtectedController : ControllerBase
{
// Your protected controller methods
}
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = "example.com",
ValidateAudience = true,
ValidAudience = "example.com",
ValidateLifetime = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("yourSecretKey")),
ValidateIssuerSigningKey = true,
};
});
services.AddAuthorization(options =>
{
options.DefaultPolicy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
});
var identity = HttpContext.User.Identity as ClaimsIdentity;
var username = identity.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value;
这样,你就可以在同一应用程序中同时使用Windows身份验证和JWT了。