框架使用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.pswp.cn/news/387164.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/387164.shtml
英文地址,請注明出處:http://en.pswp.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;進而提升整體處理性能。在一個程序…