Core篇——初探IdentityServer4(客户端模式,密码模式)

目录

1、Oatuth2协议的客户端模式介绍
2、IdentityServer4客户端模式实现
3、Oatuth2协议的密码模式介绍
4、IdentityServer4密码模式实现

Oatuth2协议的客户端模式介绍

    • Client Credentials Grant (客户端模式)是Oauth2.0协议中,四种模式自建单的一种。它由两部分构成,客户端认证服务器。认证服务器确认客户端无误后返回一个token,客户端请求带着token访问资源。(一般使用场景是在一个安全的环境下,例如我的同一个系统中,一个api请求另外一个api)。

    • 这里借用下阮一峰老师画的图(博客地址=》http://www.ruanyifeng.com/blog/2014/05/oauth_2_0.html)

IdentityServer4客户端模式实现

  • 首先我们创建一个core的api项目作为认证服务器,添加nuget程序包IdentityServer4,将启动端口设置为5000
  • 接下来添加一个类,取名字叫做Config,我们用它来初始化Identityserver(配置要保护的资源和可以访问该API的客户端服务器)。
    代码如下:
/// <summary>
/// Idnetity配置,初始化Identityserver
/// </summary>
public class Config
{
//定义要保护的资源(webapi)
public static IEnumerable<ApiResource> GetApiResources()
{
return new List<ApiResource>
{
new ApiResource("api1", "My API")
};
}
//定义可以访问该API的客户端
public static IEnumerable<Client> GetClients()
{
return new List<Client>
{
new Client()
{
ClientId = "client",
AllowedGrantTypes = GrantTypes.ClientCredentials, //设置模式,客户端模式
ClientSecrets =
{
new Secret("secret".Sha256())
},
AllowedScopes = { "api1" }
}
};
}
}
  • 接下来配置startup,将资源和客户端的初始信息服务加入到DI容器,同时引用IdentityServer中间件。代码如下所示:
        public void ConfigureServices(IServiceCollection services)
{
services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddInMemoryApiResources(Config.GetApiResources()) //配置资源
.AddInMemoryClients(Config.GetClients()); //配置客户端
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
//使用identityserver中间件
app.UseIdentityServer();
app.UseMvc();
}
  • 再添加一个webapi项目,作为我们的资源服务器。添加nuget包,IdentityServer4.AccessTokenValidation,将启动端口设置为5001
  • 2、配置startup,添加认证服务器地址,和apiname &&引用中间件,代码如下:
        public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication("Bearer")
.AddIdentityServerAuthentication(options =>
{
options.Authority = "http://localhost:5000"; //配置Identityserver的授权地址
options.RequireHttpsMetadata = false; //不需要https
options.ApiName = "api1"; //api的name,需要和config的名称相同
});
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseAuthentication();// 添加认证中间件
app.UseMvc();
}
    • 将受保护资源controller添加[Authorize]。(因为资源服务器AddIdentityServerAuthentication 方法的参数和返回值都是AuthenticationBuilder(类似于一个中间件),所以可以多次调用AddIdentityServerAuthentication方法来控制这个api 资源可以让谁访问到。)
    • 最开始我们直接访问资源服务器的api,返回401,因为我们的资源被保护了。
    • 这时候来到IdentityServer4的官网,官网给出了这么一个地址=》
    • 我们访问这个地址时候,它会返回我们的Config配置=》
    • 其中有一个token_endpoint的url地址,我们带着Client的配置来访问它=》
    • 此时拿到Token,再带着token去访问我们的资源,争取获取到资源数据=》

