前面的部分:
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");


重新运行,这次可以了:
Identity Server 4 从入门到落地(五)—— 使用Ajax访问Web Api-LMLPHP

这种解决方案是基于MVC或者Razor Page模式应用的典型方案,虽然客户端采用Ajax访问Web Api,但认证和token获取实际上是在后台完成的,这是典型的授权码模式。我们可以回顾一下本系列第二部分授权码模式的工作过程,现在已经完整实现并验证了整个过程。

上面的示例虽然使用Ajax访问Web Api,但需要后台完成认证和token的获取,真正的单页面应用没有后台参与这些过程。下一步我们看一下如果使用JS在前端完成整个流程。

12-04 21:20