author2是一个开放标准,该标准允许用户让第三方用户访问该用户在某一网站上存储的私密资源,例如头像、照片、视频等。

author2有几个基本角色:

  • 资源所有者:即用户
  • 客户端:但三方应用
  • 授权服务器:用来验证用户提供的信息是否正确,并返回一个令牌
  • 资源服务器:提供给用户资源的服务器

授权模式:

  • 授权码模式:功能最完整,流程最严谨的。通过客户端服务器与授权授权服务器交互。国内常见的第三方平台登入就是使用这个功能实现的。
  • 简化模式:不需要客户端服务器的参与,直接在浏览器中向授权服务器申请令牌,一般网站是纯静态页面的,可以使用这个方法。
  • 密码模式:直接把用户名和密码告诉客户端,客户端使用这些信息向授权服务器申请令牌。
  • 客户端模式:客户端使用自己的名义而不是用户的名义向服务器一共申请授权。

接下来开始springboot整合author2,github:https://github.com/fengqing11/springboot-oauth2

创建项目,依赖如下:
由于springboot中的oauth协议实在spring security的基础上完成的,因此需要添加spring security依赖。
令牌存储在redis缓存服务器上,同时redis具有过期功能,很适合令牌的存储,因此也加入redis的依赖。

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>org.sang</groupId><artifactId>oauth2</artifactId><version>0.0.1-SNAPSHOT</version><packaging>jar</packaging><name>oauth2</name><description>Demo project for Spring Boot</description><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.0.3.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><java.version>1.8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency><dependency><groupId>org.springframework.security.oauth</groupId><artifactId>spring-security-oauth2</artifactId><version>2.3.3.RELEASE</version></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>

配置文件:

spring.redis.database=0
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=
spring.redis.jedis.pool.max-active=8
spring.redis.jedis.pool.max-idle=8
spring.redis.jedis.pool.max-wait=-1ms
spring.redis.jedis.pool.min-idle=0

配置授权服务器:
授权服务器和资源服务器可一是同一台服务器,也可以是不同的服务器,这里使用同一服务器。
通过不同的配置分开授权服务器和资源服务器。

继承AuthorizationServerConfigurerAdapter,完成对授权服务器的配置,然后通过@EnableAuthorizationServer注解开启授权服务器。
AuthenticationManager对象用来支持password授权模式。
RedisConnectionFactory对象用来完成redis的缓存。
UserDetailsService对象为刷新token提供支持。
authorizedGrantTypes()方法配置授权模式为password和refresh_token,其实在标准的oauth中并没有refresh_token,但是spring security中将其归为一种,因此要实现access_token的刷新就需要refresh_token。
accessTokenValiditySeconds()方法设置token的过期时间。
resourceIds()方法配置资源id。
secret()方法配置了加密后的密码,明文是123。

package org.sang.oauth2;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfigextends AuthorizationServerConfigurerAdapter {@AutowiredAuthenticationManager authenticationManager;@AutowiredRedisConnectionFactory redisConnectionFactory;@AutowiredUserDetailsService userDetailsService;@BeanPasswordEncoder passwordEncoder() {return new BCryptPasswordEncoder();}@Overridepublic void configure(ClientDetailsServiceConfigurer clients)throws Exception {clients.inMemory().withClient("password").authorizedGrantTypes("password", "refresh_token").accessTokenValiditySeconds(1800).resourceIds("rid").scopes("all").secret("$2a$10$RMuFXGQ5AtH4wOvkUqyvuecpqUSeoxZYqilXzbz50dceRsga.WYiq");}@Overridepublic void configure(AuthorizationServerEndpointsConfigurer endpoints)throws Exception {endpoints.tokenStore(new RedisTokenStore(redisConnectionFactory)).authenticationManager(authenticationManager).userDetailsService(userDetailsService);}@Overridepublic void configure(AuthorizationServerSecurityConfigurer security)throws Exception {security.allowFormAuthenticationForClients();}
}

