教程由來:項目需要爲第三方客戶端提供授權和資源訪問,無疑OAuth2現在是最好的方式,如果OAuth2相關知識大家還不夠了解,請移步到阮一峯的理解OAuth2.0,本文實戰爲主,理論方面請自行查閱相關資料。
1. OAuth2的四種模式
- 授權碼模式(authorization code)(最正統的方式,也是目前絕大多數系統所採用的)(支持refresh token) (用在服務端應用之間)
- 密碼模式(resource owner password credentials)(爲遺留系統設計) (支持refresh token)
- 簡化模式(implicit)(爲web瀏覽器應用設計)(不支持refresh token) (用在移動app或者web app,這些app是在用戶的設備上的,如在手機上調起微信來進行認證授權)
- 客戶端模式(client credentials)(爲後臺api服務消費者設計) (不支持refresh token) (爲後臺api服務消費者設計)
本文采用數據庫的方式對上述四種模式進行配置,網上絕大多數都是配置在內存中的demo,學習尚可,真實的開發環境卻是還遠遠不夠。
廢話也就不多說了,咱進入正題吧。
2. 所需依賴
//Springboot版本爲2.0.2.RELEASE
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- spring-security-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- OAuth2-->
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<version>2.3.0.RELEASE</version>
</dependency>
3. 授權服務器
授權服務器是OAuth2的兩大核心之一,它將根據不同的授權類型爲客戶端提供不同的獲取令牌的方式。
@Configuration
@EnableAuthorizationServer // 授權服務器核心註解
protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
@Autowired
AuthenticationManager authenticationManager; // 注入manager
@Autowired
private DataSource dataSource; // 注入數據源
@Autowired
SecurityUserService userDetailsService; //
@Autowired
ClientDetailsService clientDetailsService;
@Autowired
private AuthorizationCodeServices authorizationCodeServices;
// redis 的相關配置已註釋,若需啓用,在tokenStore中注入即可。
// @Autowired
// private RedisConnectionFactory redisConnectionFactory;
// @Bean
// public TokenStore redisTokenStore() {
// return new RedisTokenStore(redisConnectionFactory);
// }
/**
* 密碼加密
*/
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
/**
* ClientDetails實現
* @return
*/
@Bean
public ClientDetailsService clientDetails() {
return new JdbcClientDetailsService(dataSource);
}
@Bean
public TokenStore tokenStore() {
return new JdbcTokenStore(dataSource);
}
/**
* 加入對授權碼模式的支持
* @param dataSource
* @return
*/
@Bean
public AuthorizationCodeServices authorizationCodeServices(DataSource dataSource) {
return new JdbcAuthorizationCodeServices(dataSource);
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
// 1. 數據庫的方式
clients.withClientDetails(clientDetails());
// 2. 在內存中配置,這種方式不夠靈活,學習倒是沒有問題
// //配置兩個客戶端,一個用於password認證一個用於client認證
// clients.inMemory().withClient("client_1")
// .resourceIds(DEMO_RESOURCE_ID)
// .authorizedGrantTypes("client_credentials", "refresh_token")
// .scopes("select")
// .authorities("client")
// .secret("123456")
// .and().withClient("client_2")
// .resourceIds(DEMO_RESOURCE_ID)
// .authorizedGrantTypes("password", "refresh_token")
// .scopes("select")
// .authorities("client")
// .secret("123456");
}
/**
* 聲明授權和token的端點以及token的服務的一些配置信息,
* 比如採用什麼存儲方式、token的有效期等
* @param endpoints
*/
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
endpoints
// 使用redis的配置
// .tokenStore(new RedisTokenStore(redisConnectionFactory))
.tokenStore(tokenStore())
.authenticationManager(authenticationManager)
.userDetailsService(userDetailsService)
.authorizationCodeServices(authorizationCodeServices)
.setClientDetailsService(clientDetailsService);
}
/**
* 聲明安全約束,哪些允許訪問,哪些不允許訪問
* @param oauthServer
*/
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) {
// 允許表單認證
oauthServer.allowFormAuthenticationForClients();
// 配置BCrypt加密
oauthServer.passwordEncoder(passwordEncoder());
// 對於CheckEndpoint控制器[框架自帶的校驗]的/oauth/check端點允許所有客戶端發送器請求而不會被Spring-security攔截
oauthServer.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()");
// 此處可添加自定義過濾器,對oauth相關的請求做進一步處理
// oauthServer.addTokenEndpointAuthenticationFilter(new Oauth2Filter());
}
}
4. 資源服務器
1. 資源服務器主要配置攔截的路徑,以及訪問攔截的URL所需要的權限。
2. 本文,主系統、資源服務器和授權服務器放在一起的,很多人說這樣配置security的主過濾器和資源服務器的過濾器會衝突,其實是不會的,資源服務器會優先於security主過濾器攔截你訪問的URL,當然你也沒必要在類上配置Order去改變他們的優先級,你只需要注意不要讓你的資源服務器把security主過濾器放行的資源給攔截了就行。
下面直接上代碼
@Configuration
@EnableResourceServer
protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
private static final String RESOURCE_ID = "oauth2";
@Override
public void configure(ResourceServerSecurityConfigurer resources) {
// 如果關閉 stateless,則 accessToken 使用時的 session id 會被記錄,後續請求不攜帶 accessToken 也可以正常響應
// 如果 stateless 爲 true 打開狀態,則 每次請求都必須攜帶 accessToken 請求才行,否則將無法訪問
resources.resourceId(RESOURCE_ID).stateless(true);
}
/**
* 爲oauth2單獨創建角色,這些角色只具有訪問受限資源的權限,可解決token失效的問題
* @param http
* @throws Exception
*/
@Override
public void configure(HttpSecurity http) throws Exception {
http
// 獲取登錄用戶的 session
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
.and()
// 資源服務器攔截的路徑 注意此路徑不要攔截主過濾器放行的URL
.requestMatchers().antMatchers("/authmenu/**");
http
.authorizeRequests()
// 配置資源服務器已攔截的路徑纔有效
.antMatchers("/authmenu/**").authenticated();
// .access(" #oauth2.hasScope('select') or hasAnyRole('ROLE_超級管理員', 'ROLE_設備管理員')");
http
.exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler())
.and()
.authorizeRequests()
.anyRequest()
.authenticated();
}
}
5. 主過濾器的配置
關於主過濾器,每個人的配置可能不太一樣,都是有一點是必須的,就是必須把authenticationManagerBean方法註冊爲bean,本文是基於前後端分離而開發,下文只出示了與OAuth2相關的配置,詳細信息請參考文末的GitHub地址。
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest()
.authenticated()
.withObjectPostProcessor(urlObjectPostProcessor())
.and()
.formLogin()
.loginPage("/login")
.loginProcessingUrl("/login")
.usernameParameter("username")
.passwordParameter("password")
.permitAll()
.failureHandler(securityAuthenticationFailureHandler)
.successHandler(userLoginSuccessHandler)
.and()
.exceptionHandling()
.authenticationEntryPoint(securityAuthenticationEntryPoint)
.and()
.logout()
.deleteCookies("remove")
.invalidateHttpSession(false)
.logoutUrl("/logout")
.logoutSuccessHandler(securityLogoutSuccessHandler)
.permitAll()
.and()
.csrf().requireCsrfProtectionMatcher(new AntPathRequestMatcher("/oauth/authorize"))
.disable();
http
.sessionManagement()
// 無效session跳轉
.invalidSessionUrl("/login")
.maximumSessions(1)
// session過期跳轉
.expiredUrl("/login")
.sessionRegistry(sessionRegistry());
}
6. OAuth2所需數據表
--
-- Oauth2 sql -- MYSQL
--
Drop table if exists oauth_client_details;
create table oauth_client_details (
client_id VARCHAR(255) PRIMARY KEY,
resource_ids VARCHAR(255),
client_secret VARCHAR(255),
scope VARCHAR(255),
authorized_grant_types VARCHAR(255),
web_server_redirect_uri VARCHAR(255),
authorities VARCHAR(255),
access_token_validity INTEGER,
refresh_token_validity INTEGER,
additional_information TEXT,
create_time timestamp default now(),
archived tinyint(1) default '0',
trusted tinyint(1) default '0',
autoapprove VARCHAR (255) default 'false'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Drop table if exists oauth_access_token;
create table oauth_access_token (
create_time timestamp default now(),
token_id VARCHAR(255),
token BLOB,
authentication_id VARCHAR(255),
user_name VARCHAR(255),
client_id VARCHAR(255),
authentication BLOB,
refresh_token VARCHAR(255)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Drop table if exists oauth_refresh_token;
create table oauth_refresh_token (
create_time timestamp default now(),
token_id VARCHAR(255),
token BLOB,
authentication BLOB
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Drop table if exists oauth_code;
create table oauth_code (
create_time timestamp default now(),
code VARCHAR(255),
authentication BLOB
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- Add indexes
create index token_id_index on oauth_access_token (token_id);
create index authentication_id_index on oauth_access_token (authentication_id);
create index user_name_index on oauth_access_token (user_name);
create index client_id_index on oauth_access_token (client_id);
create index refresh_token_index on oauth_access_token (refresh_token);
create index token_id_index on oauth_refresh_token (token_id);
create index code_index on oauth_code (code);
點擊此處,獲取OAuth2表中所涉及字段的詳細說明 看起來不方便的話,可以直接到源碼中通過HTML的方式查看。
最後附上我數據庫的配置截圖,嗯,差不多了。
截圖:
7. 測試
7.1 授權碼模式測試
1. 直接請求獲取授權碼:http://localhost:9999/oauth/authorize?client_id=sheep1&redirect_uri=http://localhost:8086/login&response_type=code&scope=all
2. 訪問登錄頁面:http://localhost:9999/static/login.html
爲什麼不直接使用postman測試,而要準備一個登錄頁面?
1. 首先獲取授權碼,要求用戶是已經登錄的狀態,就是未登錄的用戶是不能請求到授權碼的
2. 請求授權碼的時候,服務器收到請求,驗證參數無誤之後,會自動響應到 請求授權碼的重定向地址,並在重定向地址後面附加 我們需要的授權碼。
3. 登錄成功後,再次請求授權碼:http://localhost:9999/oauth/authorize?client_id=sheep1&redirect_uri=http://localhost:8086/login&response_type=code&scope=all
4. 拿到授權碼再去獲取需要的token,注意此處是post請求,所以需要你在postman上測試:http://localhost:9999/oauth/token?client_id=sheep1&client_secret=123456&grant_type=authorization_code&code=Y1e37c&redirect_uri=http://localhost:8086/login
5. 使用獲取到的token獲取服務器的資源:http://localhost:9999/user/oauth/all?access_token=1542569a-ca94-4015-90ee-402158be4f78
授權碼和password模式測試如下:
項目Github地址:https://github.com/Janche/springboot-security-project.git (你的star是對我最大的支持,測試OAuth2時,可以切換到 oauth2分支)
oauth2相關資料參考