基于IdentityServer4的单点登录——IdentityServer
1.新建项目并添加引用
新建一个asp .net core 2.0的项目
引用IdentityServer4.AspNetIdentity
2.定义资源
新建Config.cs文件,定义Api资源与Identity资源
资源分为身份资源(Identity resources)和API资源(API resources)
(1)身份资源(Identity resources)
身份资源是用户的用户名,姓名或电子邮件地址等数据。身份资源具有唯一的名称,可以为其分配任意声明类型。然后,这些声明将被包含在用户的身份令牌中。客户端将使用scope参数来请求访问身份资源。
身份资源可以是IdentityServer自带的资源,也可以是自定义的资源。
public static IEnumerable<IdentityResource> GetIdentityResources()
{
//自定义身份资源
var customProfile = new IdentityResource(
name: "custom.profile",
displayName: "Custom profile",
claimTypes: new[] { "name", "email", "status" });
return new List<IdentityResource>
{
//IdentityServer自带的资源
new IdentityResources.OpenId(),
new IdentityResources.Profile(),
customProfile
};
}
(2)API资源(API resources)
API资源是客户端访问API获得的资源
public static IEnumerable<ApiResource> GetApiResources()
{
return new List<ApiResource>
{
//具有单一范围的简单API(在这种情况下,范围名称与api名称相同)
new ApiResource("api1", "My API"),
// 扩展版本,更多的设置选项
new ApiResource
{
Name = "api2",
// 用于内部校验的密码
// ApiSecrets是用于内部校验的,API的名称(Name)和密码(ApiSecrets)可以用于认证
ApiSecrets =
{
new Secret("secret".Sha256())
},
// 在访问令牌中包含以下内容(除了subject ID)
// UserClaims表示用户声明
UserClaims = { JwtClaimTypes.Name, JwtClaimTypes.Email },
// // 该API定义了两个范围
Scopes =
{
new Scope()
{
Name = "api2.full_access",
DisplayName = "Full access to API 2",
},
new Scope
{
Name = "api2.read_only",
DisplayName = "Read only access to API 2"
}
}
}
};
}
3.定义客户端Client
客户端指想要访问资源的Client
public static IEnumerable<Client> GetClients()
{
return new List<Client>
{
//不一定要配置得这么复杂,根据需求来
new Client
{
ClientId = "mvc",
ClientName = "MVC Client",
AllowedGrantTypes = GrantTypes.HybridAndClientCredentials,
RequireConsent = true,
ClientSecrets =
{
new Secret("secret".Sha256())
},
//这里配置客户端的网址,多个客户端则是多个网址
RedirectUris = { "http://localhost:5002/signin-oidc" },
PostLogoutRedirectUris = { "http://localhost:5002/signout-callback-oidc" },
//允许的范围
AllowedScopes =
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
"api1"
},
AllowOfflineAccess = true
}
};
}
其他配置请参阅:
https://identityserver4.readthedocs.io/en/release/topics/clients.html
4.配置
把资源信息和客户端信息交给IdentityServer
public void ConfigureServices(IServiceCollection services)
{
//配置服务
services.AddIdentityServer()
//读取客户端列表
.AddInMemoryClients(Clients.Get())
//读取身份资源列表
.AddInMemoryIdentityResources(Resources.GetIdentityResources())
//读取API资源列表
.AddInMemoryApiResources(Resources.GetApiResources())
//设置临时签名凭据
.AddDeveloperSigningCredential()
//添加测试用户
.AddTestUsers(TestUsers.Users);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
//配置管道:注意配置管道要写在路由的前面...
app.UseIdentityServer();
}
这里需要注意的是,以上的资源信息和客户端信息是存在内存中的,可以设置为读取数据库
参阅:https://identityserver4.readthedocs.io/en/release/quickstarts/8_entity_framework.html
5.多客户端的统一登录
(1)用户表
//ApplicationUser继承于IdentityUser,可以在此为用户表添加属性,字段
public class ApplicationUser : IdentityUser
{
}
(2)页面
<div class="col-md-4">
<section>
<form asp-route-returnurl="@ViewData["ReturnUrl"]" method="post">
<h4>Use a local account to log in.</h4>
<hr />
<div asp-validation-summary="All" class="text-danger"></div>
<div class="form-group">
<!--整个流程是根据邮箱进行注册和登录的-->
<label asp-for="Email"></label>
<input asp-for="Email" class="form-control" />
<span asp-validation-for="Email" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Password"></label>
<input asp-for="Password" class="form-control" />
<span asp-validation-for="Password" class="text-danger"></span>
</div>
<div class="form-group">
<div class="checkbox">
<label asp-for="RememberMe">
<input asp-for="RememberMe" />
@Html.DisplayNameFor(m => m.RememberMe)
</label>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-default">Log in</button>
</div>
<div class="form-group">
<p>
<a asp-action="ForgotPassword">Forgot your password?</a>
</p>
<p>
<a asp-action="Register" asp-route-returnurl="@ViewData["ReturnUrl"]">Register as a new user?</a>
</p>
</div>
</form>
</section>
</div>
(3)登录方法
这里是AspNet Identity的内容
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
if (ModelState.IsValid)
{
// 尝试登录
// 需要注意的是,这里没有对登录失败进行计数
// 为了在登录失败多次之后触发锁定用户,把lockoutOnFailure设置为true
var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
_logger.LogInformation("User logged in.");
return RedirectToLocal(returnUrl);
}
if (result.RequiresTwoFactor)
{
return RedirectToAction(nameof(LoginWith2fa), new { returnUrl, model.RememberMe });
}
if (result.IsLockedOut)
{
_logger.LogWarning("User account locked out.");
return RedirectToAction(nameof(Lockout));
}
else
{
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return View(model);
}
}
return View(model);
}
6.设置IdentityServer项目的端口号为5000
7.其他
整个流程还需要包括注册,注销,忘记密码,第三方登录,修改用户信息等,这些不属于IdentityServer的讨论范畴,在此不做讨论
基于IdentityServer4的单点登录——IdentityServer的更多相关文章
- 基于IdentityServer4的单点登录——项目基本结构与流程
组成 IdentityServer,Api和Client(客户端,asp .net core)本文以官方demo:https://github.com/IdentityServer/IdentityS ...
- 基于IdentityServer4的单点登录——Client
以MvcClient项目为例 1.新建项目并添加引用 新建一个asp .net core 2.0的项目引用IdentityModel 2.配置 比之前的控制台客户端多这个步骤,需要配置这个客户端的Cl ...
- 基于IdentityServer4的单点登录——Api
1.新建项目并添加引用 新建一个asp .net core 2.0的项目引用IdentityServer4.AccessTokenValidation 2.配置 将Api与IdentityServer ...
- 基于SAML的单点登录介绍
http://blog.csdn.net/csethcrm/article/details/20694993 一.背景知识: SAML即安全断言标记语言,英文全称是Security Assertion ...
- 基于云端的通用权限管理系统,SAAS服务,基于SAAS的权限管理,基于SAAS的单点登录SSO,企业单点登录,企业系统监控,企业授权认证中心
基于云端的通用权限管理系统 SAAS服务 基于SAAS的权限管理 基于SAAS的单点登录SSO 基于.Net的SSO,单点登录系统,提供SAAS服务 基于Extjs 4.2 的企业信息管理系统 基于E ...
- 基于CAS的单点登录实战(2)-- 搭建cas的php客户端
在这之前已经搭好了CAS服务端 基于CAS的单点登录实战(1)-- 搭建cas服务器 PHP-Client php-Client是官方支持的,去官网下个最新版就好了.phpCAS 接入很简单,解压放到 ...
- (转)基于SAML的单点登录介绍
转:http://www.cnblogs.com/zsuxiong/archive/2011/11/19/2255497.html 一.背景知识: SAML即安全断言标记语言,英文全称是Securit ...
- abp集成IdentityServer4和单点登录
在abp开发的系统后,需要使用这个系统作单点登录,及其他项目登录账号依靠abp开发的系统.在官方文档上只找到作为登录服务Identity Server Integration,但是host项目却无法使 ...
- IdentityServer4实现单点登录统一认证
什么是单点登录统一认证:假如某公司旗下有10个网站(比如各种管理网站:人事系统啊,财务系统啊,业绩系统啊等),我是该公司一管理员或者用户,按照传统网站模式是这样:我打开A网站 输入账号密码 然后进入到 ...
随机推荐
- Android 带文字的图片分享
这里也记录下上下文,因为做了一个失物招领的App,当有人上交了失物之后,可以将这个消息分享出去,这个消息内容有物品的信息和图片,而微信SDK始终无法做到,就想着把物品信息嵌入到图片中分享出去,先放一个 ...
- mysql使用substring_index达到splite功能
函数: 1.从左开始截取字符串 left(str, length) 说明:left(被截取字段,截取长度) 例:select left(content,200) as abstract from my ...
- Hibernate之HQL检索(查询)方式
HQL(Hibernate Query Language)是面向对象的查询语言,与SQL非常相似.在Hibernate中,HQL是使用最广泛的检索方式. 具有下面经常使用功能: (1)在查询语句中,能 ...
- 【u026】房间最短路问题
描述 在一个长宽均为10,入口出口分别为(0,5).(10,5)的房间里,有几堵墙,每堵墙上有两个缺口,求入口到出口的最短路经. 格式 输入格式 第一排为n(n<=20),墙的数目. 接下来n排 ...
- 【HDU5748】Bellovin
Description Peter has a sequence and he define a function on the sequence -- , where is the length ...
- 【codeforces 755C】PolandBall and Forest
time limit per test1 second memory limit per test256 megabytes inputstandard input outputstandard ou ...
- Elasticsearch v5.4
在Windows上安装Elasticsearch v5.4.2 前言 最近项目里为了加快后台系统的搜索速度,决定接入开源的搜索引擎,于是大家都在对比较常用的几个开源做技术调研,比如Lucene+盘 ...
- Java设计模式菜鸟系列(二十二)中介者模式建模与实现
转载请注明出处:http://blog.csdn.net/lhy_ycu/article/details/40027109 中介者模式(Mediator):主要用来减少类与类之间的耦合的,由于假设类与 ...
- 【17.69%】【codeforces 659F】Polycarp and Hay
time limit per test4 seconds memory limit per test512 megabytes inputstandard input outputstandard o ...
- Codeforces C. Pattern 412 解决问题的方法
这个问题是比较暴力的法律主体. 主要是检查每一个是否没有使用足够的?.假设优先使用其他的无论是什么字母,假设你一定不能使用?. 找一个有能力并给予所有的字符串匹配字符串,而且采用的最小?号码. 原标题 ...