OpenID 配置步骤
允许客户端基于授权服务器执行的身份验证来验证最终用户的身份,以及以可互操作和类似REST的方式获取关于最终用户的基本配置文件信息。
创建一个MVC客户端
1.新建一个ASP.NET Core MVC应用程序
2.配置 OpenID Connect 认证
在类Startup
的 ConfigureServices
方法中添加以下代码:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(); JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); services.AddAuthentication(options =>
{
options.DefaultScheme = "Cookies";
options.DefaultChallengeScheme = "oidc";
})
.AddCookie("Cookies")
.AddOpenIdConnect("oidc", options =>
{
options.SignInScheme = "Cookies"; options.Authority = "http://localhost:5000";
options.RequireHttpsMetadata = false; options.ClientId = "mvc";
options.SaveTokens = true;
});
}
AddAuthentication将认证服务添加到依赖注入容器中,使用Cookie作为验证用户的主要方法(通过"Cookies"
作为 DefaultScheme
)。
DefaultChallengeScheme 设置为"oidc"
(OIDC是OpenID Connect的简称),因为当我们需要用户登录时,我们将使用OpenID Connect方案。
然后我们使用AddCookie
添加可以处理Cookie的处理程序。
最后,AddOpenIdConnect
用于配置执行OpenID Connect协议的处理程序。Authority
表示id4服务的地址。 然后我们通过ClientId
识别该客户端。SignInScheme
用于在OpenID Connect协议完成后使用cookie处理程序发出cookie。 而SaveTokens
用于在Cookie中保存IdentityServer中的令牌(稍后将需要)。
然后确保在每个请求上执行认证服务,在Startup
中的Configure
方法添加UseAuthentication
:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
} app.UseAuthentication(); app.UseStaticFiles();
app.UseMvcWithDefaultRoute();
}
验证中间件应该在MVC之前添加。
最后一步是触发认证。为了进入HomeController,并在其中一个Action上添加特性[Authorize]
还要修改该Action的View以显示用户的信息,例如:
<dl>
@foreach (var claim in User.Claims)
{
<dt>@claim.Type</dt>
<dd>@claim.Value</dd>
}
</dl>
如果您现在使用浏览器访问HomeController,将会导致重定向到IdentityServer,这将导致错误,因为MVC客户端尚未注册。
添加OpenID Connect Identity Scopes的支持
与OAuth 2.0类似,OpenID Connect也使用Scopes概念。 再次,Scopes代表您想要保护的客户端希望访问的内容。 与OAuth相反,OIDC中的范围不代表API,而是代表用户ID,姓名或电子邮件地址等身份信息。
在Config.cs
中添加如下代码:
public static IEnumerable<IdentityResource> GetIdentityResources()
{
return new List<IdentityResource>
{
new IdentityResources.OpenId(),
new IdentityResources.Profile(),
};
}
所有标准Scopes及其相应的声明都可以在OpenID Connect规范中找到。
然后,您需要将这些身份资源添加到Startup.cs中的IdentityServer配置中。使用AddInMemoryIdentityResources
扩展方法调用AddIdentityServer()
:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(); // configure identity server with in-memory stores, keys, clients and scopes
services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddInMemoryIdentityResources(Config.GetIdentityResources())
.AddInMemoryApiResources(Config.GetApiResources())
.AddInMemoryClients(Config.GetClients())
.AddTestUsers(Config.GetUsers());
}
为OpenID Connect implicit flow 添加客户端
Implicit Flow指的是使用OAuth2的Implicit流程获取Id Token和Access Token
最后一步是将MVC客户端的配置添加到IdentityServer。
基于OpenID Connect的客户端与我们迄今添加的OAuth 2.0客户端非常相似。 但是由于OIDC中的流程始终是交互式的,我们需要在配置中添加一些重定向URL。
将以下内容添加到您的客户端配置:
public static IEnumerable<Client> GetClients()
{
return new List<Client>
{
// other clients omitted... // OpenID Connect implicit flow client (MVC)
new Client
{
ClientId = "mvc",
ClientName = "MVC Client",
AllowedGrantTypes = GrantTypes.Implicit, // where to redirect to after login
RedirectUris = { "http://localhost:5002/signin-oidc" }, // where to redirect to after logout
PostLogoutRedirectUris = { "http://localhost:5002/signout-callback-oidc" }, AllowedScopes = new List<string>
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile
}
}
};
}
测试客户端
通过访问受保护的Action来触发身份验证握手。 你应该看到重定向到IdentityServer的登录页面。
成功登录后,用户将看到同意画面。 在这里,用户可以决定是否要将他的身份信息发布到客户端应用程序。
可以使用客户端对象上的RequireConsent属性以每个客户端为基础关闭同意询问。
最后浏览器重定向到客户端应用程序,该应用程序显示了用户的声明。
在开发过程中,您有时可能会看到一个异常,说明令牌无法验证。 这是因为签名密钥信息是即时创建的,并且只保存在内存中。 当客户端和IdentityServer不同步时,会发生此异常。 只需在客户端重复操作,下次元数据已经追上,一切都应该正常工作。
添加注销
最后一步是给MVC客户端添加注销功能。
使用IdentityServer等身份验证服务,仅清除本地应用程序Cookie是不够的。 此外,您还需要往身份服务器交互,以清除单点登录会话。
确切的协议步骤在OpenID Connect中间件内实现,只需将以下代码添加到某个控制器即可触发注销:
public async Task Logout()
{
await HttpContext.SignOutAsync("Cookies");
await HttpContext.SignOutAsync("oidc");
}
这将清除本地cookie,然后重定向到IdentityServer。 IdentityServer将清除它的cookie,然后给用户一个链接返回到MVC应用程序。
进一步实验
如上所述,OpenID Connect中间件默认要求配置 profile scope。 这个scope还包括像名字或网站这样的声明。
让我们将这些声明添加到用户,以便IdentityServer可以将它们放入身份令牌中:
public static List<TestUser> GetUsers()
{
return new List<TestUser>
{
new TestUser
{
SubjectId = "",
Username = "alice",
Password = "password", Claims = new []
{
new Claim("name", "Alice"),
new Claim("website", "https://alice.com")
}
},
new TestUser
{
SubjectId = "",
Username = "bob",
Password = "password", Claims = new []
{
new Claim("name", "Bob"),
new Claim("website", "https://bob.com")
}
}
};
}
下一次您进行身份验证时,你的声明页面现在将显示额外的声明。
OpenID Connect中间件上的Scope属性是您配置哪些Scope将在身份验证期间发送到IdentityServer。
值得注意的是,对令牌中身份信息的遍历是一个扩展点 - IProfileService。因为我们正在使用 AddTestUser,所以默认使用的是 TestUserProfileService。你可以检出这里的源代码来查看它的工作原理。
Demo下载地址
参考官方文档:https://identityserver4.readthedocs.io/en/release/quickstarts/3_interactive_login.html
官方的Demo已经更新到最新的.NET Core 2.0
OpenID 配置步骤的更多相关文章
- .net 4.0+ 应用接入openid Server步骤
.net 4.0+ 应用接入openid Server步骤: Requirements:Microsoft.AspNet.Mvc 5.2.4+ 1 确认应用是否是katana启动(项目引用了owin, ...
- log4j.properties 详解与配置步骤
一.log4j.properties 的使用详解 1.输出级别的种类 ERROR.WARN.INFO.DEBUGERROR 为严重错误 主要是程序的错误WARN 为一般警告,比如session丢失IN ...
- log4j.properties 详解与配置步骤(转)
找的文章,供参考使用 转自 log4j.properties 详解与配置步骤 一.log4j.properties 的使用详解 1.输出级别的种类 ERROR.WARN.INFO.DEBUGERROR ...
- MySQL数据库集群进行正确配置步骤
MySQL数据库集群进行正确配置步骤 2010-06-09 10:47 arrowcat 博客园 字号:T | T 我们今天是要和大家一起分享的是对MySQL数据库集群进行正确配置,我前两天在相关网站 ...
- Apache安装配置步骤
注释:这里以Linux 红帽商业版为例~~~~~~~纯手打啊 Apache安装配置步骤 准备:关闭其他虚拟设备 #/etc/init.d/libvirtd stop #/etc/init.d/xend ...
- Windows Live Writer配置步骤
推荐文档: [超详细教程]使用Windows Live Writer 2012和Office Word 2013 发布文章到博客园全面总结 Live Writer 使用小贴示:发博客时始终使用图片原始 ...
- 获取微信openID 的步骤
获取微信openid的步骤:1.进入-->判断openID是否为空: 空-->$url=urlencode("http://xxx/xxx.php");//回调链接 $ ...
- Oracle 11g客户端在Linux系统上的配置步骤详解
Oracle 11g客户端在Linux系统上的配置步骤详解 2011-07-26 10:47 newhappy2008 CSDN博客 字号:T | T 本文我们主要介绍了Oracle 11g客户端在L ...
- jenkins 邮件配置步骤
一.进行系统管理中的邮件配置步骤: 1.设置Extended E-mail Notification 二.对构建的job 添加邮件发送的步骤: 3.成功截图:
随机推荐
- element-ui table中排序 取消表格默认排序问题
sortTable 设置为 custom 一定要设置在列上
- leetcode-algorithms-8 String to Integer (atoi)
leetcode-algorithms-8 String to Integer (atoi) Implement atoi which converts a string to an integer. ...
- hpu_newoj_1028-exgcd
The Elevator 描述 全是电梯. Philo正处于高度为0的一个平台上,在他面前的一个平面,全是上上下下的电梯. Philo想要离开这里,请你帮帮他. 电梯世界规则:这里的电梯所能到达的 ...
- SQLServer清空表
TRUNCATE TABLE TABLE_NAME 这个不记日志. delete table table_name 这个记日志 drop table table_name 删除表 TRUNCATE 语 ...
- vue组件通信&&v兄弟组件通信eventbus遇到的问题(多次触发、第一次不触发)
组件通讯包括:父子组件间的通信和兄弟组件间的通信.在组件化系统构建中,组件间通信必不可少的 (vuex以后再说). 父组件--> 子组件 1. 属性设置 父组件关键代码如下: <templ ...
- utf8mb4与utf8的区别
今天在测试小程序保存表情时,数据库插入数据时报错ER_TRUNCATED_WRONG_VALUE_FOR_FIELD: Incorrect string value: '\xF0\x9F\x98\x8 ...
- How to import a GitHub project into Eclipse
Assuming you have created a project in GitHub, these are the steps to import it into Eclipse. First, ...
- css 让div 的高度和屏幕的高度一样
<html><head><title>无标题文档</title><style type="text/css">html, ...
- JS--理解参数,argument,重载
ECMAScript函数的参数与大多数其他语言函数的参数不同.ECMAScript函数不介意传递进来多少个参数,也不在乎传递进来的参数是什么数据类型. 原由在于,ECMAScript中的参数在内部是用 ...
- zabbix3.4.7集成grafana详细步骤
打开官方网站下载grafana并安装 wget https://s3-us-west-2.amazonaws.com/grafana-releases/release/grafana-5.0.4-1. ...