IdentityServer4专题之七:Authorization Code认证模式
(1)identityserver4授权服务器端
public static class Config
{
public static IEnumerable<IdentityResource> GetIdentityResources()
{
return new IdentityResource[]
{
new IdentityResources.OpenId(),
new IdentityResources.Profile(),
new IdentityResources.Email(),
new IdentityResources.Phone(),
new IdentityResources.Address(),
};
}
public static IEnumerable<ApiResource> GetApis()
{
return new ApiResource[]
{
new ApiResource("api1", "My API #1")
};
}
public static IEnumerable<Client> GetClients()
{
return new[]
{
new Client
{
ClientId="mvc client",
ClientName="ASP.NET Core MVC Client",
AllowedGrantTypes=GrantTypes.CodeAndClientCredentials,
ClientSecrets={new Secret( "mvc secret".Sha256())},
RedirectUris={"http://localhost:5002/signin-oidc"},
FrontChannelLogoutUri="http://localhost:5002/signout-oidc",
PostLogoutRedirectUris={"http://localhost:5002/signout-callback-oidc"},
AlwaysIncludeUserClaimsInIdToken=true,//将用户所有的claims包含在IdToken内
AllowOfflineAccess=true,//offline_access,其实指的是能否用refreshtoken重新申请令牌
AllowedScopes =
{
"api1",
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
IdentityServerConstants.StandardScopes.Address,
IdentityServerConstants.StandardScopes.Phone,
IdentityServerConstants.StandardScopes.Email
}
}
};
}
}
(2)客户端,还是需要安装IdentityModel库,
在startup.cs的ConfigurServices一节,需要做如下添加:
//关闭默认映射,否则它可能修改从授权服务返回的各种claim属性
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
//添加认证服务,并设置其有关选项
services.AddAuthentication(options =>
{
//客户端应用设置使用"Cookies"进行认证
options.DefaultScheme =CookieAuthenticationDefaults.AuthenticationScheme ;
//identityserver4设置使用"oidc"进行认证
options.DefaultChallengeScheme =OpenIdConnectDefaults.AuthenticationScheme ;
}).AddCookie(CookieAuthenticationDefaults.AuthenticationScheme)
//对使用的OpenIdConnect进行设置,此设置与Identityserver的config.cs中相应client配置一致才可能登录授权成功
.AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options=> {
options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.Authority = "http://localhost:5000";
options.RequireHttpsMetadata = false;
options.ClientId = "mvc client";
options.ClientSecret = "mvc secret";
options.SaveTokens = true;
options.ResponseType = "code";
options.Scope.Clear();
options.Scope.Add("api1");
options.Scope.Add(OidcConstants.StandardScopes.OpenId);//"openid"
options.Scope.Add(OidcConstants.StandardScopes.Profile);//"profile"
options.Scope.Add(OidcConstants.StandardScopes.Address);
options.Scope.Add(OidcConstants.StandardScopes.Email);
options.Scope.Add(OidcConstants.StandardScopes.Phone);
// 与identity server的AllowOfflineAccess=true,对应。offline_access,指的是能否用refreshtoken重新申请令牌
options.Scope.Add(OidcConstants.StandardScopes.OfflineAccess);
});
在Confiure一节,app.UseMvc之前添加如下内容:
app.UseAuthentication();
然后,在controller中使用时,按如下方式: 通常需如下引用
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using IdentityModel.Client;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using MvcClient.Models;
//获取AccessToken、IdToken、RefreshToken时:
[Authorize]
public async Task<IActionResult> Privacy()
{
var accessToken = await HttpContext.GetTokenAsync(OpenIdConnectParameterNames.AccessToken);
var idToken = await HttpContext.GetTokenAsync(OpenIdConnectParameterNames.IdToken);
var refreshToken = await HttpContext.GetTokenAsync(OpenIdConnectParameterNames.RefreshToken);
var authorizationCode = await HttpContext.GetTokenAsync(OpenIdConnectParameterNames.Code);
ViewData["idToken"] = idToken;
ViewData["refreshToken"] = refreshToken;
ViewData["accessToken"] = accessToken;
return View();
}
//访问Api资源时
public async Task<IActionResult> AccessApi()
{
var client = new HttpClient();
var disco = await client.GetDiscoveryDocumentAsync("http://localhost:5000");
ViewData["disco"] = disco.Error;
if (disco.IsError)
{
ViewData["disco"] = disco.Error;
return View();
}
var accessToken = await HttpContext.GetTokenAsync(OpenIdConnectParameterNames.AccessToken);
client.SetBearerToken(accessToken);
var response = await client.GetAsync("http://localhost:5001/api/values");
if (!response.IsSuccessStatusCode)
{
ViewData["response_error"] = response.StatusCode;
return View();
}
ViewData["response-content"] = await response.Content.ReadAsStringAsync();
return View();
}
从客户端及identityserver4登出时:
public async Task<IActionResult> Logout()
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
await HttpContext.SignOutAsync(OpenIdConnectDefaults.AuthenticationScheme);
return View();
}
如果登出需要跳转回到客户端应用网站,则需在将IdentityServer4的命名空间IdentityServer4.Quickstart.UI下的AccountOptions类中
public static bool AutomaticRedirectAfterSignOut = true;
这样,从identityserver登出后,将自动跳转到客户应用页面。
IdentityServer4专题之七:Authorization Code认证模式的更多相关文章
- 微信支持的Authorization code授权模式(公众号开发)(开放平台资料中心中的代公众号发起网页授权)
链接:https://blog.csdn.net/ASZJBGD/article/details/82838356 主要流程分为两步: 1.获取code 2.通过code换取accesstoken 流 ...
- OAuth2.0和企业内部统一登录,token验证方式,OAuth2.0的 Authorization code grant 和 Implicit grant区别
统一登录是个很多应用系统都要考虑的问题,多个项目的话最好前期进行统一设计,否则后面改造兼容很麻烦: cas认证的方式:新公司都是老项目,用的是cas认证的方式,比较重而且依赖较多,winform的项目 ...
- OAuth2.0安全设计之Authorization Code
OAuth 2.0 有 4 种认证流程: 授权码模式(authorization code) 简化模式(implicit) 密码模式(resource owner password credentia ...
- IdentityServer4 (3) 授权码模式(Authorization Code)
写在前面 1.源码(.Net Core 2.2) git地址:https://github.com/yizhaoxian/CoreIdentityServer4Demo.git 2.相关章节 2.1. ...
- asp.net权限认证:OWIN实现OAuth 2.0 之授权码模式(Authorization Code)
asp.net权限认证系列 asp.net权限认证:Forms认证 asp.net权限认证:HTTP基本认证(http basic) asp.net权限认证:Windows认证 asp.net权限认证 ...
- 基于OWIN WebAPI 使用OAUTH2授权服务【授权码模式(Authorization Code)】
之前已经简单实现了OAUTH2的授权码模式(Authorization Code),但是基于JAVA的,今天花了点时间调试了OWIN的实现,基本就把基于OWIN的OAUHT2的四种模式实现完了.官方推 ...
- IdentityServer4之Authorization Code(授权码)相对更安全
前言 接着授权模式聊,这次说说Authorization Code(授权码)模式,熟悉的微博接入.微信接入.QQ接入都是这种方式(这里说的是oauth2.0的授权码模式),从用户体验上来看,交互方式和 ...
- OAuth2.0学习(1-4)授权方式1-授权码模式(authorization code)
参与者列表: (1) Third-party application:第三方应用程序,又称客户端(client),如:"云冲印".社交应用. (2)HTTP service:HTT ...
- .Net Core身份认证:IdentityServer4实现OAuth 2.0 客户端模式 - 简书
原文:.Net Core身份认证:IdentityServer4实现OAuth 2.0 客户端模式 - 简书 一.客户端模式介绍 客户端模式(Client Credentials Grant)是指客户 ...
随机推荐
- 寒假pta二
整除光棍 这里所谓的“光棍”,并不是指单身汪啦~ 说的是全部由1组成的数字,比如1.11.111.1111等.传说任何一个光棍都能被一个不以5结尾的奇数整除.比如,111111就可以被13整除. 现在 ...
- 吴裕雄--天生自然Numpy库学习笔记:NumPy 副本和视图
副本是一个数据的完整的拷贝,如果我们对副本进行修改,它不会影响到原始数据,物理内存不在同一位置. 视图是数据的一个别称或引用,通过该别称或引用亦便可访问.操作原有数据,但原有数据不会产生拷贝.如果我们 ...
- 在tomcat启动时解析xml文件,获取特定标签的属性值,并将属性值设置到静态变量里
这里以解析hibernate.cfg.xml数据库配置信息为例,运用dom4j的解析方式来解析xml文件. 1.在javaWeb工程里新建一个java类,命名为GetXmlValue.java,为xm ...
- DBC的故事(二)
上篇介绍了MSB和LSB,此篇介绍更复杂的:有符号和无符号数. 1.信号符号 CAN信号有其物理意义,如温度.扭矩等,这些信号是有负值的,常见的解决方案有2种: 1)把offset设成负值 如温度of ...
- centos610最小安装之后 后续设置
1.网络配置 centos选择最小桌面(如果不用到类似Oracle需要用到桌面的软件,则操作系统安装最小化安装)安装之后 查看网络配置如下: 截图显示网络并未启用. 2.开启网络设置 cd /etc/ ...
- MySQL高级 InnoDB 和 MyISAM 的区别
InnoDB:支持事务处理等不加锁读取支持外键支持行锁不支持FULLTEXT类型的索引不保存表的具体行数,扫描表来计算有多少行DELETE 表时,是一行一行的删除InnoDB 把数据和索引存放在表空间 ...
- java集合体系结构总结
好,首先我们根据这张集合体系图来慢慢分析.大到顶层接口,小到具体实现类. 首先,我想说为什么要用集合?简单的说:数组长度固定,且是同种数据类型.不能满足需求.所以我们引入集合(容器)来存储任意数据类型 ...
- Python3.5学习之旅——day3
本节内容: 1.字符串操作 2.字典操作 3.集合 4.文件操作 5.字符编码与转码 6.函数与函数式编程 一.字符串操作 name='kobe' name.capitalize() 首字母大写 na ...
- 【快学springboot】SpringBoot整合Mybatis Plus
原创声明 本文首发于头条号[Happyjava].Happy的掘金地址:https://juejin.im/user/5cc2895df265da03a630ddca,Happy的个人博客:http: ...
- PAT T1019 Separate the Animals
暴力搜索加剪枝,二进制保存状态,set去重~ #include<bits/stdc++.h> using namespace std; ; string s[maxn]; struct n ...