Spring Security 單點(diǎn)登錄簡單示例詳解
Overview
最近在弄單點(diǎn)登錄,踩了不少坑,所以記錄一下,做了個簡單的例子。
目標(biāo):認(rèn)證服務(wù)器認(rèn)證后獲取 token,客戶端訪問資源時帶上 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)鍵代碼有如下幾個文件:

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()");
}
}
代碼中配置了一個 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)建了兩個用戶,角色分別是 USER 和 ADMIN。后續(xù)可考慮在數(shù)據(jù)庫或者 Redis 中存儲相關(guān)信息。
AuthUser 配置獲取用戶信息的 Controller:
@RestController
public class AuthUser {
@GetMapping("/oauth/user")
public Principal user(Principal principal) {
return principal;
}
}
application.yml 配置,主要就是配置個端口號:
--- 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)證
啟動項(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"
}
此時就可以獲得 access_token 為: 02f501a9-c482-46d4-a455-bf79a0e0e728。需要注意的是這里是用 user_2 獲取的 token,即角色是 ADMIN。
然后我們再進(jìn)行獲取資源的驗(yàn)證:

使用 GET 方法,參數(shù)中輸入 access_token,值輸入 02f501a9-c482-46d4-a455-bf79a0e0e728 。
點(diǎn)擊提交后即可獲取到結(jié)果。
如果我們不加上 token ,則會提示無權(quán)限。同樣如果我們換上 user_1 獲取的 token,因 user_1 的角色是 USER,此資源需要 ADMIN 權(quán)限,則此處還是會獲取失敗。
簡單的例子就到這,后續(xù)有時間再加上其它功能吧,謝謝~
以上就是本文的全部內(nèi)容,希望對大家的學(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)
- 一個注解搞定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)文章
Java上傳文件到服務(wù)器指定文件夾實(shí)現(xiàn)過程圖解
這篇文章主要介紹了Java上傳文件到服務(wù)器指定文件夾實(shí)現(xiàn)過程圖解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-08-08
Java 遞歸查詢部門樹形結(jié)構(gòu)數(shù)據(jù)的實(shí)踐
本文主要介紹了Java 遞歸查詢部門樹形結(jié)構(gòu)數(shù)據(jù)的實(shí)踐,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-09-09
Java中遞歸構(gòu)建樹形結(jié)構(gòu)的算法解讀
該文章介紹了如何使用Java遞歸算法構(gòu)建樹形結(jié)構(gòu),通過定義樹節(jié)點(diǎn)類,遍歷扁平數(shù)據(jù)列表,將節(jié)點(diǎn)加入對應(yīng)父節(jié)點(diǎn)的子節(jié)點(diǎn)列表中,實(shí)現(xiàn)從扁平數(shù)據(jù)到樹形結(jié)構(gòu)的轉(zhuǎn)換2025-03-03
java 實(shí)現(xiàn)將Object類型轉(zhuǎn)換為int類型
這篇文章主要介紹了java 實(shí)現(xiàn)將Object類型轉(zhuǎn)換為int類型的操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-07-07
SpringBoot部署到外部Tomcat無法注冊到Nacos服務(wù)端的解決思路
這篇文章主要介紹了SpringBoot部署到外部Tomcat無法注冊到Nacos服務(wù)端,本文給大家分享完美解決思路,結(jié)合實(shí)例代碼給大家講解的非常詳細(xì),需要的朋友可以參考下2023-03-03
IDEA2023 Maven3.9.1+Tomcat10.1.8配置并搭建Servlet5.0的框架實(shí)現(xiàn)
本文主要介紹了IDEA2023 Maven3.9.1+Tomcat10.1.8配置并搭建Servlet5.0的框架實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-07-07

