前言:

 前面介绍了IdentityServer4 的简单应用,本篇将继续讲解IdentityServer4 的各种授权模式使用示例

授权模式:

 环境准备

 a)调整项目结构如下:

  

 b)调整cz.IdentityServer项目中Statup文件如下 

public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews(); services.Configure<CookiePolicyOptions>(options =>
{
options.MinimumSameSitePolicy = SameSiteMode.Strict;
}); services.AddIdentityServer()
.AddDeveloperSigningCredential()
//api资源
.AddInMemoryApiResources(InMemoryConfig.GetApiResources())
//4.0版本需要添加,不然调用时提示invalid_scope错误
.AddInMemoryApiScopes(InMemoryConfig.GetApiScopes())
.AddTestUsers(InMemoryConfig.Users().ToList())
.AddInMemoryIdentityResources(InMemoryConfig.GetIdentityResourceResources())
.AddInMemoryClients(InMemoryConfig.GetClients());
} // 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();
} app.UseRouting(); app.UseStaticFiles();
app.UseCookiePolicy();
app.UseIdentityServer(); app.UseAuthentication();
//使用默认UI,必须添加
app.UseAuthorization(); app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(name: "default", pattern: "{controller=Home}/{action=Index}/{id?}");
});
  }
}

 c)在cz.Api.Order项目中添加控制器:IdentityController

namespace cz.Api.Order.Controllers
{
[Route("identity")]
[ApiController]
[Authorize]
public class IdentityController : ControllerBase
{
[HttpGet]
public IActionResult Get()
{
return new JsonResult(from c in User.Claims select new { c.Type, c.Value });
}
}
}

 1、客户端模式

  a)在InMemoryConfigGetClients方法中添加客户端:

new Client
{
ClientId = "credentials_client", //访问客户端Id,必须唯一
ClientName = "ClientCredentials Client",
//使用客户端授权模式,客户端只需要clientid和secrets就可以访问对应的api资源。
AllowedGrantTypes = GrantTypes.ClientCredentials,
ClientSecrets =
{
new Secret("secret".Sha256())
},
AllowedScopes = {
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
"goods"
},
},

  b)在cz.ConsoleClient项目中安装Nuget包:IdentityModel,在Program中添加如下方法:

/// <summary>
/// 客户端认证模式
/// </summary>
private static void ClientCredentials_Test()
{
Console.WriteLine("ClientCredentials_Test------------------->");
var client = new HttpClient();
var disco = client.GetDiscoveryDocumentAsync("http://localhost:5600/").Result;
if (disco.IsError)
{
Console.WriteLine(disco.Error);
return;
}
//请求token
var tokenResponse = client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest
{
Address = disco.TokenEndpoint,
ClientId = "credentials_client",
ClientSecret = "secret",
Scope = "goods"
}).Result; if (tokenResponse.IsError)
{
Console.WriteLine(tokenResponse.Error);
return;
} Console.WriteLine(tokenResponse.Json);
//调用认证api
var apiClient = new HttpClient();
apiClient.SetBearerToken(tokenResponse.AccessToken); var response = apiClient.GetAsync("http://localhost:5601/identity").Result;
if (!response.IsSuccessStatusCode)
{
Console.WriteLine(response.StatusCode);
}
else
{
var content = response.Content.ReadAsStringAsync().Result;
Console.WriteLine(content);
}
}

  运行该程序结果如下:

  

 2、密码模式

  a)在InMemoryConfigGetClients方法中添加客户端:

new Client
{
ClientId = "password_client",
ClientName = "Password Client",
ClientSecrets = new [] { new Secret("secret".Sha256()) },
//这里使用的是通过用户名密码换取token的方式.
AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,
AllowedScopes = {
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
"order","goods",
}
},

  b)cz.ConsoleClient项目继续在Program中添加如下方法:

/// <summary>
/// 用户名密码模式
/// </summary>
public static void ResourceOwnerPassword_Test()
{
Console.WriteLine("ResourceOwnerPassword_Test------------------->");
// request token
var client = new HttpClient();
var disco = client.GetDiscoveryDocumentAsync("http://localhost:5600/").Result;
var tokenResponse = client.RequestPasswordTokenAsync(new PasswordTokenRequest()
{
Address = disco.TokenEndpoint,
ClientId = "password_client",
ClientSecret = "secret",
UserName = "cba",
Password = "cba",
Scope = "order goods",
}).Result; if (tokenResponse.IsError)
{
Console.WriteLine(tokenResponse.Error);
return;
}
Console.WriteLine(tokenResponse.Json);
// call api
var apiClient = new HttpClient();
client.SetBearerToken(tokenResponse.AccessToken);
var response = apiClient.GetAsync("http://localhost:5601/identity").Result;
if (!response.IsSuccessStatusCode)
{
Console.WriteLine(response.StatusCode);
}
else
{
var content = response.Content.ReadAsStringAsync().Result;
Console.WriteLine(content);
}
}

  运行该程序结果同上:  

 3、简化模式

  a)在InMemoryConfigGetClients方法中添加客户端:

new Client
{
ClientId = "implicit_client",
ClientName = "Implicit Client",
ClientSecrets = new [] { new Secret("secret".Sha256()) },
AllowedGrantTypes = GrantTypes.Implicit,
AllowedScopes = {
"order","goods",
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile
},
RedirectUris = { "http://localhost:5021/signin-oidc" },
PostLogoutRedirectUris = { "http://localhost:5021" },
//是否显示授权提示界面
RequireConsent = true,
},

  b)调整在cz.MVCClient中Statup文件中内容如下:

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.Configure<CookiePolicyOptions>(options =>
{
  // This lambda determines whether user consent for non-essential cookies is needed for a given request.
  options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy =
SameSiteMode.Lax;
});
JwtSecurityTokenHandler.DefaultMapInboundClaims = false; services.AddControllersWithViews(); services.AddAuthentication(options =>
{
options.DefaultScheme = "Cookies";
options.DefaultChallengeScheme = "oidc";
})
.AddCookie("Cookies")
.AddOpenIdConnect("oidc", options =>
{
options.RequireHttpsMetadata = false;
options.Authority = "http://localhost:5600";
options.ClientId = "implicit_client";
options.ClientSecret = "secret"
;
});

} // 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");
}
app.UseStaticFiles();
app.UseCookiePolicy(); app.UseRouting(); app.UseAuthentication();
app.UseAuthorization(); app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}

  c)在cz.MVCClient中添加Nuget包:IdentityServer4.AccessTokenValidation、Microsoft.AspNetCore.Authentication.OpenIdConnect;在HomeController中添加方法:

[Authorize]
public IActionResult Secure()
{
ViewData["Message"] = "Secure page."; return View();
}
//注销
public IActionResult Logout()
{
return SignOut("oidc", "Cookies");
}

  d)界面调整:

   在_Layout.cshtml文件中添加导航按钮:Secure、Logout   

<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Secure">Secure</a>
</li>
@if (User.Identity.IsAuthenticated)
{
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Logout">Logout</a>
</li>
}

   添加视图:Secure.cshtml文件:

@{
ViewData["Title"] = "Secure";
} <h2>@ViewData["Title"]</h2> <h3>User claims</h3> <dl>
@foreach (var claim in User.Claims)
{
<dt>@claim.Type</dt>
<dd>@claim.Value</dd>
}
</dl>

  e)运行结果如下:

  

  简化模式还支持在Js客户端中运行可以查看官方说明文档:https://identityserver4.readthedocs.io/en/latest/quickstarts/4_javascript_client.html

 4、授权码模式

  a)在InMemoryConfigGetClients方法中添加客户端:

new Client
{
ClientId = "code_client",
ClientName = "Code Client",
ClientSecrets = new [] { new Secret("secret".Sha256()) },
AllowedGrantTypes = GrantTypes.Code,
RedirectUris = { "http://localhost:5021/signin-oidc" },
PostLogoutRedirectUris = { "http://localhost:5021/signout-callback-oidc" },
  //是否显示授权提示界面
RequireConsent= true,
AllowedScopes = {
"order","goods",
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile
}
},

  b)调整在cz.MVCClient中Statup文件中ConfigureServices方法内容如下:

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{ services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.Lax;
}); JwtSecurityTokenHandler.DefaultMapInboundClaims = false; services.AddControllersWithViews(); services.AddAuthentication(options =>
{
options.DefaultScheme = "Cookies";
options.DefaultChallengeScheme = "oidc";
})
.AddCookie("Cookies")
.AddOpenIdConnect("oidc", options =>
{
options.RequireHttpsMetadata = false;
options.Authority = "http://localhost:5600";
options.ClientId = "code_client";
options.ClientSecret = "secret";
options.ResponseType = "code";
options.SaveTokens = true;
options.Scope.Add("order");
options.Scope.Add("goods");
options.GetClaimsFromUserInfoEndpoint = true
;
});

}

  c)运行结果如下:同简化模式运行效果相同

 5、混合模式(Hybrid)

