框架使用SpringBoot + Spring Security Oauth2 
主要完成了客户端授权 
可以通过mysql数据库读取当前客户端表信息进行验证,token存储在数据库中

1.引入依赖

oauth2 依赖于spring security,需要引入spring, mysql,redis, mybatis

<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency><dependency><groupId>org.springframework.security.oauth</groupId><artifactId>spring-security-oauth2</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.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId></dependency><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>1.3.0</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency></dependencies>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34

2. 配置文件

server:port: 8081spring:datasource:url: jdbc:mysql://127.0.0.1:3306/oauth2?useUnicode=true&characterEncoding=utf-8&useSSL=falseusername: rootpassword: 123456driver-class-name: com.mysql.jdbc.Driverredis:host: 127.0.0.1database: 0mybatis:mapper-locations: mapper/*.xmlsecurity:oauth2:resource:filter-order: 3
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

3. 配置

关于oauth2协议相关内容以及授权流程 查看别的博文

主要会使用3个类来配置

  1. AuthorizationServerConfiguration 授权验证配置 
    继承AuthorizationServerConfigurerAdapter,配置授权的相关信息,配置的核心都在这里 
    在这里进行 配置客户端,配置token存储方式等
package oauth.security.client.configauto;import org.apache.tomcat.jdbc.pool.DataSource;
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.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.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
import oauth.security.client.configauto.jdbcdetail.MyJdbcTokenStore;@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {private static final String DEMO_RESOURCE_ID = "*";@AutowiredAuthenticationManager authenticationManager;@AutowiredRedisConnectionFactory redisConnectionFactory;@Autowiredprivate DataSource dataSource;// 初始化JdbcTokenStore@Autowiredpublic TokenStore getTokenStore() {return new JdbcTokenStore(dataSource);}// 自定义数据库存储tokenStore@Autowiredpublic TokenStore getMyTokenStore() {return new MyJdbcTokenStore(dataSource);}@Autowiredprivate TokenStore getRedisTokenStore() {return new RedisTokenStore(redisConnectionFactory);}@Bean   // 声明ApplyClientDetailServicepublic ApplyClientDetailService getClientDetails() {return new ApplyClientDetailService();}@Overridepublic void configure(ClientDetailsServiceConfigurer clients) throws Exception {// 配置客户端, 用于client认证clients.withClientDetails(getClientDetails());
/*          //使用存在内存中配置clients.inMemory().withClient("client_1").resourceIds(DEMO_RESOURCE_ID).authorizedGrantTypes("client_credentials", "refresh_token").scopes("all").authorities("client").secret("123456");*/}@Overridepublic void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {endpoints.tokenStore(new RedisTokenStore(redisConnectionFactory)).authenticationManager(authenticationManager);   // redis保存token
/*        endpoints.tokenStore(getTokenStore())   // 数据库保存token.authenticationManager(authenticationManager);*/}@Overridepublic void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {//允许表单认证oauthServer.allowFormAuthenticationForClients();}}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86

在配置客户端中,使用了ApplyClientDetailService类,是自定义的获取Client的一个类,继承ClientDetailsService

对Client的访问主要依靠JdbcClientDetailsService类的实现,必须使用官方给出的数据库结构,如果想自定义数据库结构,可以根据需求重写JdbcClientDetailsService类的实现。

package oauth.security.client.configauto;import org.apache.tomcat.jdbc.pool.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import oauth.security.client.service.ApplyService;public class ApplyClientDetailService implements ClientDetailsService {@Autowiredprivate ApplyService applyService;@Autowiredprivate DataSource dataSource;@Overridepublic ClientDetails loadClientByClientId(String applyName) throws ClientRegistrationException {/*// 使用mybatic验证client是否存在 ,根据需求写sqlMap clientMap = applyService.findApplyById(applyName);if(clientMap == null) {throw new ClientRegistrationException("应用" + applyName + "不存在!");}*///        MyJdbcClientDetailsService jdbcClientDetailsService= new MyJdbcClientDetailsService(dataSource, "authentication");JdbcClientDetailsService jdbcClientDetailsService= new JdbcClientDetailsService(dataSource);ClientDetails clientDetails = jdbcClientDetailsService.loadClientByClientId(applyName);return clientDetails;}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  1. ResourceServerConfiguration 资源配置 
    配置了资源权限
  package oauth.security.client.configauto;import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
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 ResourceServerConfiguration extends ResourceServerConfigurerAdapter {private static final String DEMO_RESOURCE_ID = "*";@Overridepublic void configure(ResourceServerSecurityConfigurer resources) {resources.resourceId(DEMO_RESOURCE_ID).stateless(true);}@Overridepublic void configure(HttpSecurity http) throws Exception {http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED).and().requestMatchers().anyRequest().and().anonymous().and().authorizeRequests()
//                    .antMatchers("/product/**").access("#oauth2.hasScope('select') and hasRole('ROLE_USER')").antMatchers("/**").authenticated();  //配置访问权限控制,必须认证过后才可以访问}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  1. SecurityConfiguration 安全配置
package oauth.security.client.configauto;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.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.approval.TokenStoreUserApprovalHandler;
import org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;/*** Created by fcz on 2017/12/28.*/
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {@Autowiredprivate ClientDetailsService clientDetailsService;@Autowiredprivate RedisConnectionFactory redisConnection;@Bean   // 声明ApplyClientDetailServicepublic ApplyClientDetailService getClientDetails() {return new ApplyClientDetailService();}@Bean@Overrideprotected UserDetailsService userDetailsService(){InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();manager.createUser(User.withUsername("user_1").password("123456").authorities("USER").build());manager.createUser(User.withUsername("user_2").password("123456").authorities("USER").build());return manager;}@Beanpublic TokenStore tokenStore() {return new RedisTokenStore(redisConnection);}@Bean@Autowiredpublic TokenStoreUserApprovalHandler userApprovalHandler(TokenStore tokenStore){TokenStoreUserApprovalHandler handler = new TokenStoreUserApprovalHandler();handler.setTokenStore(tokenStore());handler.setRequestFactory(new DefaultOAuth2RequestFactory(getClientDetails()));handler.setClientDetailsService(getClientDetails());return handler;}@Overrideprotected void configure(HttpSecurity http) throws Exception {http.requestMatchers().anyRequest().and().authorizeRequests().antMatchers("/oauth/*").permitAll();}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69

接口访问

使用postMan访问 
客户端请求token,POST :http://localhost:8081/oauth/token?grant_type=client_credentials&scope=all&client_id=apply&client_secret=123456

用户请求token,POST :http://localhost:8081/oauth/token?grant_type=password&username=user_1&password=123456&scope=all&client_id=apply&client_secret=123456

详细代码在githup : SpringSecurityOauth2

框架使用SpringBoot + Spring Security Oauth2 +PostMan相关推荐

  1. SpringBoot + Spring Security Oauth2 客户端授权

    框架使用SpringBoot + Spring Security Oauth2  主要完成了客户端授权  可以通过mysql数据库读取当前客户端表信息进行验证,token存储在数据库中 1.引入依赖 ...

  2. Springboot Spring Security +Jwt+redis+mybatisPlus 动态完成 前后端分离认证授权

    Springboot Spring Security +Jwt 动态完成 前后端分离认证授权 文章目录 Springboot Spring Security +Jwt 动态完成 前后端分离认证授权 前 ...

  3. springboot集成Spring Security oauth2(八)

    由于公司项目需要,进行SpringBoot集成Spring Security oauth2,几乎搜寻网上所有大神的案例,苦苦不能理解,不能完全OK. 以下是借鉴各大神的代码,终于demo完工,请欣赏 ...

  4. 芋道 Spring Security OAuth2 入门

    芋道 Spring Security OAuth2 入门 总阅读量:28123次 <Dubbo 实现原理与源码解析 -- 精品合集> <Netty 实现原理与源码解析 -- 精品合集 ...

  5. Spring Security Oauth2 JWT 实现用户认证授权功能

    Spring Security Oauth2 JWT 一 用户认证授权 1. 需求分析 1.1 用户认证与授权 什么是用户身份认证? 用户身份认证即用户去访问系统资源时系统要求验证用户的身份信息,身份 ...

  6. Spring Security OAuth2 单点登录

    1. 概述 在前面的文章中,我们学习了 Spring Security OAuth 的简单使用. <Spring Security OAuth2 入门> <Spring Securi ...

  7. 微服务安全Spring Security OAuth2实战

    文章目录 一.OAuth2.0介绍 1.1 应用场景 1.2 基本概念 1.3 优缺点 二.OAuth2的设计思路 2.1 客户端授权模式 授权码模式 简化(隐式)模式 密码模式 客户端模式 2.2 ...

  8. 学成在线-第16天-讲义- Spring Security Oauth2 JWT RSA加解密

    学成在线-第16天-讲义- Spring Security Oauth2 JWT 1 用户认证需求分析 1.1 用户认证与授权 ​ 截至目前,项目已经完成了在线学习功能,用户通过在线学习页面点播视频进 ...

  9. Spring Security OAuth2.0认证授权知识概括

    Spring Security OAuth2.0认证授权知识概括 安全框架基本概念 基于Session的认证方式 Spring Security简介 SpringSecurity详解 分布式系统认证方 ...

最新文章

  1. JS中的Replace方法
  2. python 批量打印文档_使用python将Excel数据填充Word模板并生成Word
  3. GDKOI 2016
  4. redis系列之1----redis简介以及linux上的安装
  5. 让子弹飞,零成本让你的网站更快一点,boxopened http/3 (QUIC) 协议实战
  6. 三种方法实现多级撤消/重做
  7. Oracle 从入门到精通系列 - 资料下载
  8. Python 将文件夹内所有pdf转换为图片输出到指定文件夹中
  9. 使用百度云AI C++SDK在windows上进行在线语音识别
  10. openCV中sobel边缘增强
  11. java提升的计划书
  12. C++基础入门(一)
  13. 【转】对Android开发者有益的40条优化建议
  14. Mac OS X 10.8.5升级到更高版本的方法
  15. Unity3d Ugui 20 Grid Layout Group Aspect Ratio Fitter
  16. JavaWeb项目实战 第四部分 Linux
  17. bug记录--------JSON parse error:Cannot deserialize value of type `com.test.EnumTest` from String
  18. 零知识证明经典文献大汇总(可收藏)
  19. 自学软件测试需要多久?怎么自学软件测试?自学软件测试可以找到工作吗?--请看我是怎么走过来的!绝对干货!
  20. 测控技术与仪器考计算机三级,测控技术与仪器专业就业方向及前景

热门文章

  1. Swing 学习小记
  2. 160 - 37 CyberBlade.1
  3. 转载|网络编程中阻塞式函数的底层逻辑
  4. 【设计模式之美】<Reading Notes>继承与组合
  5. 【C++ grammar】数据类型转换、列表初始化
  6. 合约 cd 模式_CD的完整形式是什么?
  7. django 静态数据_如何在Django中使用静态数据?
  8. vc++ 6.0 堆栈_在C ++中使用链接列表实现堆栈
  9. java 方法 示例_Java集合syncedSortedSet()方法与示例
  10. rda冗余分析步骤_群落分析的典范对应分析(CCA)概述