微服务(入门四):identityServer的简单使用(客户端授权)
IdentityServer简介(摘自Identity官网)
IdentityServer是将符合规范的OpenID Connect和OAuth 2.0端点添加到任意ASP.NET核心应用程序的中间件,通常,您构建(或重新使用)一个包含登录和注销页面的应用程序(可能还包括同意,具体取决于您的需要),IdentityServer中间件向其添加必要的协议头,以便客户端应用程序可以使用这些标准协议与之对话。
托管应用程序可以像您希望的那样复杂,但我们通常建议通过只包含与身份验证相关的UI来尽可能地保持攻击面小。
client :客户端,从identityServer请求令牌,用户对用户身份校验,客户端必须先从identityServer中注册,然后才能请求令牌。
sources :每个资源都有自己唯一的名称,就是文中所定义的api1服务名称,indentity会验证判定是否有访问该资源的权限。
access Token :访问令牌,由identityServer服务器签发的,客户端使用该令牌进行访问拥有权限的api
OAuth 2.0四种授权模式(GrantType)
- 客户端模式(client_credentials)
- 密码模式(password)
- 授权码模式(authorization_code)
- 简化模式(implicit)
作用
- 单点登录
在多个应用程序当中进行统一登录或者注销。
- api访问控制
- 为各种类型的客户端(如服务器到服务器、Web应用程序、SPA和本机/移动应用程序)颁发API访问令牌。
- 联盟网关
支持外部身份提供商,如Azure Active Directory、Google、Facebook等。这将使您的应用程序不了解如何连接到这些外部提供商的详细信息。
开发准备
开发环境 :vs2019
identityServer4:2.4.0
netcore版本 :2.1
客户端授权模式介绍
客户端模式的话是属于identityServer保护API的最基础的方案,我们定义个indentityServer服务以及一个需要保护的API服务,
当客户端直接访问api的话,由于我们的api服务添加了authorization认证,所以必须要到identityServer放服务器上拿到访问令牌,客户端凭借该令牌去对应api服务当中获取想要得到的数据。
添加IdentityServer项目
1.首先添加新项目,创建ASP.NET Core Web 应用程序 创建一个名称为identityServer4test的项目,选择项目类型API 项目进行创建。
2.从程序包管理器控制台或者ngGet下载IdentityServer4
2.1 程序包管理器控制台:install-package IdentityServer4
2.2 NuGet 的话在对应的程序集,选择nuget输入IdentityServer4选择对应的版本进行下载安装
3.添加Identity Server4 配置
资源定义可以通过多种方式实现,具体的请查阅官方api文档:https://identityserver4.readthedocs.io/en/latest/quickstarts/1_client_credentials.html
注:1.ApiResource("api1","My Api"),其中api1代表你的唯一资源名称,在 AllowedScopes = { "api1" }当中必须配置上才可以进行访问
using IdentityServer4.Models;
using IdentityServer4.Test;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks; namespace IdentityServer4Test.IndntityConfig
{
public class IdentityServerConfig
{
/// <summary>
/// 添加api资源
/// </summary>
/// <returns></returns>
public static IEnumerable<ApiResource> GetResources()
{
return new List<ApiResource>
{
new ApiResource("api1","My Api")
};
}
/// <summary>
/// 添加客户端,定义一个可以访问此api的客户端
/// </summary>
/// <returns></returns>
public static IEnumerable<Client> GetClients()
{
return new List<Client>
{
new Client
{
///
ClientId = "client", // 没有交互性用户,使用 客户端模式 进行身份验证。
AllowedGrantTypes = GrantTypes.ClientCredentials, // 用于认证的密码
ClientSecrets =
{
new Secret("".Sha256())
},
// 客户端有权访问的范围(Scopes)
AllowedScopes = { "api1" }
} }; }
}
}
4.在startUp当中注入IdentityServer4 服务
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using IdentityServer4.Models;
using IdentityServer4.Test;
using IdentityServer4Test.IndntityConfig;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options; namespace IdentityServer4Test
{
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.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
// 在DI容器中注入identityServer服务
services.AddIdentityServer() .AddInMemoryApiResources(IdentityServerConfig.GetResources())//添加配置的api资源
.AddInMemoryClients(IdentityServerConfig.GetClients())//添加客户端,定义一个可以访问此api的客户端
.AddDeveloperSigningCredential(); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
//添加identityserver中间件到http管道
app.UseIdentityServer();
//app.UseMvc();
}
}
}
5.此时启动程序输入 http://localhost:3322/.well-known/openid-configuration可以得到如下网站,这是identity Server4 提供的配置文档
6.用postMan请求获取access_token
标注:body 当中的参数
grant_type :对应api AllowedGrantTypes 类型表示授权模式
client_id : 对应clentID
client_secret: 客户端秘钥
7.拿到token以后就可以根据token去访问我们的服务程序,服务程序,首先也是创建一个webApi程序,并且从NuGet下载所需的依赖
- IdentityServer4.AccessTokenValidation(程序报管理器的话加上install-package IdentityServer4.AccessTokenValidation)
7.1 配置authentication,并且添加 app.UseAuthentication();到http管道当中
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options; namespace IndentityServerClientTest
{
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.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
//注入authentication服务
services.AddAuthentication("Bearer") .AddIdentityServerAuthentication(options =>
{
options.Authority = "http://localhost:3322";//IdentityServer服务地址
options.ApiName = "api1"; //服务的名称,对应Identity Server当中的Api资源名称,如果客户端得到的token可以访问此api的权限才可以访问,否则会报401错误
options.RequireHttpsMetadata = false;
}); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
//添加authentication中间件到http管道
app.UseAuthentication();
app.UseMvc();
}
}
}
7.2 引用Microsoft.AspNetCore.Authorization;命名空间,添加authorize认证
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; namespace IndentityServerClientTest.Controllers
{
[Route("api/[controller]")]
[ApiController]
[Authorize]
public class ValuesController : ControllerBase
{
// GET api/values
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
return new string[] { "value1", "value2" };
} // GET api/values/5
[HttpGet("{id}")]
public ActionResult<string> Get(int id)
{
return "value";
} // POST api/values
[HttpPost]
public void Post([FromBody] string value)
{
} // PUT api/values/5
[HttpPut("{id}")]
public void Put(int id, [FromBody] string value)
{
} // DELETE api/values/5
[HttpDelete("{id}")]
public void Delete(int id)
{
} // DELETE api/values/5
[Route("send")]
[HttpGet]
public string send()
{
return "成功了"; } }
}
7.3. 直接访问的话会报401错误
7.4 在请求头当中添加Authorization 参数,参数值为Bearer加上空格 加上咱们刚才获取到的access_token 请求成功!~~
密码授权
官方介绍
OAuth2.0资源所有者密码授权允许客户端向令牌服务发送用户名和密码,并获取代表该用户的访问令牌。
除了不能承载浏览器的遗留应用程序之外,规范通常建议不要使用资源所有者密码授予。一般来说,当您想要对用户进行身份验证并请求访问令牌时,最好使用交互式OpenID连接流之一。
然而,这种授权类型允许我们将用户的概念引入到QuickStartIdentityServer,这就是我们展示它的原因。
1.配置可访问的用户信息以及授权模式
新添加一个client模式并且更改AllowedGrantTypes 类型为“GrantTypes.ResourceOwnerPassword”
using IdentityServer4.Models;
using IdentityServer4.Test;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks; namespace IdentityServer4Test.IndntityConfig
{
public class IdentityServerConfig
{
/// <summary>
/// 添加api资源
/// </summary>
/// <returns></returns>
public static IEnumerable<ApiResource> GetResources()
{
return new List<ApiResource>
{
new ApiResource("api1","My Api")
};
}
/// <summary>
/// 添加客户端,定义一个可以访问此api的客户端
/// </summary>
/// <returns></returns>
public static IEnumerable<Client> GetClients()
{
return new List<Client>
{
new Client
{
///
ClientId = "client", // 没有交互性用户,使用 客户端模式 进行身份验证。
AllowedGrantTypes = GrantTypes.ClientCredentials, // 用于认证的密码
ClientSecrets =
{
new Secret("123454".Sha256())
},
// 客户端有权访问的范围(Scopes)
AllowedScopes = { "api1" }
}
,
new Client
{
ClientId = "client1", AllowedGrantTypes = GrantTypes.ResourceOwnerPassword, // 用于认证的密码
ClientSecrets =
{
new Secret("laozheng".Sha256())
},
RequireClientSecret=false,
// 客户端有权访问的范围(Scopes)
AllowedScopes = { "api1" }
}
}; } public static List<TestUser> GetTestUsers()
{
return new List<TestUser> {
new TestUser{
SubjectId="1",
Password="111",
Username="111",
}
};
}
}
}
1.1 修改startup.cs文件
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using IdentityServer4.Models;
using IdentityServer4.Test;
using IdentityServer4Test.IndntityConfig;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options; namespace IdentityServer4Test
{
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.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
// 在DI容器中注入identityServer服务
services.AddIdentityServer() .AddInMemoryApiResources(IdentityServerConfig.GetResources())
.AddInMemoryClients(IdentityServerConfig.GetClients())
.AddTestUsers(IdentityServerConfig.GetTestUsers())
.AddDeveloperSigningCredential(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
//添加identityserver中间件到http管道
app.UseIdentityServer();
//app.UseMvc();
}
}
}
2.获取token
3.通过刚才获取到的token访问接口
快速入口:微服务(入门一):netcore安装部署consul
快速入口: 微服务(入门二):netcore通过consul注册服务
快速入口: 微服务(入门三):netcore ocelot api网关结合consul服务发现
快速入口:微服务(入门四):identityServer的简单使用(客户端授权)
微服务(入门四):identityServer的简单使用(客户端授权)的更多相关文章
- .Net Core微服务入门全纪录(四)——Ocelot-API网关(上)
前言 上一篇[.Net Core微服务入门全纪录(三)--Consul-服务注册与发现(下)]已经使用Consul完成了服务的注册与发现,实际中光有服务注册与发现往往是不够的,我们需要一个统一的入口来 ...
- .Net Core微服务入门全纪录(五)——Ocelot-API网关(下)
前言 上一篇[.Net Core微服务入门全纪录(四)--Ocelot-API网关(上)]已经完成了Ocelot网关的基本搭建,实现了服务入口的统一.当然,这只是API网关的一个最基本功能,它的进阶功 ...
- 微服务入门三:SpringCloud Alibaba
一.什么是SpringCloud Alibaba 1.简介 1)简介 阿里云未分布式应用开发提供了一站式解决方案.它包含了开发分布式应用程序所需的所有组件,使您可以轻松地使用springcloud开发 ...
- 基于Spring Cloud的微服务入门教程
(本教程的原地址发布在本人的简书上:http://www.jianshu.com/p/947d57d042e7,若各位看官有什么问题或不同看法请在这里或简书留言,谢谢!) 本人也是前段时间才开始接触S ...
- 《Spring Cloud微服务 入门 实战与进阶》
很少在周末发文,还是由于昨晚刚收到实体书,还是耐不住性子马上发文了. 一年前,耗时半年多的时间,写出了我的第一本书<Spring Cloud微服务-全栈技术与案例解析>. 时至今日,一年的 ...
- Java生鲜电商平台-微服务入门与服务的拆分架构实战
Java生鲜电商平台-微服务入门与服务的拆分架构实战 刚开始进入软件行业时还是单体应用的时代,前后端分离的概念都还没普及,开发的时候需要花大量的时间在“强大”的JSP上面,那时候SOA已经算是新技术了 ...
- .Net Core微服务入门全纪录(二)——Consul-服务注册与发现(上)
前言 上一篇[.Net Core微服务入门全纪录(一)--项目搭建]讲到要做到服务的灵活伸缩,那么需要有一种机制来实现它,这个机制就是服务注册与发现.当然这也并不是必要的,如果你的服务实例很少,并且很 ...
- .Net Core微服务入门全纪录(三)——Consul-服务注册与发现(下)
前言 上一篇[.Net Core微服务入门全纪录(二)--Consul-服务注册与发现(上)]已经成功将我们的服务注册到Consul中,接下来就该客户端通过Consul去做服务发现了. 服务发现 同样 ...
- .Net Core微服务入门全纪录(六)——EventBus-事件总线
前言 上一篇[.Net Core微服务入门全纪录(五)--Ocelot-API网关(下)]中已经完成了Ocelot + Consul的搭建,这一篇简单说一下EventBus. EventBus-事件总 ...
- .Net Core微服务入门全纪录(七)——IdentityServer4-授权认证
前言 上一篇[.Net Core微服务入门全纪录(六)--EventBus-事件总线]中使用CAP完成了一个简单的Eventbus,实现了服务之间的解耦和异步调用,并且做到数据的最终一致性.这一篇将使 ...
随机推荐
- 使用commons-compress操作zip文件(压缩和解压缩)
http://www.cnblogs.com/luxh/archive/2012/06/28/2568758.html Apache Commons Compress是一个压缩.解压缩文件的类库. 可 ...
- Retrofit 2.0 超能实践,完美支持Https传输
http://blog.csdn.NET/sk719887916/article/details/51597816 前阵子看到圈子里Retrofit 2.0,RxJava(Android), OkHt ...
- Python HTTP库requests中文页面乱码解决方案!
http://www.cnblogs.com/bitpeng/p/4748872.html Python中文乱码,是一个很大的坑,自己不知道在这里遇到多少问题了.还好通过自己不断的总结,现在遇到乱码的 ...
- Jersey VS Django-Rest
在对Restful服务框架做对比前,主要先说说Restful设计的三大主要元素:以资源为核心的资源方法.资源状态.关系链接超媒体表述. 辅助的有内容协商.安全.版本化设计等. Jersey作为Java ...
- I want to try to improve myself from today
I involved in the Internet of Things project team in my university in 2015 and now I have completed ...
- C++ 延时等待(sleep/timer/wait)
原文链接:http://blog.csdn.net/tangweide/article/details/7063747 (-)使用_sleep()函数 #include <iostream> ...
- Nginx负载均衡和反向代理
1:反向代理 代理就是中介,那有反向代理就有正向代理,两者的区别是什么嘞? 正向代理隐藏真实客户端,服务端不知道实际发起请求的客户端.,proxy和client同属一个LAN,对server透明: 反 ...
- 解决AES算法CBC模式加密字符串后再解密出现乱码问题
问题 在使用 AES CBC 模式加密字符串后,再进行解密,解密得到的字符串出现乱码情况,通常都是前几十个字节乱码: 复现 因为是使用部门 cgi AESEncryptUtil 库,找到问题后,在这里 ...
- SpringBoot19 集成SpringSecurity01 -> 环境搭建、SpringSecurity验证
1 环境搭建 1.1 创建一个SpringBoot项目 项目脚手架 -> 点击前往 1.2 创建一个Restful接口 新建一个Controller类即可 package com.example ...
- 实验效果展示(会声会影+FSCapture)
第一步,视频录制: 利用屏幕录制软件(Eg:FSCapture,可设定矩形区域)录制信号采集过程,存储. 第二步,视频叠加制作 1)导入视频 2)主轨,复叠轨视频安插&时序调整 3)两个视频图 ...