a)在InMemoryConfigGetClients方法中添加客户端:

new Client
{
ClientId = "hybrid_client",
ClientName = "Hybrid Client",
ClientSecrets = new [] { new Secret("secret".Sha256()) },
AllowedGrantTypes = GrantTypes.Hybrid,
//是否显示授权提示界面
RequireConsent = true,
AllowedScopes = {
"order","goods",
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile
}
}

  b)调整在cz.MVCClient中Statup文件中ConfigureServices方法内容如下:

public void ConfigureServices(IServiceCollection services)
{ services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.Lax;
}); JwtSecurityTokenHandler.DefaultMapInboundClaims = false; services.AddControllersWithViews(); services.AddAuthentication(options =>
{
options.DefaultScheme = "Cookies";
options.DefaultChallengeScheme = "oidc";
})
.AddCookie("Cookies")
.AddOpenIdConnect("oidc", options =>
{
options.RequireHttpsMetadata = false;
options.Authority = "http://localhost:5600";
options.ClientId = "hybrid_client";
options.ClientSecret = "secret";
options.ResponseType = "code token id_token";
options.SaveTokens = true;
options.ResponseMode = "fragment";
options.GetClaimsFromUserInfoEndpoint = true;
options.Scope.Add("order");
options.Scope.Add("goods");
});
}

总结:

 应用场景总结

  • 客户端模式(Client Credentials):和用户无关,应用于应用程序与 API 资源之间的交互场景。
  • 密码模式:和用户有关,常用于第三方登录。
  • 简化模式:可用于前端或无线端。
  • 混合模式:推荐使用,包含 OpenID 认证服务和 OAuth 授权,针对的是后端服务调用。

 过程中遇到的坑:

  • Postman调用时总是提示:invalid_scope异常;

   解决:在添加IdentityServer服务时:调用AddInMemoryApiScopes方法注册Scope

  • MVC项目登录成功后跳转时,找不到http://localhost:5020/signin-oidc路径:

   解决:在Statup文件中添加services.Configure<CookiePolicyOptions>(options =>{options.CheckConsentNeeded = context => true;options.MinimumSameSitePolicy = SameSiteMode.Lax; });

  • 登录时授权界面展示展示:

   解决:客户端注册时,指定属性RequireConsent= true

Git地址:https://github.com/cwsheng/IdentityServer.Demo.git

