Spring Security 單點(diǎn)登錄簡單示例詳解
Overview
最近在弄單點(diǎn)登錄,踩了不少坑,所以記錄一下,做了個(gè)簡單的例子。
目標(biāo):認(rèn)證服務(wù)器認(rèn)證后獲取 token,客戶端訪問資源時(shí)帶上 token 進(jìn)行安全驗(yàn)證。
可以直接看源碼。
關(guān)鍵依賴
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.2.RELEASE</version> <relativePath/> </parent> <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-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.security.oauth.boot</groupId> <artifactId>spring-security-oauth2-autoconfigure</artifactId> <version>2.1.2.RELEASE</version> </dependency> </dependencies>
認(rèn)證服務(wù)器
認(rèn)證服務(wù)器的關(guān)鍵代碼有如下幾個(gè)文件:
AuthServerApplication
:
@SpringBootApplication @EnableResourceServer public class AuthServerApplication { public static void main(String[] args) { SpringApplication.run(AuthServerApplication.class, args); } }
AuthorizationServerConfiguration
認(rèn)證配置:
@Configuration @EnableAuthorizationServer class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter { @Autowired AuthenticationManager authenticationManager; @Autowired TokenStore tokenStore; @Autowired BCryptPasswordEncoder encoder; @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { //配置客戶端 clients .inMemory() .withClient("client") .secret(encoder.encode("123456")).resourceIds("hi") .authorizedGrantTypes("password","refresh_token") .scopes("read"); } @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints .tokenStore(tokenStore) .authenticationManager(authenticationManager); } @Override public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception { //允許表單認(rèn)證 oauthServer .allowFormAuthenticationForClients() .checkTokenAccess("permitAll()") .tokenKeyAccess("permitAll()"); } }
代碼中配置了一個(gè) client,id 是 client
,密碼 123456
。 authorizedGrantTypes
有 password
和refresh_token
兩種方式。
SecurityConfiguration
安全配置:
@Configuration @EnableWebSecurity public class SecurityConfiguration extends WebSecurityConfigurerAdapter { @Bean public TokenStore tokenStore() { return new InMemoryTokenStore(); } @Bean public BCryptPasswordEncoder encoder() { return new BCryptPasswordEncoder(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .passwordEncoder(encoder()) .withUser("user_1").password(encoder().encode("123456")).roles("USER") .and() .withUser("user_2").password(encoder().encode("123456")).roles("ADMIN"); } @Override protected void configure(HttpSecurity http) throws Exception { // @formatter:off http.csrf().disable() .requestMatchers() .antMatchers("/oauth/authorize") .and() .authorizeRequests() .anyRequest().authenticated() .and() .formLogin().permitAll(); // @formatter:on } @Override @Bean public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } }
上面在內(nèi)存中創(chuàng)建了兩個(gè)用戶,角色分別是 USER
和 ADMIN
。后續(xù)可考慮在數(shù)據(jù)庫或者 Redis 中存儲(chǔ)相關(guān)信息。
AuthUser
配置獲取用戶信息的 Controller:
@RestController public class AuthUser { @GetMapping("/oauth/user") public Principal user(Principal principal) { return principal; } }
application.yml
配置,主要就是配置個(gè)端口號(hào):
--- spring: profiles: active: dev application: name: auth-server server: port: 8101
客戶端配置
客戶端的配置比較簡單,主要代碼結(jié)構(gòu)如下:
application.yml
配置:
--- spring: profiles: active: dev application: name: client server: port: 8102 security: oauth2: client: client-id: client client-secret: 123456 access-token-uri: http://localhost:8101/oauth/token user-authorization-uri: http://localhost:8101/oauth/authorize scope: read use-current-uri: false resource: user-info-uri: http://localhost:8101/oauth/user
這里主要是配置了認(rèn)證服務(wù)器的相關(guān)地址以及客戶端的 id 和 密碼。user-info-uri
配置的就是服務(wù)器端獲取用戶信息的接口。
HelloController
訪問的資源,配置了 ADMIN
的角色才可以訪問:
@RestController public class HelloController { @RequestMapping("/hi") @PreAuthorize("hasRole('ADMIN')") public ResponseEntity<String> hi() { return ResponseEntity.ok().body("auth success!"); } }
WebSecurityConfiguration
相關(guān)安全配置:
@Configuration @EnableOAuth2Sso @EnableGlobalMethodSecurity(prePostEnabled = true) class WebSecurityConfiguration extends WebSecurityConfigurerAdapter { @Override public void configure(HttpSecurity http) throws Exception { http .csrf().disable() // 基于token,所以不需要session .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .authorizeRequests() .anyRequest().authenticated(); } }
其中 @EnableGlobalMethodSecurity(prePostEnabled = true)
開啟后,Spring Security 的 @PreAuthorize,@PostAuthorize
注解才可以使用。
@EnableOAuth2Sso
配置了單點(diǎn)登錄。
ClientApplication
:
@SpringBootApplication @EnableResourceServer public class ClientApplication { public static void main(String[] args) { SpringApplication.run(ClientApplication.class, args); } }
驗(yàn)證
啟動(dòng)項(xiàng)目后,我們使用 postman 來進(jìn)行驗(yàn)證。
首先是獲取 token:
選擇 POST 提交,地址為驗(yàn)證服務(wù)器的地址,參數(shù)中輸入 username
,password
,grant_type
和 scope
,其中 grant_type
需要輸入 password
。
然后在下面等 Authorization 標(biāo)簽頁中,選擇 Basic Auth,然后輸入 client 的 id 和 password。
{ "access_token": "02f501a9-c482-46d4-a455-bf79a0e0e728", "token_type": "bearer", "refresh_token": "0e62dddc-4f51-4cb5-81c3-5383fddbb81b", "expires_in": 41741, "scope": "read" }
此時(shí)就可以獲得 access_token
為: 02f501a9-c482-46d4-a455-bf79a0e0e728
。需要注意的是這里是用 user_2 獲取的 token,即角色是 ADMIN
。
然后我們?cè)龠M(jìn)行獲取資源的驗(yàn)證:
使用 GET 方法,參數(shù)中輸入 access_token,值輸入 02f501a9-c482-46d4-a455-bf79a0e0e728
。
點(diǎn)擊提交后即可獲取到結(jié)果。
如果我們不加上 token ,則會(huì)提示無權(quán)限。同樣如果我們換上 user_1 獲取的 token,因 user_1 的角色是 USER
,此資源需要 ADMIN
權(quán)限,則此處還是會(huì)獲取失敗。
簡單的例子就到這,后續(xù)有時(shí)間再加上其它功能吧,謝謝~
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Spring Security使用單點(diǎn)登錄的權(quán)限功能
- Spring?boot?security權(quán)限管理集成cas單點(diǎn)登錄功能的實(shí)現(xiàn)
- SpringSecurity OAuth2單點(diǎn)登錄和登出的實(shí)現(xiàn)
- 一個(gè)注解搞定Spring Security基于Oauth2的SSO單點(diǎn)登錄功能
- Spring Security基于JWT實(shí)現(xiàn)SSO單點(diǎn)登錄詳解
- 使用Spring Security OAuth2實(shí)現(xiàn)單點(diǎn)登錄
- SpringSecurity OAtu2+JWT實(shí)現(xiàn)微服務(wù)版本的單點(diǎn)登錄的示例
相關(guān)文章
Struts2學(xué)習(xí)筆記(4)-通配符的使用
本文主要介紹Struts2中通配符的使用,簡單實(shí)用,希望能給大家做一個(gè)參考。2016-06-06如何解決Gradle、Maven項(xiàng)目build后沒有mybatis的mapper.xml文件的問題
這篇文章主要介紹了如何解決Gradle、Maven項(xiàng)目build后沒有mybatis的mapper.xml文件的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-01-01java解析XML Node與Element的區(qū)別(推薦)
下面小編就為大家分享一篇java解析XML Node與Element的區(qū)別,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-01-01MyBatis標(biāo)簽之Select?resultType和resultMap詳解
這篇文章主要介紹了MyBatis標(biāo)簽之Select?resultType和resultMap,在MyBatis中有一個(gè)ResultMap標(biāo)簽,它是為了映射select標(biāo)簽查詢出來的結(jié)果集,下面使用一個(gè)簡單的例子,來介紹 resultMap 的使用方法,需要的朋友可以參考下2022-09-09