【.NET Core】ASP.NET Core之IdentityServer4(1):快速入门
本文中的IdentityServer4基于上节的jenkins 进行docker自动化部署。
使用了MariaDB,EF Core,AspNetIdentity,Docker
Demo地址:https://sso.neverc.cn
Demo源码:https://github.com/NeverCL/Geek.IdentityServer4
简介
OpenID Connect :常用的认证协议有SAML2p, WS-Federation and OpenID Connect – SAML2p。OpenID Connect是其中最新的协议。
OAuth 2.0 :OAuth 2.0 是一种授权协议。通过Access Token可以访问受保护的API接口。
OpenID Connect和OAuth 2.0非常相似,实际上,OpenID Connect是OAuth 2.0之上的一个扩展。
身份认证和API访问这两个基本的安全问题被合并为一个协议 - 往往只需一次往返安全令牌服务。
IdentityServer4基于ASP.NET Core 2对这两种协议的实现。
支持规范:https://identityserver4.readthedocs.io/en/release/intro/specs.html
关键词
IdentityServer:提供OpenID Connect and OAuth 2.0 protocols.
User:IdentityServer中的用户
Client:第三方应用,包括web applications, native mobile or desktop applications, SPAs etc.
Resource:包含Identity data 和 APIs。这是认证授权中的标识。
Identity Token:标识认证信息,至少包含user的sub claim。
Access Token:标识授权信息,可以包含Client 和 user的claim信息。
授权方式
Client Credentials
Client Credentials是最简单的一种授权方式。
步骤:
- 创建IdentityServer
- 定义APIs
- 定义Client
- 创建API
- 定义Authentication
- 使用Client
- 请求Token
- 使用Token
IdentityServer:
dotnet new web -o Geek.IdentityServer4 && dotnet add Geek.IdentityServer4 package IdentityServer4
Startup:
services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddInMemoryApiResources(Config.GetApiResources())
.AddInMemoryClients(Config.GetClients());
...
app.UseIdentityServer();
Config:
public static IEnumerable<ApiResource> GetApiResources()
{
return new List<ApiResource>
{
new ApiResource("api1")
};
}
public static IEnumerable<Client> GetClients()
{
return new List<Client>
{
new Client
{
ClientId = "client",
AllowedGrantTypes = GrantTypes.ClientCredentials,
ClientSecrets = { new Secret("secret".Sha256()) },
Claims = { new Claim("name","名称") },
AllowedScopes = { "api1" }
},
}
}
API:
dotnet new web -o Geek.Api && dotnet add Geek.Api package IdentityServer4.AccessTokenValidation
Startup:
services.AddMvc();
services.AddAuthentication("Bearer")//AddIdentityServerAuthentication 默认SchemeName:Bearer
.AddIdentityServerAuthentication(opt =>
{
opt.ApiName = "api1";
opt.Authority = "https://sso.neverc.cn";
});
...
app.UseAuthentication();
app.UseMvc();
Controller:
[Route("identity")]
[Authorize]
public class IdentityController : ControllerBase
{
[HttpGet]
public IActionResult Get()
{
return new JsonResult(from c in User.Claims select new { c.Type, c.Value });
}
}
Client:
dotnet new web -o Geek.Client && dotnet add Geek.Client package IdentityServer4.IdentityModel
Program:
var disco = await DiscoveryClient.GetAsync("https://sso.neverc.cn");
var tokenClient = new TokenClient(disco.TokenEndpoint, "client", "secret");
var tokenResponse = await tokenClient.RequestClientCredentialsAsync("api1");
var client = new HttpClient();
client.SetBearerToken(tokenResponse.AccessToken);
var response = await client.GetAsync("http://localhost:5001/identity");
var content = await response.Content.ReadAsStringAsync();
Console.WriteLine(JArray.Parse(content));
ResourceOwnerPassword
这种认证方式需要User提供用户名和密码,所以Client为非常可信的应用才可能使用这种方式。
步骤:
- 定义RO Client 和 User
- 使用Client
Identity Server
Config:
public static IEnumerable<Client> GetClients()
{
...
new Client
{
ClientId = "ro.client",
AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,
ClientSecrets = { new Secret("secret".Sha256()) },
AllowedScopes = { "api1" }
}
}
public static List<TestUser> GetUsers()
{
return new List<TestUser>
{
new TestUser
{
SubjectId = "1",
Username = "alice",
Password = "password",
}
}
}
Startup:
services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddInMemoryApiResources(Config.GetApiResources())
.AddInMemoryClients(Config.GetClients())
.AddTestUsers(Config.GetUsers());
Client
var disco = await DiscoveryClient.GetAsync("https://sso.neverc.cn");
var tokenClient = new TokenClient(disco.TokenEndpoint, "ro.client", "secret");
var tokenResponse = await tokenClient.RequestResourceOwnerPasswordAsync("alice", "password", "api1");
var client = new HttpClient();
client.SetBearerToken(tokenResponse.AccessToken);
var response = await client.GetAsync("http://localhost:5001/identity");
var content = await response.Content.ReadAsStringAsync();
Console.WriteLine(JArray.Parse(content));
区分Client Credentials 和 ResourceOwnerPassword 可通过 sub claim来区分
Implicit
Implicit为隐式模式,通过浏览器端直接传输id_token
步骤:
- 配置IdentityServer
- 定义IdentityResources
- 定义mvc client
- 添加Mvc UI
- 创建mvc client
IdentityServer
public static IEnumerable<IdentityResource> GetIdentityResources()
{
return new List<IdentityResource>
{
new IdentityResources.OpenId(),
new IdentityResources.Profile()
};
}
...
new Client
{
ClientId = "mvc",
ClientName = "MVC Client",
AllowedGrantTypes = GrantTypes.Implicit,
ClientSecrets = { new Secret("secret".Sha256()) },
RedirectUris = { "http://localhost:5002/signin-oidc" },
PostLogoutRedirectUris = { "http://localhost:5002/signout-callback-oidc" },
AllowedScopes = new List<string>
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
}
}
services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddInMemoryApiResources(Config.GetApiResources())
.AddInMemoryClients(Config.GetClients())
.AddTestUsers(Config.GetUsers())
.AddInMemoryIdentityResources(Config.GetIdentityResources());
添加MvcUI:
在IdentityServer项目中powershell执行:
iex ((New-Object System.Net.WebClient).DownloadString('https://raw.githubusercontent.com/IdentityServer/IdentityServer4.Quickstart.UI/release/get.ps1'))
MvcClient
public void ConfigureServices(IServiceCollection services)
{
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
services.AddMvc();
services.AddAuthentication(options =>
{
options.DefaultScheme = "Cookies";
options.DefaultChallengeScheme = "oidc";
})
.AddCookie("Cookies")
.AddOpenIdConnect("oidc", options =>
{
options.SignInScheme = "Cookies";
options.Authority = "https://sso.neverc.cn";
options.ClientId = "mvc";
options.SaveTokens = true;
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseAuthentication();
app.UseMvcWithDefaultRoute();
}
public class HomeController : ControllerBase
{
[Authorize]
public ActionResult Index()
{
return new JsonResult(from c in User.Claims select new { c.Type, c.Value });
}
}
Hybrid
在Implicit方式中,id_token在浏览器中传输是适用的,但是access_token不应该暴露在浏览器中。
Hybrid模式则是在Implicit的基础上,再传输code,适用code模式来获取access_token。
步骤:
- 定义Client
- 使用Client
IdentityServer配置
Config:
new Client
{
ClientId = "hybrid",
AllowedGrantTypes = GrantTypes.Hybrid,
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"
},
};
MvcClient配置
Startup:
.AddOpenIdConnect("oidc", options =>
{
options.SignInScheme = "Cookies";
options.Authority = "https://sso.neverc.cn";
options.ClientId = "mvc";
options.ClientSecret = "secret";
options.ResponseType = "code id_token";
options.SaveTokens = true;
options.Scope.Add("api1");
});
Controller:
public async Task<IActionResult> CallApiUsingUserAccessToken()
{
var accessToken = await HttpContext.GetTokenAsync("access_token");
var client = new HttpClient();
client.SetBearerToken(accessToken);
var content = await client.GetStringAsync("http://localhost:5001/identity");
ViewBag.Json = JArray.Parse(content).ToString();
return View("json");
}
在登录完成后,即可通过认证得到的access_token调用CallApiUsingUserAccessToken来调用API服务。
总结
本文为IdentityServer4做了基本的介绍。
实际上IdentityServer4还可以非常灵活的与ASP.NET Identity 以及 EF Core等组合使用。
另外基于ASP.NET Core,所以IdentityServer4也支持跨平台。
【.NET Core】ASP.NET Core之IdentityServer4(1):快速入门的更多相关文章
- .NET Core & ASP.NET Core 1.0在Redhat峰会上正式发布
众所周知,Red Hat和微软正在努力使.NET Core成为Red Hat企业版Linux (RHEL)系统上的一流开发平台选项.这个团队已经一起工作好几个月了,RHEL对.NET有许多需求.今天在 ...
- .NET Core & ASP.NET Core 1.0
.NET Core & ASP.NET Core 1.0在Redhat峰会上正式发布 众所周知,Red Hat和微软正在努力使.NET Core成为Red Hat企业版Linux (RHEL) ...
- Do You Kown Asp.Net Core -- Asp.Net Core 2.0 未来web开发新趋势 Razor Page
Razor Page介绍 前言 上周期待已久的Asp.Net Core 2.0提前发布了,一下子Net圈热闹了起来,2.0带来了很多新的特性和新的功能,其中Razor Page引起我的关注,作为web ...
- ASP.NET Core 配置 Entity Framework Core - ASP.NET Core 基础教程 - 简单教程,简单编程
原文:ASP.NET Core 配置 Entity Framework Core - ASP.NET Core 基础教程 - 简单教程,简单编程 ASP.NET Core 配置 Entity Fram ...
- .NET Core ASP.NET Core Basic 1-2 控制反转与依赖注入
.NET Core ASP.NET Core Basic 1-2 本节内容为控制反转与依赖注入 简介 控制反转IOC 这个内容事实上在我们的C#高级篇就已经有所讲解,控制反转是一种设计模式,你可以这样 ...
- [.NET Core]ASP.NET Core中如何解决接收表单时的不支持的媒体类型(HTTP 415 Unsupported Media Type)错误呢?
[.NET Core]ASP.NET Core中如何解决接收表单时的不支持的媒体类型(HTTP 415 Unsupported Media Type)错误呢? 在ASP.NET Core应用程序中,接 ...
- 使用ASP.NET 构建 Web 应用程序快速入门-8小时的免费培训视频
- Scott Hanselman的中文博客[转载] [原文发表地址] Building Web Apps with ASP.NET Jump Start - 8 Hours of FREE Trai ...
- [译]初识.NET Core & ASP.NET Core
原文:点这 本文的源代码在此: ASP.NET From Scratch Sample on GitHub 你过你是.NET Core的入门者,你可以先看看下面这篇文章: ASP.NET and .N ...
- ASP.NET Core - ASP.NET Core MVC 的功能划分
概述 大型 Web 应用比小型 Web 应用需要更好的组织.在大型应用中,ASP.NET MVC(和 Core MVC)所用的默认组织结构开始成为你的负累.你可以使用两种简单的技术来更新组织方法并及时 ...
- 比较ASP.NET和ASP.NET Core[经典 Asp.Net v和 Asp.Net Core (Asp.Net Core MVC)]
ASP.NET Core是.与.Net Core FrameWork一起发布的ASP.NET 新版本,最初被称为ASP.NET vNext,有一系列的命名变化,ASP.NET 5.0,ASP.NET ...
随机推荐
- Android初级教程理论知识(第六章广播接受者)
总体概述: 广播接收者 现实中:电台要发布消息,通过广播把消息广播出去,使用收音机,就可以收听广播,得知这条消息 Android中:系统在运行过程中,会产生很多事件,那么某些事件产生时,比如:电量改变 ...
- Uva - 816 - Abbott's Revenge
这个迷宫问题还是挺好玩的,多加了一个转向的问题,有些路口不同的进入方式会有不同的转向限制,这个会比较麻烦一点,所以定义结点结构体的时候需要加一个朝向dir.总体来说是一道BFS求最短路的问题.最后打印 ...
- 管道模式——pipeline与valve
在一个比较复杂的大型系统中,假如存在某个对象或数据流需要被进行繁杂的逻辑处理的话,我们可以选择在一个大的组件中进行这些繁杂的逻辑处理,这种方式确实达到了目的,但却是简单粗暴的.或许在某些情况这种简单粗 ...
- [Android编程心得] Camera(OpenCV)自动对焦和触摸对焦的实现
写在前面 最近在从零开始写一个移动端的AR系统,坑实在是太多了!!!整个项目使用了OpenCV第三方库,但对于摄像机来说,和原生Camera的方法基本相同. 实现 以OpenCV的JavaCamera ...
- android smartbar适配
1.使用魅族的demo里的SmartBarUtils.java 2.在mainifest中的Application android:theme="@android:style ...
- OC内存管理-OC笔记
内存管理细节:http://blog.sina.com.cn/s/blog_814ecfa90102vus2.html 学习目标 1.[理解]内存管理 2.[掌握]第一个MRC程序 3.[掌握]内存管 ...
- python is not None
python 判空常用 XX is not None,但其实 not XX is None 也可以. http://stackoverflow.com/questions/2710940/pyth ...
- HTML入门笔记
HTML简介 HTML是做网页最基本的技术 1_由标签组件 2_在任何操作系统平台,只要有浏览器,都有执行HTML 3_浏览器中有HTML解析器 4_编辑HTML可以使用任何文本编辑工具,如记事本,建 ...
- QGIS编译
一.准备工作 1.下载QGIS源码 最新版本的QGIS源码需要从git上下载.最新的发布版是2.0,下载地址见下.https://github.com/qgis/QGIS/tree/release-2 ...
- 12_Android中HttpClient的应用,doGet,doPost,doHttpClientGet,doHttpClient请求,另外借助第三方框架实现网络连接的应用,
准备条件, 编写一个web项目.编写一个servlet,若用户名为lisi,密码为123,则返回"登录成功",否则"登录失败".项目名为ServerIth ...