认证授权:IdentityServer4 - 各种授权模式应用的更多相关文章

  1. 授权认证(IdentityServer4)

    区别 OpenId: Authentication :认证 Oauth: Aurhorize :授权 输入账号密码,QQ确认输入了正确的账号密码可以登录 --->认证 下面需要勾选的复选框(获取 ...

  2. IdentityServer4 (3) 授权码模式(Authorization Code)

    写在前面 1.源码(.Net Core 2.2) git地址:https://github.com/yizhaoxian/CoreIdentityServer4Demo.git 2.相关章节 2.1. ...

  3. IdentityServer4系列 | 授权码模式

    一.前言 在上一篇关于简化模式中,通过客户端以浏览器的形式请求IdentityServer服务获取访问令牌,从而请求获取受保护的资源,但由于token携带在url中,安全性方面不能保证.因此,我们可以 ...

  4. IdentityServer4 自定义授权模式

    IdentityServer4除了提供常规的几种授权模式外(AuthorizationCode.ClientCredentials.Password.RefreshToken.DeviceCode), ...

  5. .Net Core身份认证:IdentityServer4实现OAuth 2.0 客户端模式 - 简书

    原文:.Net Core身份认证:IdentityServer4实现OAuth 2.0 客户端模式 - 简书 一.客户端模式介绍 客户端模式(Client Credentials Grant)是指客户 ...

  6. (转)基于OWIN WebAPI 使用OAuth授权服务【客户端模式(Client Credentials Grant)】

    适应范围 采用Client Credentials方式,即应用公钥.密钥方式获取Access Token,适用于任何类型应用,但通过它所获取的Access Token只能用于访问与用户无关的Open ...

  7. 基于 IdentityServer3 实现 OAuth 2.0 授权服务【客户端模式(Client Credentials Grant)】

    github:https://github.com/IdentityServer/IdentityServer3/ documentation:https://identityserver.githu ...

  8. 基于OWIN WebAPI 使用OAuth授权服务【客户端模式(Client Credentials Grant)】

    适应范围 采用Client Credentials方式,即应用公钥.密钥方式获取Access Token,适用于任何类型应用,但通过它所获取的Access Token只能用于访问与用户无关的Open ...

  9. ASP.NET Core 认证与授权[5]:初识授权

    经过前面几章的姗姗学步,我们了解了在 ASP.NET Core 中是如何认证的,终于来到了授权阶段.在认证阶段我们通过用户令牌获取到用户的Claims,而授权便是对这些的Claims的验证,如:是否拥 ...

  10. OAuth2.0学习(1-6)授权方式3-密码模式(Resource Owner Password Credentials Grant)

    授权方式3-密码模式(Resource Owner Password Credentials Grant) 密码模式(Resource Owner Password Credentials Grant ...

随机推荐

  1. 看完就能掌握的PHP核心技术 - ​​​​​​​​面向对象

    继承和多态 类的组合与继承 假设我们有两个类,一个 person,另外一个是 family:在 family 类中我们创建 person 类中的对象,并且我们把这个对象视为 family 类的一个属性 ...

  2. Android 禁止ViewPager左右滑动的功能实现

    来来来,各位看官~ Look here!!! Android    禁止ViewPager左右滑动的功能实现!! I think it`s so easy,无需重写ViewPager!!! JUST ...

  3. centos7.8 安装部署 k8s 集群

    centos7.8 安装部署 k8s 集群 目录 centos7.8 安装部署 k8s 集群 环境说明 Docker 安装 k8s 安装准备工作 Master 节点安装 k8s 版本查看 安装 kub ...

  4. Ceph Luminous手动解决pg分布不均衡问题

    原文链接: https://www.jianshu.com/p/afb6277dbfd6 1.设置集群仅支持 Luminous(或者L之后的)客户端 具体命令: ceph osd set-requir ...

  5. Lambda 表达式推演全过程

    Java 的 Lambda 表达式推演过程: 第一步:正常的类实现(外部实现),new一个对象,然后重写方法实现 public class TestLambda3 { public static vo ...

  6. jmeter参数化之 【CSV Data Set Config/CSV数据配置文件】

    这里以登录功能为例: 1.新建.txt文件,将参数值写入到txt文件中(多个参数值如:用户名,密码 之间以逗号隔开),将文件放置在想要放置的目录下 2.添加csv数据文件设置 右键线程组->添加 ...

  7. soso官方:网页分类技术介绍

    http://www.wocaoseo.com/thread-190-1-1.html 1.    技术背景     分类问题是人类所面临的一个非常重要且具有普遍意义的问题.将事物正确的分类,有助于人 ...

  8. 符合SEO的网站标题应该怎么写

    http://www.wocaoseo.com/thread-96-1-1.html 的seo网站标题既能提起读者的点击欲望,又能搜索引擎中获得好的排名,这两着之间有着有有一些联系,网站的标题若要从s ...

  9. 建设开发者生态:6项华为API管理原则落地

    摘要: 为了向开发者提供良好.一致.稳定的华为API的体验,华为通过明确“API管理六项原则”,来支持开发者生态建设. 一个不开放的组织,会慢慢成为一潭僵水,一个封闭的系统,能量最终会耗尽,在产品开发 ...

  10. Git使用感悟

    前言 分支介绍 我们现在开发的分支一般是这样的(基于上面那张图片的): master:上线用的 dev:开发用的 featature_xxx:开发用的 test:测试用的 hotfix:修复bug的 ...