1.概述
在本教程中,我們將討論如何使用Spring Security OAuth和Spring Boot實現SSO - 單點登錄。
我們將使用三個單獨的應用程序:
- 授權服務器 - 這是中央身份驗證機制
- 兩個客戶端應用程序:使用SSO的應用程序
非常簡單地說,當用戶試圖訪問客戶端應用程序中的安全頁面時,他們將被重定向到首先通過身份驗證服務器進行身份驗證。
我們將使用OAuth2中的授權代碼授權類型來驅動身份驗證委派。
2.客戶端應用程序
讓我們從客戶端應用程序開始;當然,我們將使用Spring Boot來最小化配置:
2.1。 Maven依賴
首先,我們需要在pom.xml中使用以下依賴項:
<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配置
接下來,最重要的部分,我們的客戶端應用程序的Security配置:
@Configuration
@EnableOAuth2Sso
public class UiSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http.antMatcher("/**")
.authorizeRequests()
.antMatchers("/", "/login**")
.permitAll()
.anyRequest()
.authenticated();
}
}
當然,這種配置的核心部分是我們用於啟用單點登錄的@ EnableOAuth2Sso注釋。
請注意,我們需要擴展WebSecurityConfigurerAdapter - 如果沒有它,所有路徑都將受到保護 - 因此用戶將在嘗試訪問任何頁面時重定向以登錄。在我們的例子中,首頁和登錄頁面是唯一可以在沒有身份驗證的情況下訪問的頁面。
最后,我們還定義了一個RequestContextListener bean來處理請求范圍。
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
一些快速說明:
- 我們禁用了默認的基本身份驗證
- accessTokenUri是獲取訪問令牌的URI
- userAuthorizationUri是用戶將被重定向到的授權URI
- userInfoUri用戶端點的URI,用於獲取當前用戶詳細信息
另請注意,在我們的示例中,我們推出了授權服務器,但當然我們也可以使用其他第三方提供商,如Facebook或GitHub。
2.3。前端
現在,讓我們來看看客戶端應用程序的前端配置。我們不會在這里專注於此,主要是因為我們已經在網站上介紹過。
我們的客戶端應用程序有一個非常簡單的前端;這是index.html:
<h1>Spring Security SSO</h1>
<a href="securedPage">Login</a>
和securedPage.html:
<h1>Secured Page</h1>
Welcome, <span th:text="${#authentication.name}">Name</span>
securedPage.html頁面需要對用戶進行身份驗證。如果未經身份驗證的用戶嘗試訪問securedPage.html,則會首先將其重定向到登錄頁面。
3. Auth服務器
現在讓我們在這里討論我們的授權服務器。
3.1。 Maven依賴
首先,我們需要在pom.xml中定義依賴項:
<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配置
重要的是要理解我們將在這里一起運行授權服務器和資源服務器,作為單個可部署單元。
讓我們從資源服務器的配置開始 :
@SpringBootApplication
@EnableResourceServer
public class AuthorizationServerApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(AuthorizationServerApplication.class, args);
}
}
然后,我們將配置我們的授權服務器:
@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");
}
}
請注意我們如何僅使用authorization_code grant類型啟用簡單客戶端。
另外,請注意autoApprove如何設置為true,以便我們不會被重定向並手動批准任何范圍。
3.3。Security配置
首先,我們將通過application.properties禁用默認的基本身份驗證:
server.port=8081
server.servlet.context-path=/auth
現在,讓我們轉到配置並定義一個簡單的表單登錄機制:
@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();
}
}
請注意,我們使用簡單的內存中身份驗證,但我們可以簡單地將其替換為自定義userDetailsService。
3.4。用戶端
最后,我們將創建我們之前在配置中使用的用戶端:
@RestController
public class UserController {
@GetMapping("/user/me")
public Principal user(Principal principal) {
return principal;
}
}
當然,這將使用JSON表示返回用戶數據。
4。結論
在本快速教程中,我們專注於使用Spring Security Oauth2和Spring Boot實現單點登錄。
與往常一樣,可以在GitHub上找到完整的源代碼。