大體介紹
在本教程中还蹲,我們將討論如何使用Spring Security OAuth和Spring Boot實現(xiàn)SSO(單點登錄)。
我們將使用三個單獨的應(yīng)用程序:
授權(quán)服務(wù)器 - 這是中央身份驗證機制
兩個使用SSO的客戶端程序
- 簡單來說壁袄,當用戶試圖訪問需要認證的頁面的時候,他們將被重定向到授權(quán)服務(wù)器進行身份驗證,認證成功后才能訪問缸剪。
我們將使用OAuth2中的授權(quán)碼模式來進行身份驗證策添。
客戶端程序
我們先從客戶端應(yīng)用程序開始配置;我們將使用最簡單的Spring Boot配置來完成材部。
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>
Security相關(guān)配置
下面是在客戶端中關(guān)鍵的Security配置內(nèi)容唯竹,主要繼承WebSecurityConfigurerAdapter
:
@Configuration
@EnableOAuth2Sso
public class UiSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http.antMatcher("/**")
.authorizeRequests()
.antMatchers("/", "/login**")
.permitAll()
.anyRequest()
.authenticated();
}
}
-
antMatcher("/**")
表示匹配以/
開頭的路由 -
.authorizeRequests()
表示以authorizeRequests
開始進行驗證 -
.antMatchers("/", "/login**").permitAll()
表示允許/
(首頁)和/login
開頭的路由通過乐导,因為我們驗證之前要允許別人訪問這些頁面。 -
.anyRequest().authenticated()
表示其它的路由都需要經(jīng)過驗證
我們這個客戶端程序還有一個核心的點摩窃,就是我們要加上@EnableOAuth2Sso
注解兽叮,以表明是一個SSO應(yīng)用配置。
接下來就是啟動文件的配置:
server:
port: 8082
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
我們在controller定義一個路由猾愿,訪問 http://127.0.0.1:8082/admin/ 會直接訪問不通鹦聪。接下來,我們繼續(xù)配置認證服務(wù)器蒂秘,讓程序可以繼續(xù)泽本。
@RestController
@RequestMapping("/admin")
@Validated
public class AdminController {
@RequestMapping(value="/")
public PageInfo listByPage() {
return "這是一個分頁列表程序";
}
}
認證服務(wù)器
接下來我們來討論怎么配置認證服務(wù)器相關(guān)的內(nèi)容。
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>
認證配置
在這里我要重點理解將授權(quán)服務(wù)器和資源服務(wù)器一起運行规丽,作為一個應(yīng)用程序來部署蒲牧。
首先,我們先配置資源服務(wù)器赌莺,在啟動類中冰抢,加入@EnableResourceServer
注解:
@SpringBootApplication
@EnableResourceServer
public class AuthorizationServerApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(AuthorizationServerApplication.class, args);
}
}
然后配置我們的認證服務(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:8081/login","http://localhost:8083/login"); //有多個客戶端程序可以繼續(xù)加
}
}
請出注意,我們這里使用的是authorization_code
授權(quán)模式艘狭。
另外挎扰,請注意autoApprove設(shè)置為true,那么我們就不會被重定向巢音,并且可以提升為手動批準任何的scopes遵倦。
認證信息相關(guān)配置
首先,在我們的application.yml
配置如下基本信息
server:
port: 8081
servlet:
context-path : /auth
現(xiàn)在官撼,我們配置一些登錄信息梧躺。
@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();
}
}
@Order(1)
代表優(yōu)先執(zhí)行,這里代表先執(zhí)行SecurityConfig
的配置傲绣,在執(zhí)行AuthServerConfig
的配置掠哥。
withUser
和password
代表相關(guān)的認證信息,該信息可以結(jié)合實際情況在數(shù)據(jù)庫等途徑取出斜筐。
BCryptPasswordEncoder
對密碼進行加密龙致。
認證信息
最后,我們可以建立一個路由來獲取用戶的認證相關(guān)的信息顷链。
@RestController
public class UserController {
@GetMapping("/user/me")
public Principal user(Principal principal) {
return principal;
}
}