配置资源服务器:
继承ResourceServerConfigurerAdapter,并使用@EnableResourceServer注解开启资源服务器配置。
resourceId()来配置资源id,这里的id和授权服务器的资源id要一样。
stateless()方法设置这些资源仅基于令牌验证。

package org.sang.oauth2;import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;@Configuration
@EnableResourceServer
public class ResourceServerConfigextends ResourceServerConfigurerAdapter {@Overridepublic void configure(ResourceServerSecurityConfigurer resources)throws Exception {resources.resourceId("rid").stateless(true);}@Overridepublic void configure(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/admin/**").hasRole("admin").antMatchers("/user/**").hasRole("user").anyRequest().authenticated();}
}

配置security:
和前面的没什么区别,唯一不同的是多了两个@bean注解,这两个Bean将注入到授权服务器中使用。
这里的HttpSecurity配置主要配置/oauth/**的URL,这一类的请求直接放行。在资源服务器配置中也有一个HttpSecurity,这里的HttpSecurity优先于资源服务器的HttpSecurity。

package org.sang.oauth2;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {@Bean@Overridepublic AuthenticationManager authenticationManagerBean() throws Exception {return super.authenticationManagerBean();}@Bean@Overrideprotected UserDetailsService userDetailsService() {return super.userDetailsService();}@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.inMemoryAuthentication().withUser("admin").password("$2a$10$RMuFXGQ5AtH4wOvkUqyvuecpqUSeoxZYqilXzbz50dceRsga.WYiq").roles("admin").and().withUser("sang").password("$2a$10$RMuFXGQ5AtH4wOvkUqyvuecpqUSeoxZYqilXzbz50dceRsga.WYiq").roles("user");}@Overrideprotected void configure(HttpSecurity http) throws Exception {http.antMatcher("/oauth/**").authorizeRequests().antMatchers("/oauth/**").permitAll().and().csrf().disable();}
}

启动服务器后POST访问:http://127.0.0.1:8080/oauth/token?username=sang&password=123&grant_type=password&client_id=password&scope=all&client_secret=123

这里参数都写在url上,方便,但也是一个post请求:

请求参数:

  • username:用户名
  • password:面膜
  • grant_type:授权模式
  • client_id:资源服务器id
  • scope:资源服务器范围
  • client_secret:资源服务器密码

返回内容:

  • access_token:就是令牌
  • token_type:
  • refresh_token:用来刷新令牌,可以用来刷新token,前提是token未过期
  • expires_in:token的过期时间,再次刷新可以发现实现不在是1800,他减少了
  • scope:

刷新token访问:http://127.0.0.1:8080/oauth/token?grant_type=refresh_token&refresh_token=6bef362e-a96c-48af-a310-b9623d7c69a4&client_id=password&client_secret=123

访问资源,访问:http://localhost:8080/user/hello?access_token=cf4d8b09-3fe1-4671-91f3-4703d6e75c91

至此,一个password模式的oauth认证体系就搭建好了。

-end-

springboot整合author2相关推荐

  1. SpringBoot第九篇: springboot整合Redis

    这篇文章主要介绍springboot整合redis,至于没有接触过redis的同学可以看下这篇文章:5分钟带你入门Redis. 引入依赖: 在pom文件中添加redis依赖: <dependen ...

  2. es springboot 不设置id_原创 | 一篇解决Springboot 整合 Elasticsearch

    ElasticSearch 结合业务的场景,在目前的商品体系需要构建搜索服务,主要是为了提供用户更丰富的检索场景以及高速,实时及性能稳定的搜索服务. ElasticSearch是一个基于Lucene的 ...

  3. springboot整合shiro使用shiro-spring-boot-web-starter

    此文章仅仅说明在springboot整合shiro时的一些坑,并不是教程 增加依赖 <!-- 集成shiro依赖 --> <dependency><groupId> ...

  4. db2 springboot 整合_springboot的yml配置文件通过db2的方式整合mysql的教程

    springboot整合MySQL很简单,多数据源就master,slave就行了,但是在整合DB2就需要另起一行,以下是同一个yml文件 先配置MySQL,代码如下 spring: datasour ...

  5. 九、springboot整合rabbitMQ

    springboot整合rabbitMQ 简介 rabbitMQ是部署最广泛的开源消息代理. rabbitMQ轻量级,易于在内部和云中部署. 它支持多种消息传递协议. RabbitMQ可以部署在分布式 ...

  6. 八、springboot整合Spring Security

    springboot整合Spring Security 简介 Spring Security是一个功能强大且可高度自定义的身份验证和访问控制框架.它是保护基于Spring的应用程序的事实标准. Spr ...

  7. 六、springboot整合swagger

    六.springboot整合swagger 简介 swagger 提供最强大,最易用的工具,以充分利用OpenAPI规范. 官网 : https://swagger.io/ 准备工作 pom.xml ...

  8. SpringBoot整合mybatis、shiro、redis实现基于数据库的细粒度动态权限管理系统实例(转)...

    SpringBoot整合mybatis.shiro.redis实现基于数据库的细粒度动态权限管理系统实例 shiro 目录(?)[+] 前言 表结构 maven配置 配置Druid 配置mybatis ...

  9. SpringBoot整合RabbitMQ-整合演示

    本系列是学习SpringBoot整合RabbitMQ的练手,包含服务安装,RabbitMQ整合SpringBoot2.x,消息可靠性投递实现等三篇博客. 学习路径:https://www.imooc. ...

  10. 【模板引擎】Springboot整合ThymeleafThymeleaf基本语法

    Thymeleaf介绍 thymeleaf是一个XML/XHTML/HTML5模板引擎,可用于Web与非Web环境中的应用开发.它是一个开源的Java库,基于Apache License 2.0许可, ...

最新文章

  1. LeetCode:326. Power of Three
  2. leetcoed123. 买卖股票的最佳时机 III
  3. .net动态控件的使用(listview ,treeview,tabControl)
  4. 【转】如何读一篇论文
  5. 苹果Mac重复文件清理工具:​​​​Tidy Up
  6. GCC与VC2013性能比较
  7. sonar下载地址使用
  8. PPTV发布裸眼3D手机:中国联通加持,又一款“互联网生态手机”---ESM
  9. YAML和JSON对比
  10. 华为软件测试笔试真题之变态逻辑推理题【二】华为爆火面试题
  11. Python之统计英文字符的个数
  12. int content=Integer.parseInt(jtf.getText().trim());
  13. opencv-python对大视频切割成小视频
  14. 社交网络叠加直播功能,会产生什么化学反应?
  15. K--最邻近(K-NN)算法
  16. vue初学篇----过滤器(filters)
  17. 基于微信小程序做直播的截图(微信小程序发起视频直播)
  18. 浏览器兼容问题,一直是自己最头疼,一直回避的问题,今天看得到了一些启发,发奋今天开始研究这个,哈哈,以下为转载文章,好好学习。...
  19. 漫步最优化五——可行域
  20. BP神经网络需要训练的参数,bp神经网络训练时间

热门文章

  1. Hibernate配置(核心配置文件.cfg.xml 和映射配置文件.hbm.xml)(对象-关系映射 Object Relational Mapping)
  2. tableau的骑行路线地理数据可视化
  3. Linux下命令无法使用
  4. 江苏工匠杯easyphp
  5. 判定树与判定表的定义与相关练习
  6. 从投入产出简析直复营销
  7. 华为H3CNE认证题库、教材-热门下载帖汇总!
  8. HTML5会砸掉iOS和Android的饭碗么?
  9. Worm.Win32.DownLoad.gew病毒清除记
  10. 实话实说,现在的结婚,真就是走个形式!