框架使用SpringBoot + Spring Security Oauth2 +PostMan

框架使用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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/387164.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

3.12 12!配对

找出输入数据中所有两两相乘的积为12!的个数。 输入样例&#xff1a; 1 10000 159667200 9696 38373635 1000000 479001600 3 1 479001600 输出样例&#xff1a; 3 有3对&#xff1a; 1 479001600 1 479001600 3 159667200 #include<iostream> #include<fstre…

程序员自身价值值这么多钱么?

xx 网络公司人均奖金 28 个月…… xx 科技公司人均奖金 35 个月…… 每到年底&#xff0c;这样的新闻在互联网业内简直是铺天盖地。那些奖金不高的程序员们一边羡慕嫉妒&#xff0c;一边暗暗比较一下自己的身价&#xff0c;考虑是不是该跳槽了。 不同水平的程序员&#xff0c;薪…

3.13 判读是否是对称素数

输入&#xff1a;11 101 272 输出&#xff1a; Yes Yes No #include<fstream> #include<iostream> #include<sstream> #include<string> #include<cmath> using namespace std;bool isPrime(int); bool isSymmetry(int);int main(){ifstream…

Spring MVC中使用 Swagger2 构建Restful API

0.Spring MVC配置文件中的配置[java] view plaincopy<!-- 设置使用注解的类所在的jar包&#xff0c;只加载controller类 --> <span style"white-space:pre"> </span><context:component-scan base-package"com.jay.plat.config.contro…

Go语言规范汇总

目录 统一规范篇合理规划目录GOPATH设置import 规范代码风格大小约定命名篇基本命令规范项目目录名包名文件名常量变量变量申明变量命名惯例全局变量名局部变量名循环变量结构体(struct)接口名函数和方法名参数名返回值开发篇包魔鬼数字常量 & 枚举结构体运算符函数参数返回…

3.14 01串排序

将01串首先按照长度排序&#xff0c;其次按1的个数的多少排序&#xff0c;最后按ASCII码排序。 输入样例&#xff1a; 10011111 00001101 10110101 1 0 1100 输出样例&#xff1a; 0 1 1100 1010101 00001101 10011111 #include<fstream> #include<iost…

platform(win32) 错误

运行cnpm install后&#xff0c;出现虽然提示不适合Windows&#xff0c;但是问题好像是sass loader出问题的。所以只要执行下面命令即可&#xff1b;方案一&#xff1a;cnpm rebuild node-sass #不放心可以重新安装下 cnpm install方案二&#xff1a;npm update npm install no…

Error: Program type already present: okhttp3.Authenticator$1

在app中的build.gradle中加入如下代码&#xff0c; configurations {all*.exclude group: com.google.code.gsonall*.exclude group: com.squareup.okhttp3all*.exclude group: com.squareup.okioall*.exclude group: com.android.support,module:support-v13 } 如图 转载于:ht…

3.15 排列对称串

筛选出对称字符串&#xff0c;然后将其排序。 输入样例&#xff1a; 123321 123454321 123 321 sdfsdfd 121212 \\dd\\ 输出样例 123321 \\dd\\ 123454321 #include<fstream> #include<iostream> #include<string> #include<set> using …

ES6规范 ESLint

在团队的项目开发过程中&#xff0c;代码维护所占的时间比重往往大于新功能的开发。因此编写符合团队编码规范的代码是至关重要的&#xff0c;这样做不仅可以很大程度地避免基本语法错误&#xff0c;也保证了代码的可读性&#xff0c;毕竟&#xff1a;程序是写给人读的&#xf…

前端 HTML 常用标签 head标签相关内容 script标签

script标签 定义JavaScript代码 <!--定义JavaScript代码--> <script type"text/javascript"></script> 引入JavaScript文件 src""引入的 js文件路径 <!-- 引入JavaScript文件 --> <script src"./index.js"></s…

3.16 按绩点排名

成绩60分及以上的课程才予以计算绩点 绩点计算公式&#xff1a;[(课程成绩-50) / 10 ] * 学分 学生总绩点为所有绩点之和除以10 输入格式&#xff1a; 班级数 课程数 各个课程的学分 班级人数 姓名 各科成绩 输出格式&#xff1a; class 班级号: 姓名&#xff08;占1…

iview日期控件,双向绑定日期格式

日期在双向绑定之后格式为&#xff1a;2017-07-03T16:00:00.000Z 想要的格式为2017-07-04调了好久&#xff0c;几乎一天&#xff1a;用一句话搞定了 on-change”addForm.Birthday$event”<Date-picker placeholder"选择日期" type"datetime" v-model&…

移除html,jsp中的元素

移除html&#xff0c;jsp中的元素 某些时候&#xff0c;需要移除某个元素&#xff0c;比如移除表中的某一行 $("#tbody").children().eq(i).remove();或者 $("#tr").remove();PS&#xff1a;获取表中的tr的数量&#xff1a; $("#tbody").childre…

ACM001 Quicksum

本题的重点在于数据的读入。 可采用cin.getlin()一行一行读入数据&#xff1b;也可采用cin.get()一个一个读入字符。 cin会忽略回车、空格、Tab跳格。 cin.get()一个一个字符读&#xff0c;不忽略任何字符。 cin.getline()一行一行读入。 #include<fstream> #include…

[Swift]LeetCode884. 两句话中的不常见单词 | Uncommon Words from Two Sentences

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★➤微信公众号&#xff1a;山青咏芝&#xff08;shanqingyongzhi&#xff09;➤博客园地址&#xff1a;山青咏芝&#xff08;https://www.cnblogs.com/strengthen/&#xff09;➤GitHub地址&a…

微信公众号 语音录音jssdk

1.开发流程 如果开发的是普通的展示性页面&#xff0c;就和开发普通的页面没有区别&#xff0c;不过这里要用到设备&#xff08;手机&#xff09;的录音功能&#xff0c;就需要调用微信app的录音接口&#xff0c;需要使用微信jssdk。 使用微信jssdk&#xff1a;微信JS-SDK说明文…

iview table 方法若干

新增默认选中1. _checked字段增加2. 给data项设置特殊 key _checked: true2.0 多选框样式错乱&#xff0c;默认选中问题1. 修改为元素checkbox 样式大概调整2. 如果样式不好看 可以自行修改或者使用其他组件ui checkboxAPI props 属性说明类型items显示的结构化数据Arraycolumn…

05 MapReduce应用案例01

1、单词计数 在一定程度上反映了MapReduce设计的初衷--对日志文件进行分析。 public class WordCountMapper extends Mapper<LongWritable, Text, Text, IntWritable>{//该方法循环调用&#xff0c;从文件的split中读取每行调用一次&#xff0c;把该行所在的下标为key&a…

ios高级开发之多线程(一)

1.概念&#xff1a; 多线程&#xff08;multithreading&#xff09;到底是什么呢&#xff0c;它是指在软件或者硬件上实现多个线程并发执行的技术。具有多线程能力的计算机因有硬件的支持&#xff0c;而能够在同一时间执行多个线程&#xff0c;进而提升整体处理性能。在一个程序…