Oatuth2协议的密码模式介绍

    • 用户会将用户名,密码给予客户端,但是客户端不保存此信息,客户端带着用户的密码请求认证服务器,认证服务器密码验证通过后后将token返回给客户端。
    • 这里借用下阮一峰老师画的图(博客地址=》http://www.ruanyifeng.com/blog/2014/05/oauth_2_0.html)

IdentityServer4密码模式实现

  • 我们不需要修改资源服务器,我们在客户端模式下的认证服务器的Config配置中,添加一个Client,允许我们使用密码模式访问授权服务器获取token,再添加一个测试用户。同时修改我们的startup,在ConfigureServices方法中配置测试用户,代码如下所示:
 //定义可以访问该API的客户端
public static IEnumerable<Client> GetClients()
{
return new List<Client>
{
new Client()
{
ClientId = "client",
AllowedGrantTypes = GrantTypes.ClientCredentials, //设置模式,客户端模式
ClientSecrets =
{
new Secret("secret".Sha256())
},
AllowedScopes = { "api1" }
},
new Client()
{
ClientId="pwdClient",
AllowedGrantTypes=GrantTypes.ResourceOwnerPassword, //密码模式
ClientSecrets= {new Secret("secret".Sha256()) },
AllowedScopes= { "api1" }
}
};
}
public static List<TestUser> GetTestUsers()
{
return new List<TestUser>
{
new TestUser
{
SubjectId="1",
Username="lmc",
Password="123456"
}
};
}
public void ConfigureServices(IServiceCollection services)
{
services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddInMemoryApiResources(Config.GetApiResources()) //配置资源
.AddInMemoryClients(Config.GetClients()) //配置客户端
.AddTestUsers(Config.GetTestUsers()); //配置测试用户
services.AddMvc();
}

此时我们使用我们定义的用户名和密码来访问我们的授权服务器(这里使用postman 要注意body的数据格式为x-www-form-urlencoded)=》

带着我们拿到的token,去访问资源=》

Core篇——初探IdentityServer4(客户端模式,密码模式)的更多相关文章

  1. Core篇——初探IdentityServer4(OpenID Connect模式)

    Core篇——初探IdentityServer4(OpenID Connect客户端验证) 目录 1.Oauth2协议授权码模式介绍2.IdentityServer4的OpenID Connect客户 ...

  2. OAuth2建立webapi认证服务供自己的客户端使用--密码模式

    场景:你自己实现了一套webApi,想供自己的客户端调用,又想做认证. 第一步:通过vs2015建立web api项目,Startup.cs,这个类将会作为Owin的启动类. 第二步:在webapi. ...

  3. Core篇——初探Core配置管理

    文章目录 1.命令行配置 2.Json文件配置 3.配置文件文本至C#对象实例的映射 4.配置文件热更新 5.总结 命令行的配置 我们首先来创建一个.net core 的控制台项目,然后引入.net ...

  4. Core篇——初探Core的认证,授权机制

    目录 1.Cookie-based认证的实现 2.Jwt Token 的认证与授权 3.Identity Authentication + EF 的认证 Cookie-based认证的实现 cooki ...

  5. Core篇——初探Core的Http请求管道&&Middleware

    目录: 1.Core 处理HTTP请求流程 2.中间件(Middleware)&&处理流程 3.创建自定义中间件&&模拟Core的请求管道 Core 处理HTTP请求流 ...

  6. Core篇——初探依赖注入

    目录 1.DI&&IOC简单介绍 2.UML类图中六种关联关系 3..net core 中DI的使用 4..net core DI初始化源码初窥 DI&&IOC简单介绍 ...

  7. IdentityServer4 密码模式认证

     授权服务器设置 添加用户 添加测试用户,也可以从数据库查 public static List<TestUser> GetTestUser() { return new List< ...

  8. Spring Security OAuth2 Demo —— 密码模式(Password)

    前情回顾 前几节分享了OAuth2的流程与授权码模式和隐式授权模式两种的Demo,我们了解到授权码模式是OAuth2四种模式流程最复杂模式,复杂程度由大至小:授权码模式 > 隐式授权模式 > ...

  9. 【ASP.NET Core分布式项目实战】(一)IdentityServer4登录中心、oauth密码模式identity server4实现

    本博客根据http://video.jessetalk.cn/my/course/5视频整理 资料 OAuth2 流程:http://www.ruanyifeng.com/blog/2014/05/o ...

随机推荐

  1. Reducing the Dimensionality of Data with Neural Networks:神经网络用于降维

    原文链接:http://www.ncbi.nlm.nih.gov/pubmed/16873662/ G. E. Hinton* and R. R. Salakhutdinov .   Science. ...

  2. XML-20100: (Fatal Error) Expected ';'. xml转word 导出时异常

    因为数据中包含特殊字符.需要进行转译. < < 小于号 > > 大于号 & & 和 &apos; ’ 单引号 " " 双引号 XML ...

  3. Apex语言(六)数组

    1.数组 数组能保存多个数据,每一个数据称为数组元素,元素的个数称为数组的长度. 数组元素的类型必须相同,元素的类型就是数组的类型. 数组元素在数组中都有一个编号,称为数组下标.下标从0开始编号,通过 ...

  4. 移动端自动化测试-WTF Appium

    手机App分为两大类,原生App(Native App)和混合APP(Hybrid App) 原生App(Native App) 原生App实际就是我们所常见的传统App开发模式,云端数据存储+App ...

  5. python-selenium,关于页面滑动

    第一种: #滑到底部 js="var q=document.documentElement.scrollTop=100000" driver.execut_script(js) 目 ...

  6. Linux的环境配置文件----.bashrc文件

    .bashrc文件主要保存个人的一些个性化设置,如命令别名.路径等.也即在同一个服务器上,只对某个用户的个性化设置相关.它是一个隐藏文件,需要使用ls -a来查看. .bash_history   记 ...

  7. 1.1、配置Python虚拟环境

    安装虚拟环境 系统:CentOS 7.2 python版本:Python 2.7.5 1.虚拟环境介绍 虚拟环境是Python解释器的一个私有副本,在这个环境中你可以安装私有包,而且不会影响系统中安装 ...

  8. Linux挂载NAS共享文件夹

    [root@ftp:/mnt] > mount -o username=user01,password=1234567890 //192.168.31.20/share /mnt/nas [ro ...

  9. springcloud 中文文档

    spring cloud 中文文档:https://springcloud.cc/spring-cloud-dalston.html spring cloud 中文网:https://springcl ...

  10. oracle 单独开始一个事物的写法 。

    SET TRANSACTION NAME 'Update salaries'; SAVEPOINT before_salary_update; UPDATE employees SET salary= ...