一元扔、客戶端模式簡介
??客戶端模式(Client Credentials Grant)指客戶端以自己的名義,而不是以用戶的名義旋膳,向"服務提供商"進行認證澎语。嚴格地說,客戶端模式并不屬于OAuth框架所要解決的問題验懊。在這種模式中擅羞,用戶直接向客戶端注冊,客戶端以自己的名義要求"服務提供商"提供服務义图,其實不存在授權(quán)問題。
??這種模式直接根據(jù)client的id和密鑰即可獲取token碱工,無需用戶參與這種模式比較合適消費api的后端服務娃承,比如拉取一組用戶信息等,不支持refresh token怕篷,主要是沒有必要历筝。
(A)客戶端向認證服務器進行身份認證,并要求一個訪問令牌匙头。
客戶端發(fā)出的HTTP請求漫谷,包含以下參數(shù):
granttype:表示授權(quán)類型,此處的值固定為"clientcredentials"蹂析,必選項舔示。
scope:表示權(quán)限范圍,可選項电抚。
POST /token HTTP/1.1
Host: server.example.com
Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW
Content-Type: application/x-www-form-urlencoded
grant_type=client_credentials
認證服務器必須以某種方式惕稻,驗證客戶端身份。
(B)認證服務器確認無誤后蝙叛,向客戶端提供訪問令牌俺祠。
認證服務器向客戶端發(fā)送訪問令牌,借帘。
HTTP/1.1 200 OK
Content-Type: application/json;charset=UTF-8
Cache-Control: no-store
Pragma: no-cache
{
"access_token":"2YotnFZFEjr1zCsicMWpAA",
"token_type":"example",
"expires_in":3600,
"example_parameter":"example_value"
}
二蜘渣、Maven依賴
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-oauth2</artifactId>
</dependency>
三、代碼實現(xiàn)
- 認證服務配置
/**
* 認證服務配置
*/
@Configuration
@EnableAuthorizationServer
@Slf4j
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private UserDetailsService userService;
@Autowired
private TokenStore tokenStore;
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("client") // 客戶端ID
.scopes("app") // 允許的授權(quán)范圍
.authorizedGrantTypes("client_credentials") // 設置驗證方式
.secret(new BCryptPasswordEncoder().encode("123456")); //必須加密
.accessTokenValiditySeconds(10000) // token過期時間
.refreshTokenValiditySeconds(10000); // refresh過期時間;
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.tokenStore(tokenStore)
.authenticationManager(authenticationManager)
.userDetailsService(userService); //配置userService 這樣每次認證的時候會去檢驗用戶是否鎖定肺然,有效等
}
@Bean
public TokenStore tokenStore() {
// 使用內(nèi)存的tokenStore
return new InMemoryTokenStore();
}
}
- 資源服務配置
/**
* 資源服務配置
*/
@Configuration
@EnableResourceServer()
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.authorizeRequests()
.antMatchers("/oauth/authorize","/login")
.permitAll()
.antMatchers(HttpMethod.OPTIONS)
.permitAll()
.antMatchers("/account/**").authenticated()
.and().httpBasic()
.and().csrf().disable();
}
}
其它代碼同密碼模式蔫缸。
四、測試
-
令牌獲取
-
接口訪問