已授权登录场景下,jQuery调用ASP.NET Core API的认证参数配置问题
没错,你确实需要获取用户的access token来调用这个API——因为你的Web应用的Cookie只能在自己的域名(localhost:5002)下生效,跨域请求localhost:5001的API时,浏览器不会自动携带这个Cookie,而且API是受Identity Server保护的,需要用Bearer token来完成认证。下面是具体的实现步骤:
1. 确保Web应用登录时请求了API的权限范围
首先要确认你的Web应用在Identity Server的客户端配置中,已经添加了目标API的权限范围(比如api1,具体名称要和API的配置一致)。同时,Web应用的登录流程需要请求这个scope,比如在AddOpenIdConnect配置里:
services.AddAuthentication(options => { options.DefaultScheme = "Cookies"; options.DefaultChallengeScheme = "oidc"; }) .AddCookie("Cookies") .AddOpenIdConnect("oidc", options => { options.Authority = "http://localhost:5000"; options.ClientId = "web_app"; // 你的Web应用客户端ID options.ClientSecret = "your_secret"; options.ResponseType = "code"; options.Scope.Add("api1"); // 添加API的权限范围 options.SaveTokens = true; // 关键:保存获取到的access token到Cookie中 });
这里的SaveTokens = true很重要,它会把Identity Server颁发的access token、id token等保存到Web应用的Cookie里,方便后续获取。
2. 在页面中获取access token
在你的Razor视图(或HTML页面)中,通过ASP.NET Core的HttpContext获取保存的access token,并传递给JavaScript:
<script> // 从服务器端获取access token,注入到JS中 const accessToken = '@await HttpContext.GetTokenAsync("access_token")'; </script>
3. 修改jQuery请求,添加认证头
因为jQuery.get的简写方式不太方便添加请求头,推荐使用$.ajax或者通过beforeSend方法给请求添加Authorization头,格式为Bearer {accessToken}:
方法一:使用$.ajax
$.ajax({ url: "http://localhost:5001/UserProcessData/Id", type: "GET", data: { query: request.term }, headers: { "Authorization": `Bearer ${accessToken}` }, success: function(data) { response(data); } });
方法二:使用jQuery.get + beforeSend
jQuery.get("http://localhost:5001/UserProcessData/Id", { query: request.term }, function(data) { response(data); }).beforeSend(function(xhr) { xhr.setRequestHeader("Authorization", `Bearer ${accessToken}`); });
4. 配置API的CORS策略
由于是跨域请求,你的API(localhost:5001)必须配置CORS,允许来自Web应用(localhost:5002)的请求,并且允许携带Authorization头。在API的Startup.cs(或Program.cs)中添加:
builder.Services.AddCors(options => { options.AddPolicy("AllowWebApp", policy => { policy.WithOrigins("http://localhost:5002") .AllowAnyHeader() .AllowAnyMethod(); }); }); // 注意:CORS中间件要放在认证和授权中间件之前 app.UseCors("AllowWebApp"); app.UseAuthentication(); app.UseAuthorization();
5. 确保API能验证access token
最后,API需要配置JWT认证,来验证Identity Server颁发的access token:
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.Authority = "http://localhost:5000"; // Identity Server地址 options.Audience = "api1"; // 要和Web应用请求的scope一致 });
同时,API的UserProcessData/Id接口需要添加[Authorize]特性,确保只有携带有效token的请求才能访问。
内容的提问来源于stack exchange,提问作者Mark Johnson

