使用Spring Security OAuth2實(shí)現(xiàn)單點(diǎn)登錄
1.概述
在本教程中,我們將討論如何使用Spring Security OAuth和Spring Boot實(shí)現(xiàn)SSO - 單點(diǎn)登錄。
我們將使用三個(gè)單獨(dú)的應(yīng)用程序:
•授權(quán)服務(wù)器 - 這是中央身份驗(yàn)證機(jī)制
•兩個(gè)客戶端應(yīng)用程序:使用SSO的應(yīng)用程序
非常簡(jiǎn)單地說(shuō),當(dāng)用戶試圖訪問(wèn)客戶端應(yīng)用程序中的安全頁(yè)面時(shí),他們將被重定向到首先通過(guò)身份驗(yàn)證服務(wù)器進(jìn)行身份驗(yàn)證。
我們將使用OAuth2中的授權(quán)代碼授權(quán)類型來(lái)驅(qū)動(dòng)身份驗(yàn)證委派。
2.客戶端應(yīng)用程序
讓我們從客戶端應(yīng)用程序開(kāi)始;當(dāng)然,我們將使用Spring Boot來(lái)最小化配置:
2.1。 Maven依賴
首先,我們需要在pom.xml中使用以下依賴項(xiàng):
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.security.oauth.boot</groupId> <artifactId>spring-security-oauth2-autoconfigure</artifactId> <version>2.0.1.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.thymeleaf.extras</groupId> <artifactId>thymeleaf-extras-springsecurity4</artifactId> </dependency>
2.2。Security配置
接下來(lái),最重要的部分,我們的客戶端應(yīng)用程序的Security配置:
@Configuration
@EnableOAuth2Sso
public class UiSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http.antMatcher("/**")
.authorizeRequests()
.antMatchers("/", "/login**")
.permitAll()
.anyRequest()
.authenticated();
}
}
當(dāng)然,這種配置的核心部分是我們用于啟用單點(diǎn)登錄的@ EnableOAuth2Sso注釋。
請(qǐng)注意,我們需要擴(kuò)展WebSecurityConfigurerAdapter - 如果沒(méi)有它,所有路徑都將受到保護(hù) - 因此用戶將在嘗試訪問(wèn)任何頁(yè)面時(shí)重定向以登錄。在我們的例子中,首頁(yè)和登錄頁(yè)面是唯一可以在沒(méi)有身份驗(yàn)證的情況下訪問(wèn)的頁(yè)面。
最后,我們還定義了一個(gè)RequestContextListener bean來(lái)處理請(qǐng)求范圍。
application.yml: server: port: 8082 servlet: context-path: /ui session: cookie: name: UISESSION security: basic: enabled: false oauth2: client: clientId: SampleClientId clientSecret: secret accessTokenUri: http://localhost:8081/auth/oauth/token userAuthorizationUri: http://localhost:8081/auth/oauth/authorize resource: userInfoUri: http://localhost:8081/auth/user/me spring: thymeleaf: cache: false
一些快速說(shuō)明:
•我們禁用了默認(rèn)的基本身份驗(yàn)證
•accessTokenUri是獲取訪問(wèn)令牌的URI
•userAuthorizationUri是用戶將被重定向到的授權(quán)URI
•userInfoUri用戶端點(diǎn)的URI,用于獲取當(dāng)前用戶詳細(xì)信息
另請(qǐng)注意,在我們的示例中,我們推出了授權(quán)服務(wù)器,但當(dāng)然我們也可以使用其他第三方提供商,如Facebook或GitHub。
2.3。前端
現(xiàn)在,讓我們來(lái)看看客戶端應(yīng)用程序的前端配置。我們不會(huì)在這里專注于此,主要是因?yàn)槲覀円呀?jīng)在網(wǎng)站上介紹過(guò)。
我們的客戶端應(yīng)用程序有一個(gè)非常簡(jiǎn)單的前端;這是index.html:
<h1>Spring Security SSO</h1> <a href="securedPage" rel="external nofollow" >Login</a>
和securedPage.html:
<h1>Secured Page</h1>
Welcome, <span th:text="${#authentication.name}">Name</span>
securedPage.html頁(yè)面需要對(duì)用戶進(jìn)行身份驗(yàn)證。如果未經(jīng)身份驗(yàn)證的用戶嘗試訪問(wèn)securedPage.html,則會(huì)首先將其重定向到登錄頁(yè)面。
3. Auth服務(wù)器
現(xiàn)在讓我們?cè)谶@里討論我們的授權(quán)服務(wù)器。
3.1。 Maven依賴
首先,我們需要在pom.xml中定義依賴項(xiàng):
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.security.oauth</groupId> <artifactId>spring-security-oauth2</artifactId> <version>2.3.3.RELEASE</version> </dependency>
3.2。 OAuth配置
重要的是要理解我們將在這里一起運(yùn)行授權(quán)服務(wù)器和資源服務(wù)器,作為單個(gè)可部署單元。
讓我們從資源服務(wù)器的配置開(kāi)始 :
@SpringBootApplication
@EnableResourceServer
public class AuthorizationServerApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(AuthorizationServerApplication.class, args);
}
}
然后,我們將配置我們的授權(quán)服務(wù)器:
@Configuration
@EnableAuthorizationServer
public class AuthServerConfig extends AuthorizationServerConfigurerAdapter {
@Autowired
private BCryptPasswordEncoder passwordEncoder;
@Override
public void configure(
AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer.tokenKeyAccess("permitAll()")
.checkTokenAccess("isAuthenticated()");
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("SampleClientId")
.secret(passwordEncoder.encode("secret"))
.authorizedGrantTypes("authorization_code")
.scopes("user_info")
.autoApprove(true)
.redirectUris("http://localhost:8082/ui/login","http://localhost:8083/ui2/login");
}
}
請(qǐng)注意我們?nèi)绾蝺H使用authorization_code grant類型啟用簡(jiǎn)單客戶端。
另外,請(qǐng)注意autoApprove如何設(shè)置為true,以便我們不會(huì)被重定向并手動(dòng)批準(zhǔn)任何范圍。
3.3。Security配置
首先,我們將通過(guò)application.properties禁用默認(rèn)的基本身份驗(yàn)證:
server.port=8081 server.servlet.context-path=/auth
現(xiàn)在,讓我們轉(zhuǎn)到配置并定義一個(gè)簡(jiǎn)單的表單登錄機(jī)制:
@Configuration
@Order(1)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.requestMatchers()
.antMatchers("/login", "/oauth/authorize")
.and()
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin().permitAll();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("john")
.password(passwordEncoder().encode("123"))
.roles("USER");
}
@Bean
public BCryptPasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
}
請(qǐng)注意,我們使用簡(jiǎn)單的內(nèi)存中身份驗(yàn)證,但我們可以簡(jiǎn)單地將其替換為自定義userDetailsService。
3.4。用戶端
最后,我們將創(chuàng)建我們之前在配置中使用的用戶端:
@RestController
public class UserController {
@GetMapping("/user/me")
public Principal user(Principal principal) {
return principal;
}
}
當(dāng)然,這將使用JSON表示返回用戶數(shù)據(jù)。
4。結(jié)論
在本快速教程中,我們專注于使用Spring Security Oauth2和Spring Boot實(shí)現(xiàn)單點(diǎn)登錄。
與往常一樣,可以在GitHub上找到完整的源代碼。
總結(jié)
以上所述是小編給大家介紹的使用Spring Security OAuth2實(shí)現(xiàn)單點(diǎn)登錄,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
如果你覺(jué)得本文對(duì)你有幫助,歡迎轉(zhuǎn)載,煩請(qǐng)注明出處,謝謝!
- 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 單點(diǎn)登錄簡(jiǎn)單示例詳解
- SpringSecurity OAtu2+JWT實(shí)現(xiàn)微服務(wù)版本的單點(diǎn)登錄的示例
相關(guān)文章
java正則表達(dá)式實(shí)現(xiàn)提取需要的字符并放入數(shù)組【ArrayList數(shù)組去重復(fù)功能】
這篇文章主要介紹了java正則表達(dá)式實(shí)現(xiàn)提取需要的字符并放入數(shù)組,即基于正則的ArrayList數(shù)組去重復(fù)功能,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2017-01-01
Spring中@Transactional注解關(guān)鍵屬性和用法小結(jié)
在Spring框架中,@Transactional 是一個(gè)注解,用于聲明事務(wù)性的方法,它提供了一種聲明式的事務(wù)管理方式,避免了在代碼中直接編寫(xiě)事務(wù)管理相關(guān)的代碼,本文給大家介紹@Transactional 注解的一些關(guān)鍵屬性和用法,感興趣的朋友一起看看吧2023-12-12
解決SpringBoot整合ElasticSearch遇到的連接問(wèn)題
這篇文章主要介紹了解決SpringBoot整合ElasticSearch遇到的連接問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-08-08
java 非對(duì)稱加密算法DH實(shí)現(xiàn)詳解
這篇文章主要介紹了java 非對(duì)稱加密算法DH實(shí)現(xiàn)詳解 ,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-07-07
Spring的異常處理@ExceptionHandler注解解析
這篇文章主要介紹了Spring的異常處理@ExceptionHandler注解解析,當(dāng)一個(gè)Controller中有方法加了@ExceptionHandler之后,這個(gè)Controller其他方法中沒(méi)有捕獲的異常就會(huì)以參數(shù)的形式傳入加了@ExceptionHandler注解的那個(gè)方法中,需要的朋友可以參考下2023-12-12
Spring注解@Configuration與@Bean注冊(cè)組件的使用詳解
這篇文章主要介紹了SpringBoot中的注解@Configuration與@Bean注冊(cè)組件的使用,具有很好的參考價(jià)值,希望對(duì)大家有所幫助2022-06-06
Spring Boot實(shí)現(xiàn)分布式鎖的自動(dòng)釋放的示例代碼
在實(shí)際開(kāi)發(fā)中,我們可以使用 Redis、Zookeeper 等分布式系統(tǒng)來(lái)實(shí)現(xiàn)分布式鎖,本文將介紹如何使用 Spring Boot 來(lái)實(shí)現(xiàn)分布式鎖的自動(dòng)釋放,感興趣的朋友跟隨小編一起看看吧2023-06-06

