理解什么是OAUTH2

OAuth2是什么

OAuth 就是一种授权机制,数据的所有者告诉系统,同意授权第三方应用进入系统,获取这些数据。系统从而产生一个短期的进入令牌(token),用来代替密码,供第三方应用使用。

授权机制和密码机制的区别:
(1)令牌是短期的,到期会自动失效,用户自己无法修改。密码一般长期有效,用户不修改,就不会发生变化。

(2)令牌可以被数据所有者撤销,会立即失效。密码一般不允许被他人撤销。

(3)令牌有权限范围(scope)。对于网络服务来说,只读令牌就比读写令牌更安全。密码一般是完整权限。

OAuth2的优点

你只需要一个账号密码,就能在各个网站进行访问,从而免去了在每个网站都进行注册的繁琐过程,如:很多网站都可以使用微信登录,网站作为第三方服务、微信作为服务提供商。

OAuth2 中的角色分类

  1. resource owner:资源拥有者,可以简单的理解成“我”,关系是Resource Owner在Authorization Server注册Client信息。
  2. resource server:资源存放所在的服务器
  3. authrization server:授权认证服务器,用来和客户端打交道,判断是否允许访问我们的数据
  4. client:需要使用我们资源的第三方信息

OAuth授权模式的共性

不管哪一种授权方式,第三方应用拿到 token 之前,都必须先到系统备案,说明自己的身份,然后会拿到两个身份识别码:客户端 ID(client_id)和客户端密钥(client_secret)。这是为了防止令牌被滥用,没有备案过的第三方应用,是不会拿到令牌的。

OAuth2 的授权模式(获取令牌的几种模式)

OAuth2中授权模式分为以下四种:

  1. 授权码模式:四种模式中功能最完整、流程最严密的授权模式,授权码既微信中的code的概念
  2. 简化模式/隐藏式:浏览器中直接访问认证服务器获取授权token,简化了授权码模式中的后台和后台的交互
  3. 密码模式:简单暴力的模式,客户端拿着用户名密码访问授权服务器
  4. 客户端模式/凭证式:客户端用自己的秘钥向授权服务器获取授权

授权码模式流程步骤

指的是第三方应用先申请一个授权码,然后再用该授权码获取令牌。

  1. 用户访问客户端,客户端需要知道用户是谁,于是带着用户去找授权服务器

  1. 授权服务器问用户:因为您是我们的用户,所以我知道你的身份,请问您愿意把您的相关信息给客户端吗? 客户说:“Ok”

  2. 授权服务器分配一个code(授权码)并重定向到客户端指定的url

  1. 客户端在该url下截取了code(授权码),向认证服务器索要令牌

  1. 授权服务器用code码验证了合法性,发放了令牌

简化模式详解

允许直接向前端颁发令牌。这种方式没有授权码这个中间步骤,所以称为"隐藏式"(implicit)。

  1. 用户访问客户端,客户端需要知道用户是谁,于是带着用户去找授权服务器

  1. 授权服务器问用户:因为您是我们的用户,所以我知道你的身份,请问您愿意把您的相关信息给客户端吗? 客户说:“Ok”

  2. 授权服务器生成了令牌,追加在了重定向uri中

密码模式详解

如果你高度信任某个应用,RFC 6749 也允许用户把用户名和密码,直接告诉该应用。该应用就使用你的密码,申请令牌,这种方式称为"密码式"(password)。

  1. 用户向客户端提供用户名和密码
  2. 客户端将用户名密码发送认证给服务器,向后者请求令牌

  1. 认证服务器确认无误后,向客户端提供访问令牌

客户端模式

凭证式(client credentials),适用于没有前端的命令行应用,即在命令行下请求令牌。

  1. 客户端向认证服务器进行身份认证,并要求一个访问令牌

  1. 认证服务器确认无误后,向客户端提供访问令牌

令牌的其他操作–更新令牌

如果用户访问的时候,客户端“访问令牌”已经过期,则需要使用“更新令牌”申请一个新的令牌。

具体方法是,B 网站颁发令牌的时候,一次性颁发两个令牌,一个用于获取数据,另一个用于获取新的令牌(refresh token 字段)。令牌到期前,用户使用 refresh token 发一个请求,去更新令牌。

Spring Cloud Oauth2 集成

Spring Cloud版本

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-dependencies</artifactId><version>2.2.0.RELEASE</version><type>pom</type><scope>import</scope>
</dependency><!--springcloud依赖-->
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-dependencies</artifactId><version>Hoxton.RELEASE</version><type>pom</type><scope>import</scope>
</dependency>

Spring Cloud Oauth2 部署

核心pom

<!--oauth2-->
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-oauth2</artifactId>
</dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

