在本快速入门中,将对通过OpenID Connect协议进行的交互式用户身份验证的支持添加到上一章中构建的IdentityServer中。

实现后,我们将创建一个将使用IdentityServer进行身份验证的MVC应用程序。

本文假设已创建《IdentityServer4 (IDS4) 快速入门》一文中的IdentityServer服务项目,将修改部分配置以支持带UI的MVC客户端。

系统环境与上文相同。

一、添加UI

从QuickStart\src\IdentitySever目录,运行以下命令。

dotnet new is4ui

运行此命令后将在IdentityServer项目中增加支持UI模版, 添加MVC UI后,还需要在DI系统和管道中启用MVC。当您查看时,Startup.cs您会在ConfigureServices和Configure方法中找到注释,这些注释告诉您如何启用MVC。

你可以在IdentityServer项目中看到新增了wwwroot、Views目录和一些支持文件。

二、创建一个MVC客户端

从QuickStart\src目录下,运行以下命令。

dotnet new mvc -n MvcClient
cd ..
dotnet sln add .\src\MvcClient\MvcClient.csproj

添加依赖包,在src\MvcClient目录下运行

dotnet add package Microsoft.AspNetCore.Authentication.OpenIdConnect

打开MvcClient项目,在startup.cs文件中添加代码,修改完成后如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System.IdentityModel.Tokens.Jwt;namespace MvcClient
{public class Startup{public Startup(IConfiguration configuration){Configuration = configuration;}public IConfiguration Configuration { get; }// This method gets called by the runtime. Use this method to add services to the container.public void ConfigureServices(IServiceCollection services){services.AddControllersWithViews();JwtSecurityTokenHandler.DefaultMapInboundClaims = false;services.AddAuthentication(options =>{options.DefaultScheme = "Cookies";options.DefaultChallengeScheme = "oidc";}).AddCookie("Cookies").AddOpenIdConnect("oidc", options =>{options.Authority = "https://localhost:5001";options.ClientId = "mvc";options.ClientSecret = "secret";options.ResponseType = "code";options.SaveTokens = true;});}// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.public void Configure(IApplicationBuilder app, IWebHostEnvironment env){if (env.IsDevelopment()){app.UseDeveloperExceptionPage();}else{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.UseAuthorization();app.UseEndpoints(endpoints =>{endpoints.MapControllerRoute(name: "default",pattern: "{controller=Home}/{action=Index}/{id?}");});*/app.UseStaticFiles();app.UseRouting();app.UseAuthentication();app.UseAuthorization();app.UseEndpoints(endpoints =>{endpoints.MapDefaultControllerRoute().RequireAuthorization();});}}
}

AddAuthentication 将身份验证服务添加到依赖注入DI。

使用一个Cookie在本地登录的用户(通过"Cookies"DefaultScheme),和设定的DefaultChallengeSchemeoidc,因为当我们需要用户登录,我们将使用ID连接协议。

然后AddCookie,我们使用添加可以处理cookie的处理程序。

最后,AddOpenIdConnect用于配置执行OpenID Connect协议的处理程序。该Authority指示了信任令牌服务所在。然后,我们通过ClientId和标识此客户ClientSecret。 SaveTokens用于将来自IdentityServer的令牌保留在cookie中

还需要修改Views\Home\index.cshtml主视图以显示用户的声明以及cookie属性:

@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>

三、修改IdentityServer服务端

1、添加对OpenID Connect Identity Scope的支持

修改config.cs文件,通过修改以下属性来添加对标准openid(主题ID)和profile(名字,姓氏等)范围的支持:

 public static IEnumerable<IdentityResource> IdentityResources =>new IdentityResource[]{ new IdentityResources.OpenId(),new IdentityResources.Profile(),};

startup.cs文件ConfigureServices中位置向IdentityServer注册身份资源:

 var builder = services.AddIdentityServer(options =>{// see https://identityserver4.readthedocs.io/en/latest/topics/resources.htmloptions.EmitStaticAudienceClaim = true;}).AddInMemoryIdentityResources(Config.IdentityResources).AddInMemoryApiScopes(Config.ApiScopes).AddInMemoryClients(Config.Clients);

2、添加测试用户

示例UI还带有一个内存中的“用户数据库”。可以通过添加AddTestUsers扩展方法在IdentityServer中启用它:

  var builder = services.AddIdentityServer(options =>{// see https://identityserver4.readthedocs.io/en/latest/topics/resources.htmloptions.EmitStaticAudienceClaim = true;}).AddInMemoryIdentityResources(Config.IdentityResources).AddInMemoryApiScopes(Config.ApiScopes).AddInMemoryClients(Config.Clients).AddTestUsers(TestUsers.Users);

3、将MVC客户端添加到IdentityServer配置

修改config.cs文件,客户端列表应如下所示:

public static IEnumerable<Client> Clients =>new List<Client>{// machine to machine client (from quickstart 1)new Client{ClientId = "client",ClientSecrets = { new Secret("secret".Sha256()) },AllowedGrantTypes = GrantTypes.ClientCredentials,// scopes that client has access toAllowedScopes = { "api1" }},// interactive ASP.NET Core MVC clientnew Client{ClientId = "mvc",ClientSecrets = { new Secret("secret".Sha256()) },AllowedGrantTypes = GrantTypes.Code,// where to redirect to after loginRedirectUris = { "https://localhost:5002/signin-oidc" },// where to redirect to after logoutPostLogoutRedirectUris = { "https://localhost:5002/signout-callback-oidc" },AllowedScopes = new List<string>{IdentityServerConstants.StandardScopes.OpenId,IdentityServerConstants.StandardScopes.Profile}}};

四、测试运行

修改MvcClient项目launchSettings.json文件,将运行端口设为5002(5001已被IdentityServer占用)

    "MvcClient": {"commandName": "Project","dotnetRunMessages": "true","launchBrowser": true,"applicationUrl": "https://localhost:5002","environmentVariables": {"ASPNETCORE_ENVIRONMENT": "Development"}}

先运行IdentityServer项目,然后运行MvcClient,再访问 https://localhost:5002

输入TestUsers中的用户名和密码 ,则可以看到从IdentityServer中取得的token。

五、其他实验测试

六、参考文章

https://identityserver4.readthedocs.io/en/latest/quickstarts/2_interactive_aspnetcore.html

IdentityServer4 (IDS4) UI界面使用相关推荐

  1. 解决cocos2dx 3.x 导入cocostudio的ui界面出现错位问题

    笔者今天发现导入cocostudio的ui界面时,会有部分控件出现错位的现象,后来我看了一下源码,发现是部分控件是没有继承 Layout类,导致不能设置控件位置造成,原因可以看看cocos2dx 源码 ...

  2. UI培训教程分享:APP启动页UI界面设计

    本期为大家分享的ui培训教程是关于APP启动页面的UI设计方面,作为一名合格的UI设计师,APP产品的启动页是需要会的,下面就来看看详细的教程吧. UI培训教程分享:APP启动页UI界面设计 启动页面 ...

  3. qt ui界面无法移动控件_使用qt 键盘上的方向键只能控制ui界面上的按钮选择,不能实现我设定的功能...

    已结贴√ 问题点数:20 回复次数:2 使用qt 键盘上的方向键只能控制ui界面上的按钮选择,不能实现我设定的功能 我做的是一个贪吃蛇游戏,现在我想实现的功能是:按下键盘上的上下左右箭头的方向按键时, ...

  4. 用Cocos Studio 2.3.2制作UI界面中控件不再支持运行3d动作特效

    用Cocos Studio 2.3.2制作UI界面中控件不再支持运行3d动作特效  cocos2d-x + cocos studio无疑是当下二维手游开发的利器,但是在从旧版本向新版本的升级过程中,坑 ...

  5. NGUI 学习笔记实战——制作商城UI界面

    Unity3D的uGUI听说最近4.6即将推出,但是目前NGUI等UI插件大行其道并且已经非常成熟,所以我们还是先看眼前吧. 一.实现思想 商城的功能是很多游戏都拥有的,按下一个界面按钮,弹出一个窗体 ...

  6. 在Service中通过WindowManger添加View的方式来把UI界面显示出来

    整体方案 在Service中通过WindowManger添加View的方式来把UI界面显示出来 业务场景 具体场景 IQOO手机,游戏辅助 这种场景能否使用Activity方式来做 使用activit ...

  7. [UI] 精美UI界面欣赏[1]

    精美UI界面欣赏[1] 转载于:https://www.cnblogs.com/YouXianMing/p/4199520.html

  8. C#/.NET基于Topshelf创建Windows服务的守护程序作为服务启动的客户端桌面程序不显示UI界面的问题分析和解决方案

    C#/.NET基于Topshelf创建Windows服务的守护程序作为服务启动的客户端桌面程序不显示UI界面的问题分析和解决方案 参考文章: (1)C#/.NET基于Topshelf创建Windows ...

  9. 如果你不习惯新版的 Github 的 UI 界面,可以试试这款插件

    微软现在大搞副业,就是不肯在 Windows 系统上下功夫,最近又改了 GitHub UI 布局设计.核心思想是好的,利用了屏幕的宽度,首屏展示了更多的信息,元素设计上也更现代了一些.好看不好看不说, ...

最新文章

  1. 业界首个实时多目标跟踪系统开源
  2. 【Java代码实现】递归两大经典问题-----“汉诺塔问题” 与 “青蛙跳台阶问题” 讲解
  3. 一个新游戏的思路;大家来说说看,觉得好的话,我做成游戏
  4. 网络营销专员浅析网络营销优化对企业来说意味着什么?
  5. sun game server (sgs)初探
  6. 1625 宝石项链 大视野评测
  7. SAP Spartacus界面看不到Carousel左右移动控件的一个可能原因
  8. 985硕博士:你为什么比我差?
  9. 金错刀:“打工皇帝”唐骏的职场潜规则
  10. 脚本之家python专题_一个简单的python读写文件脚本
  11. 1.1 print输出语句(Python)
  12. AXURE 8.1.0.3382 有效激活码
  13. 【AI志愿超强攻略】中国高校人工智能专业最全院校排名课程对比
  14. VScode Remote SSH连接失败
  15. 高性能初级维修电工及技能考核实训装置
  16. 将视频截取成图片的C++代码
  17. 12306 验证码验证流程
  18. 禁止vite打包时将rgba转为16进制
  19. 学生管理系统的mysql数据库设计_MySQL数据库--学生管理系统数据库设计
  20. 阿里巴巴java开发手册-泰山版 下载

热门文章

  1. 实现 swiper 的左右箭头放到外面,定制箭头的样式
  2. H5+ app自动更新思路
  3. Hi3536音频单声道改双声道
  4. webclient学习1.webclient是什么?
  5. Labview和西门子PLC smart200 OPC通讯仪器串口通讯
  6. 解决 择色器选择的位置有偏差
  7. Axure 教程:知识竞赛/答题app、小程序原型
  8. UE4 虚幻引擎,更改源代码编辑器 Visual Studio ,Rider
  9. STM32 cubemx 开发系列文章(一)认识cubemx
  10. Mac 上的优秀 GTD 任务管理工具「Things3」