Identity Server 4 从入门到落地(三)—— 创建Web客户端

书接上回,我们已经搭建好了基于Identity Server 4的认证服务和管理应用(如果还没有搭建,参看本系列前两部分,相关代码可以从github下载:https://github.com/zhenl/IDS4Admin )。
现在我们来创建Web客户端。基本上可以按照Identity Server官网教程来: https://identityserver4.readthedocs.io/en/latest/quickstarts/2_interactive_aspnetcore.html 。只不过我使用的是.Net 6,代码上有少许出入。
首先创建一个Asp.Net Core Web项目,使用MVC项目模板,在创建时选择不需要身份认证。然后引入程序包 Microsoft.AspNetCore.Authentication.OpenIdConnect。
接下来修改Program.cs,.Net 6引入了简洁模式,代码看上去有些不同。

using System.IdentityModel.Tokens.Jwt;

var builder = WebApplication.CreateBuilder(args);

//增加的代码
JwtSecurityTokenHandler.DefaultMapInboundClaims = false;

builder.Services.AddAuthentication(options =>
{
    options.DefaultScheme = "Cookies";
    options.DefaultChallengeScheme = "oidc";
})
    .AddCookie("Cookies")
    .AddOpenIdConnect("oidc", options =>
    {
        options.Authority = "http://localhost:4010";
        options.RequireHttpsMetadata = false;
        options.ClientId = "myclient";
        options.ClientSecret = "secret";
        options.ResponseType = "code";
        options.Scope.Add("openid");
        options.Scope.Add("profile");
        options.GetClaimsFromUserInfoEndpoint = true;
        options.SaveTokens = true;
    });
//增加结束

// Add services to the container.
builder.Services.AddControllersWithViews();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();
app.UseAuthentication(); //增加的代码
app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}")
    .RequireAuthorization(); //增加的代码

app.Run();

增加的代码进行了注释。需要注意的是,由于我们的测试认证服务器运行在http://localhost:4010,没有使用HTTPS协议,所以增加了options.RequireHttpsMetadata = false。
还需要修改lanuch.json中的代码,将项目改变为自启动项目,不依赖IIS Express:

{
  "profiles": {
    "IDS4Client": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": true,
      "applicationUrl": "https://localhost:7002;http://localhost:5002",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

最后,修改Index.cshtml,显示用户信息:

@{
    ViewData["Title"] = "Home Page";
}
@using Microsoft.AspNetCore.Authentication

<h2>Claims</h2>

<dl>
    @foreach (var claim in User.Claims)
    {
        <dt>@claim.Type</dt>
        <dd>@claim.Value</dd>
    }
</dl>

<h2>Properties</h2>

<dl>
    @foreach (var prop in (await Context.AuthenticateAsync()).Properties.Items)
    {
        <dt>@prop.Key</dt>
        <dd>@prop.Value</dd>
    }
</dl>

客户端就编写完成了,然后使用管理应用(我这里是http://localhost:4003)向认证服务的数据库中增加这个客户端的定义。设置项很多,可以参考现有的管理客户端进行设置,也可以克隆现有的客户端进行修改。主要的设置是基本信息和认证注销部分,特别注意别忘了设置客户端密钥,并且密钥需要与客户端代码中的相同,还有就是允许作用域也要和代码中的相同。这两部分的截图如下:


设置完成后,访问这个客户端http://localhost:7002,会重定位到认证服务器提示登录,登录后,会出现下面的界面:

同意确认后,回到我们需要访问的界面:

最后,增加登出链接,将这个链接增加到_Layout.chstml中,在菜单代码下面增加这个链接:


                    <ul class="navbar-nav">
                        <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Logout">Logout</a>
                    </ul>

简化起见,我们在HomeController中增加登出代码,很简单:

       public IActionResult Logout()
        {
            return SignOut("Cookies", "oidc");
        }

到此,采用Identity Server 4进行认证管理的Web客户端就初步搭建完成了。下一步,我们需要搭建一个受Identity Server 4 保护的Web Api。

上述代码可以github下载: https://github.com/zhenl/IDS4ClientDemo,喜欢的话给个star。

posted @ 2021-12-02 16:29  寻找无名的特质  阅读(2400)  评论(7编辑  收藏  举报