前面的部分:
Identity Server 4 從入門到落地(一)—— 從IdentityServer4.Admin開始
Identity Server 4 從入門到落地(二)—— 理解授權碼模式
Identity Server 4 從入門到落地(三)—— 創建Web客戶端
Identity Server 4 從入門到落地(四)—— 創建Web Api
認證服務和管理的github地址: https://github.com/zhenl/IDS4Admin
客戶端及web api示例代碼的github地址:https://github.com/zhenl/IDS4ClientDemo
在前面我們創建了Web Api,為了驗證客戶端,我們從后台訪問Api,再將數據返回瀏覽器,但在實際項目中,一般不會這么做,我們會使用Ajax在頁面上直接調用Web Api。現在我們在客戶端中增加一個頁面,在這個頁面上使用Ajax訪問Web Api。
在IDS4Client這個項目Views/Home目錄下增加一個視圖JSClient.cshtml,代碼如下:
@using Microsoft.AspNetCore.Authentication
@{
var auth = await Context.AuthenticateAsync();
var token = auth.Properties.Items[".Token.access_token"];
}
<div id="result"">
</div>
@section Scripts
{
<script>
$(document).ready(function(){
$.ajax({
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Bearer " + "@token");
},
url: "http://localhost:5153/WeatherForecast",
type: 'get',
success: function (res) {
console.log(res);
for(var i=0;i<res.length;i++){
$("#result").append("<div>" +res[i].date + " : " + res[i].temperatureC + "</div>");
}
alert("success");
},
error: function (err) {
console.log(err);
alert(err.statusText);
}
});
});
</script>
}
代碼很簡單,直接了當。我們從當前上下文中獲取Access Token,在Ajax的beforeSend中使用token進行認證,后面的訪問部分沒有什么特殊的。
在HomeController中增加下面的代碼:
public IActionResult JSClient()
{
return View();
}
同時運行客戶端和Web Api,登錄后訪問https://localhost:7002/Home/JSClient,看一下效果。不出意外的話,應該報錯,我們會發現CORS錯誤,也就是從瀏覽器中使用Ajax直接訪問Web Api受到跨域訪問的限制。這需要我們對Web Api進行修改,增加對跨域訪問的支持:
builder.Services.AddCors(option => option.AddPolicy("cors",
policy => policy.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials()
.WithOrigins(new[] { "https://localhost:7002" })));
... ...
app.UseCors("cors");
重新運行,這次可以了:

這種解決方案是基於MVC或者Razor Page模式應用的典型方案,雖然客戶端采用Ajax訪問Web Api,但認證和token獲取實際上是在后台完成的,這是典型的授權碼模式。我們可以回顧一下本系列第二部分授權碼模式的工作過程,現在已經完整實現並驗證了整個過程。
上面的示例雖然使用Ajax訪問Web Api,但需要后台完成認證和token的獲取,真正的單頁面應用沒有后台參與這些過程。下一步我們看一下如果使用JS在前端完成整個流程。
