在ASP.NET Core中,處理JWT(JSON Web Token)跨域問題的方法如下:
首先,你需要在Startup.cs
文件中配置CORS策略。在ConfigureServices
方法中添加以下代碼:
services.AddCors(options =>
{
options.AddPolicy("AllowSpecificOrigin",
builder => builder.WithOrigins("http://yourfrontenddomain.com") // 替換為你的前端域名
.AllowAnyHeader()
.AllowAnyMethod());
});
然后,在Configure
方法中添加以下代碼:
app.UseCors("AllowSpecificOrigin");
為了在中間件中處理JWT驗證和跨域問題,你需要創建一個自定義的JWT中間件。在Startup.cs
文件中的ConfigureServices
方法中添加以下代碼:
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.RequireHttpsMetadata = true;
options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your_secret_key")), // 替換為你的密鑰
ValidateIssuer = false,
ValidateAudience = false
};
});
接下來,創建一個名為JwtMiddleware
的新類,并繼承自MiddlewareBase
。在這個類中,你將處理JWT驗證和跨域問題:
public class JwtMiddleware : MiddlewareBase
{
private readonly RequestDelegate _next;
public JwtMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
if (!context.Request.Headers.ContainsKey("Authorization"))
{
context.Response.StatusCode = 401;
await context.Response.WriteAsync("Unauthorized");
return;
}
var token = context.Request.Headers["Authorization"].ToString().Replace("Bearer ", "");
try
{
var claims = new[]
{
new Claim(ClaimTypes.Name, "John Doe"),
new Claim(ClaimTypes.Email, "johndoe@example.com")
};
var identity = new ClaimsIdentity(claims, JwtBearerDefaults.AuthenticationScheme);
var principal = new ClaimsPrincipal(identity);
var contextOptions = new AuthenticationProperties();
contextOptions.AllowRefresh = true;
contextOptions.IsPersistent = true;
contextOptions.ExpiresUtc = DateTime.UtcNow.AddMinutes(30);
await _next(context);
}
catch (Exception ex)
{
context.Response.StatusCode = 401;
await context.Response.WriteAsync("Unauthorized");
}
}
}
Startup.cs
文件中的Configure
方法中添加自定義JWT中間件:app.UseMiddleware<JwtMiddleware>();
現在,你已經創建了一個處理JWT驗證和跨域問題的自定義中間件。當客戶端發送帶有有效JWT的請求時,請求將繼續進行。否則,將返回401未經授權的響應。