SpringBoot + Spring Security Oauth2 客户端授权
框架使用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>
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
3. 配置
关于oauth2协议相关内容以及授权流程 查看别的博文
主要会使用3个类来配置
- 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();}}
在配置客户端中,使用了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;}
}
- 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(); //配置访问权限控制,必须认证过后才可以访问}
}
- 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();}
}
接口访问
使用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
SpringBoot + Spring Security Oauth2 客户端授权相关推荐
- 框架使用SpringBoot + Spring Security Oauth2 +PostMan
框架使用SpringBoot + Spring Security Oauth2 主要完成了客户端授权 可以通过mysql数据库读取当前客户端表信息进行验证,token存储在数据库中 1.引入依赖 ...
- spring security oauth2 常用授权方式配置详细教程(一)
1 spring security oauth2 简单配置说明(一) 配套源码:https://download.csdn.net/download/tiancxz/12902941 1.1 工程说明 ...
- Spring Security OAuth2认证授权示例
本文介绍了如何使用Spring Security OAuth2构建一个授权服务器来验证用户身份以提供access_token,并使用这个access_token来从资源服务器请求数据. 1.概述 OA ...
- Spring Security Oauth2:授权模式、简单模式 、密码模式 和 客户端模式
Oauth2的授权模式流程 1.先得到用户的授权grant 2.利用grant得到令牌token 3.根据token获取用户的信息 步骤1:客户端(第三方应用)向用户请求授权. 步骤2:用户单击客户端 ...
- 【Spring Cloud Alibaba 实战 | 总结篇】Spring Cloud Gateway + Spring Security OAuth2 + JWT 实现微服务统一认证授权和鉴权
一. 前言 hi,大家好~ 好久没更文了,期间主要致力于项目的功能升级和问题修复中,经过一年时间这里只贴出关键部分代码的打磨,[有来]终于迎来v2.0版本,相较于v1.x版本主要完善了OAuth2认证 ...
- Spring Security OAuth2 微服务认证中心自定义授权模式扩展以及常见登录认证场景下的应用实战
本文源码地址 后端:https://gitee.com/youlaitech/youlai-mall/tree/v2.0.1 前端:https://gitee.com/youlaiorg/mall-a ...
- springboot集成Spring Security oauth2(八)
由于公司项目需要,进行SpringBoot集成Spring Security oauth2,几乎搜寻网上所有大神的案例,苦苦不能理解,不能完全OK. 以下是借鉴各大神的代码,终于demo完工,请欣赏 ...
- Spring Security OAuth2.0认证授权知识概括
Spring Security OAuth2.0认证授权知识概括 安全框架基本概念 基于Session的认证方式 Spring Security简介 SpringSecurity详解 分布式系统认证方 ...
- Spring Security Oauth2 JWT 实现用户认证授权功能
Spring Security Oauth2 JWT 一 用户认证授权 1. 需求分析 1.1 用户认证与授权 什么是用户身份认证? 用户身份认证即用户去访问系统资源时系统要求验证用户的身份信息,身份 ...
最新文章
- 360董事长兼CEO周鸿祎:未来网络攻击或造成物理伤害
- 计算机视觉行业迎来大发展,多角度解读未来前景
- 获取Executor提交的并发执行的任务返回结果的两种方式/ExecutorCompletionService使用...
- PAT甲级1142 Maximal Clique :[C++题解]图论、最大团、枚举
- 8大排序算法图文讲解
- 斐波那契数列(大数)
- 云小课 | 玩转HiLens Studio之手机实时视频流调试代码
- MySQL distinct多个字段
- java 返回值给c_Java有陷阱,用时需谨慎——慎用入参做返回值
- PostgreSQL的notify 与listen (三)
- ES6 iterator 迭代器
- socket.io 消息发送
- 第十届中国证券金紫荆奖名单揭晓 华能国际斩获两项大奖
- 用计算机处理表格信息,怎么制作表格-三线表丨做数据表格必须学会的处理技巧...
- 数字逻辑电路设计(实验测试题)
- 控制器中接收数据的四种方式
- MCU简单控制DAC芯片应用(以DAC8550为例)
- 服务器带宽10M能带多少人同时访问之并发数计算
- STM32自学笔记-7-CAN总线通信
- Sim Lock —— 手机Network锁
热门文章
- Docker 入门终极指南,这是我见过最好的教程!
- 用fock实现简易shell(程序替换)
- 数据结构 堆 heap
- HTML5七夕情人节表白网页制作——蓝色梦幻海洋3D相册—— HTML+CSS+JavaScript
- 绝妙四道题(C语言)
- 2021年危险化学品经营单位安全管理人员考试资料及危险化学品经营单位安全管理人员新版试题
- 第6章第23节:文字视觉化:使用图片来诠释文字的涵义 [PowerPoint精美幻灯片实战教程]
- api与密度转换公式_API重度和密度换算公式.doc
- IDL实现MODIS Grid(正弦投影)产品的重投影及拼接处理
- 图像特征点、投影变换与图像拼接