配置

server:port: 50005servlet:context-path: /tomcat:uri-encoding: UTF-8max-threads: 1000min-spare-threads: 30spring:application:name: oauth2-centerredis:host: redis-hostport: 6379

启动器

/*** @author zhexiao* @date 2020-09-25 20:11**/
@EnableDiscoveryClient //获得服务信息
@SpringBootApplication
public class Oauth2 {@Beanpublic PasswordEncoder passwordEncoder() {return new BCryptPasswordEncoder();}public static void main(String[] args) {SpringApplication.run(Oauth2.class, args);}
}

测试用的Controller

ApiController

/*** @author zhe.xiao* @date 2021-03-26 15:37* @description*/
@RestController
@RequestMapping(path = "/api")
public class ApiController {@GetMapping(path = "/a")public String a(){return "api a";}@GetMapping(path = "/b")public String b(){return "api b";}@PostMapping(path = "/c")public String c(){return "api c";}
}

UserController

/*** @author zhe.xiao* @date 2021-03-26 15:37* @description*/
@RestController
@RequestMapping(path = "/user")
public class UserController {@GetMapping(path = "/")public String user(){return "zhexiao user";}
}

核心的Oauth2 Configuration

Oauth2 第一步 配置WebSecurityConfigurerAdapter

/*** @author zhe.xiao* @date 2021-03-26 15:46* @description* OAUTH2 第一步配置 web*/
@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {@AutowiredPasswordEncoder passwordEncoder;/*** 认证管理器* OAUTH2 认证服务器会使用这个* @return* @throws Exception*/@Bean@Overridepublic AuthenticationManager authenticationManagerBean() throws Exception {return super.authenticationManagerBean();}/*** 用户验证* @param auth* @throws Exception*/@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.inMemoryAuthentication().withUser("admin_1").password(passwordEncoder.encode("123456")).roles("ADMIN").and().withUser("user_1").password(passwordEncoder.encode("123456")).roles("USER");}/*** HTTP请求权限* @param http* @throws Exception*/@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/user/**").permitAll().antMatchers("/oauth/**").permitAll().antMatchers("/api/**").authenticated();}
}

Oauth2 第二步 配置资源服务器

/*** @author zhe.xiao* @date 2021-03-26 15:35* @description* Oauth2 第二步 配置资源服务器*/
@EnableResourceServer
@Configuration
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {public static final String RESOURCE_NAME = "my-resource";@Overridepublic void configure(ResourceServerSecurityConfigurer resources) throws Exception {//只有基于token的认证才可以访问这些资源resources.resourceId(RESOURCE_NAME).stateless(true);}
}

Oauth2 第三步 配置认证服务器

/*** @author zhe.xiao* @date 2021-03-26 15:23* @description** Oauth2 第三步 配置认证服务器*/
@EnableAuthorizationServer
@Configuration
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {@AutowiredPasswordEncoder passwordEncoder;@AutowiredRedisConnectionFactory redisConnectionFactory;@AutowiredAuthenticationManager authenticationManager;@Overridepublic void configure(ClientDetailsServiceConfigurer clients) throws Exception {clients.inMemory()//client1允许client_credentials认证.withClient("client1").secret(passwordEncoder.encode("client1_secret")).resourceIds(ResourceServerConfig.RESOURCE_NAME).authorizedGrantTypes("client_credentials", "refresh_token").scopes("access_token").authorities("client").and()//client2允许密码认证.withClient("client2").secret(passwordEncoder.encode("client2_secret")).resourceIds(ResourceServerConfig.RESOURCE_NAME).authorizedGrantTypes("password", "refresh_token").scopes("access_token").authorities("client");}@Overridepublic void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {endpoints.tokenStore(new RedisTokenStore(redisConnectionFactory)).authenticationManager(authenticationManager).allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST); //支持OAUTH相关接口以GET和POST方法请求}/*** 支持请求的时候,已表单的形式发送数据* @param oauthServer* @throws Exception*/@Overridepublic void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {oauthServer.allowFormAuthenticationForClients().checkTokenAccess("permitAll()");}
}

访问

这个时候,系统已经暴露了一批与Oauth相关的接口给我们使用:
{[/oauth/authorize],methods=[GET/POST]
{[/oauth/token],methods=[GET/POST]}
{[/oauth/token],methods=[POST]}
{[/oauth/check_token]}
{[/oauth/error]}

client1请求

POST http://localhost:50005/oauth/token

client2请求

POST http://localhost:50005/oauth/token

因为我们上面tokenStore指明的这些数据存在Redis里面,所以可以发现在生成token后redis自动新增了许多key:

检查token是否合法

GET http://localhost:50005/oauth/check_token?token=1e83bdbf-5529-4a70-9ffb-b5f845c45509

通过token访问controller

没带token

带了token

SpringCloud Oauth2认证 基础版本相关推荐

  1. spring security 5 oauth2认证服务器开发

    注:本文节选自 spring security 5.x 的介绍,原文包含介绍.技术选型.spring security 的使用.可以运行的oauth2认证demo工程,如何开发自己的脚手架等.原文地址 ...

  2. springcloud + oauth2

    http://www.ruanyifeng.com/blog/2014/05/oauth_2_0.html 1.什么是OAuth OAuth是一个关于授权(authorization)的开放网络标准, ...

  3. Windows认证基础知识

    Windows认证 本地认证 基础知识 本地登录,操作系统会使用用户输入的密码作为凭证去与系统中的密码进行验证 密码存储位置:%SystemRoot%\system32\config\sam SAM保 ...

  4. SpringCloud - Oauth2增加短信验证码验证登录

    文章目录 前言 Oauth2认证过程 1.在进行认证时,会先根据认证类型即前端传入的grant_type,从所有的TokenGranter中找到具体匹配的TokenGranter 2.在找到对应的To ...

  5. OAuth2认证流程

    目录 什么是OAuth2 1. OAuth2认证流程 1.用户点击微信扫码 2.用户授权黑马网站访问用户信息 3.黑马程序员的网站获取到授权码 4.携带授权码请求微信认证服务器申请令牌 5.微信认证服 ...

  6. angular-oauth2 —— NG 的 OAuth2 认证模块

    angular-oauth2 详细介绍 angular-oauth2 是 AngularJS 的 OAuth2 认证模块,使用 ES6 编写. 使用方法: 引入 js 库: <script sr ...

  7. 权限认证php,2016年Linux认证基础知识:php做权限管理

    2016年Linux认证基础知识:php做权限管理 在学习Linux认证过程中,每个人会遇到每个人不同的问题,或小或大,那么你知道在Linux下,php怎么做权限管理?下面跟yjbys小编来看看最新的 ...

  8. WebView实例开发之人人网Oauth2认证

    今天做了一个webview网络操作的实例,这里与大家分享.相信开发过新浪.腾讯.豆瓣以及人人等微博的开发者都知道OAuth这个认证框架.这些开放平台上也有自己开发好了的SDK,只需要下载过来即可使用. ...

  9. Envoy实现.NET架构的网关(四)集成IdentityServer4实现OAuth2认证

    .NET网关与Gateway实战-Envoy与kong课程 什么是OAuth2认证 简单说,OAuth 就是一种授权机制.数据的所有者告诉系统,同意授权第三方应用进入系统,获取这些数据.系统从而产生一 ...

最新文章

  1. 基于熵权法优劣解距离法_基于优劣解距离法的火电机组单辅机运行状态评估
  2. 关于登录记住密码使用cookie的详解
  3. PHP 不跳转界面取input值进行验证_【Python】tesseract+uiautomator2+夜神模拟器 悠长假期手游集市识别验证码自动购买 - Amorius...
  4. IDEA中新建SpringBoot项目时提示:Artifact contains illegal characters
  5. Qt路径中常用字符“./”、“../”、“/”、“*”的含义
  6. 新一代数据安全的制胜法宝-UBA
  7. 软件设计师25-操作系统
  8. Android Studio 设置主题及字体
  9. pix 506E拨号上网设置
  10. SQL 分页查询显示
  11. rpcbind 、nfs无法启动问题
  12. Eclipse+Wildfly10 创建第一个EJB项目
  13. 6个专家认可的持续绩效管理技巧
  14. java材质转基岩版_我的世界java版材质包转换导入基岩版教程
  15. 面向未来的100项颠覆性创新技术!欧盟重磅报告
  16. 批处理bat下载FTP服务器上某个目录下的文件
  17. 李密(582~619)
  18. 反病毒工具-C32ASM
  19. 联想拯救者y7000电池耗电快_联想拯救者Y7000电池不充电,是因为电池有保护的
  20. TP-LINK路由器如何设置上网

热门文章

  1. hudi系列-upsert写过程
  2. 关于Mac App Store无法下载、无法安装、一直转圈的解决方法
  3. 企业架构顶层设计TOGAF 9.2标准认证 鉴定级培训课程
  4. Kafka消费者与消费组
  5. STM32 库函数学习 TIM篇
  6. 将小写字母转换为大写
  7. windows下安装nmap
  8. 讯飞文字转语音_unity3D
  9. 福州微信小程序服务器托管,福州微信小程序怎么搭建制作?
  10. 计算机电源可以带上飞机吗,移动电源能带上飞机吗