截止目前客戶端信息和授權(quán)碼仍然存儲(chǔ)在內(nèi)存中属韧,生產(chǎn)環(huán)境中通常會(huì)存儲(chǔ)在數(shù)據(jù)庫中述吸,下邊將完善環(huán)境的配置。
一、創(chuàng)建表
1登舞、接入客戶端信息表 oauth_client_details
CREATE TABLE `oauth_client_details` (
`client_id` varchar(255) COLLATE utf8_croatian_ci NOT NULL COMMENT '客戶端標(biāo)識(shí)',
`resource_ids` varchar(255) COLLATE utf8_croatian_ci DEFAULT NULL COMMENT '接入資源列表',
`client_secret` varchar(255) COLLATE utf8_croatian_ci DEFAULT NULL COMMENT '客戶端秘鑰',
`scope` varchar(255) COLLATE utf8_croatian_ci DEFAULT NULL,
`authorized_grant_types` varchar(255) COLLATE utf8_croatian_ci DEFAULT NULL,
`web_server_redirect_uri` varchar(255) COLLATE utf8_croatian_ci DEFAULT NULL,
`authorities` varchar(255) COLLATE utf8_croatian_ci DEFAULT NULL,
`access_token_validity` int(11) DEFAULT NULL,
`refresh_token_validity` int(11) DEFAULT NULL,
`additional_information` longtext COLLATE utf8_croatian_ci,
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`archived` tinyint(4) DEFAULT NULL,
`trusted` tinyint(4) DEFAULT NULL,
`autoapprove` varchar(255) COLLATE utf8_croatian_ci DEFAULT NULL,
PRIMARY KEY (`client_id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_croatian_ci ROW_FORMAT=DYNAMIC COMMENT='接入客戶端信息';
-- 初始化數(shù)據(jù)
INSERT INTO oauth2.oauth_client_details (client_id, resource_ids, client_secret, scope, authorized_grant_types, web_server_redirect_uri, authorities, access_token_validity, refresh_token_validity, additional_information, create_time, archived, trusted, autoapprove) VALUES ('c1', 'res1', '$2a$10$iDXj8iLaUNVZoJ2M5xkkb./o25cvWpNvB6cqmDBBeiRcDOBCnSf/.', 'ROLE_ADMIN,ROLE_USER,ROLE_API', 'client_credentials,password,authorization_code,implicit,refresh_token', 'http://www.baidu.com', null, 7200, 259200, null, '2019-12-08 09:55:11', 0, 0, 'false');
INSERT INTO oauth2.oauth_client_details (client_id, resource_ids, client_secret, scope, authorized_grant_types, web_server_redirect_uri, authorities, access_token_validity, refresh_token_validity, additional_information, create_time, archived, trusted, autoapprove) VALUES ('c2', 'res2', '$2a$10$iDXj8iLaUNVZoJ2M5xkkb./o25cvWpNvB6cqmDBBeiRcDOBCnSf/.', 'ROLE_API', 'client_credentials,password,authorization_code,implicit,refresh_token', 'http://www.baidu.com', null, 3153600, 25920000, null, '2019-09-09 21:48:51', 0, 0, 'false');
2贰逾、授權(quán)碼表 oauth_code Spring Security OAuth2使用,用來存儲(chǔ)授權(quán)碼
CREATE TABLE `oauth_code` (
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`code` varchar(255) COLLATE utf8_croatian_ci DEFAULT NULL,
`authentication` blob,
KEY `code_index` (`code`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_croatian_ci ROW_FORMAT=COMPACT;
二菠秒、配置權(quán)限服務(wù)
1疙剑、修改AuthorizationServer
ClientDetailsService
和AuthorizationCodeServices
從數(shù)據(jù)庫中讀取數(shù)據(jù)。
@Configuration
@EnableAuthorizationServer
public class AuthorizationServer extends AuthorizationServerConfigurerAdapter {
/**
* 在 TokenConfig 中已經(jīng)注入
*/
@Autowired
private TokenStore tokenStore;
@Autowired
private ClientDetailsService clientDetailsService;
/**
* 本類中注入
*/
@Autowired
private AuthorizationCodeServices authorizationCodeServices;
/**
* 在 WebSecurityConfig 中已經(jīng)注入
*/
@Autowired
private AuthenticationManager authenticationManager;
/**
* 在 TokenConfig 中已經(jīng)注入
*/
@Autowired
private JwtAccessTokenConverter accessTokenConverter;
/**
* 在 WebSecurityConfig 中已經(jīng)注入
*/
@Autowired
private PasswordEncoder passwordEncoder;
/**
* 將客戶端信息存儲(chǔ)到數(shù)據(jù)庫
* @param dataSource
* @return
*/
@Bean
public ClientDetailsService clientDetailsService(DataSource dataSource) {
JdbcClientDetailsService clientDetailsService = new JdbcClientDetailsService(dataSource);
clientDetailsService.setPasswordEncoder(passwordEncoder);
return clientDetailsService;
}
/**
* 將客戶端信息存儲(chǔ)到內(nèi)存中
* @return ClientDetailsService
*/
/*@Bean
public ClientDetailsService clientDetailsService() {
return new InMemoryClientDetailsService();
}*/
/**
* 配置客戶端詳情信息服務(wù)
* @param clients
* @throws Exception
*/
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
// clientDetailsService使用jdbc查詢數(shù)據(jù)庫的方式
clients.withClientDetails(clientDetailsService);
// 使用in-memory存儲(chǔ)
/*clients.inMemory()
// client_id
.withClient("c1")
// 客戶端秘鑰
.secret(new BCryptPasswordEncoder().encode("secret"))
// 客戶端可以訪問的資源列表
.resourceIds("res1")
// 該client允許的授權(quán)范圍(所有支持的5種)
.authorizedGrantTypes("authorization_code", "password", "client_credentials", "implicit", "refresh_token")
// 允許的授權(quán)范圍(客戶端的權(quán)限)践叠,user-service言缤、read等標(biāo)識(shí)
.scopes("all")
// false:授權(quán)碼模式,跳轉(zhuǎn)到授權(quán)的頁面禁灼,如果是true管挟,不用跳轉(zhuǎn)頁面
.autoApprove(false)
// 加上驗(yàn)證回調(diào)地址
.redirectUris("http://www.baidu.com");*/
// 另外一套
// .and()
// // client_id
// .withClient("c1")
// // 客戶端秘鑰
// .secret(new BCryptPasswordEncoder().encode("secret"))
// // 客戶端可以訪問的資源列表
// .resourceIds("res1")
// // 該client允許的授權(quán)范圍(所有支持的5種)
// .authorizedGrantTypes("authorization_code", "password", "client_credentials", "implicit", "refresh_token")
// // 允許的授權(quán)范圍(客戶端的權(quán)限),user-service弄捕、read等標(biāo)識(shí)
// .scopes("all")
// // false:授權(quán)碼模式僻孝,跳轉(zhuǎn)到授權(quán)的頁面导帝,如果是true,不用跳轉(zhuǎn)頁面
// .autoApprove(false)
// // 加上驗(yàn)證回調(diào)地址
// .redirectUris("http://www.baidu.com");
}
/**
* 令牌管理服務(wù)
* @return
*/
@Bean
public AuthorizationServerTokenServices tokenService() {
DefaultTokenServices service = new DefaultTokenServices();
// 客戶端詳情服務(wù)
service.setClientDetailsService(clientDetailsService);
// 是否產(chǎn)生支持刷新令牌
service.setSupportRefreshToken(true);
// 令牌存儲(chǔ)策略
service.setTokenStore(tokenStore);
// 設(shè)置令牌增強(qiáng)
TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
tokenEnhancerChain.setTokenEnhancers(Collections.singletonList(accessTokenConverter));
service.setTokenEnhancer(tokenEnhancerChain);
// 令牌桶默認(rèn)有效期2小時(shí)
service.setAccessTokenValiditySeconds(7200);
// 刷新令牌默認(rèn)有效期3天
service.setRefreshTokenValiditySeconds(259200);
return service;
}
/**
* 令牌端點(diǎn)的安全配置
* @param security
* @throws Exception
*/
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
// /oauth/token_key: 這個(gè)endpoint當(dāng)使用jwttoken且使用非對稱加密時(shí)穿铆,資源服務(wù)器用于獲取公鑰而開放的您单,這里指這個(gè)endpoint完全公開
security.tokenKeyAccess("permitAll()")
// oauth/check_token: checkToken這個(gè)endpoint完全公開
.checkTokenAccess("permitAll()")
// 允許表單認(rèn)證
.allowFormAuthenticationForClients();
}
/**
* 設(shè)置授權(quán)碼模式的授權(quán)碼如何存取,暫時(shí)采用內(nèi)存方式
* @return
*/
/*@Bean
public AuthorizationCodeServices authorizationCodeServices() {
// 內(nèi)存方式
return new InMemoryAuthorizationCodeServices();
}*/
@Bean
public AuthorizationCodeServices authorizationCodeServices(DataSource dataSource) {
// 設(shè)置授權(quán)碼模式的授權(quán)碼如何存儲(chǔ):數(shù)據(jù)庫方式
return new JdbcAuthorizationCodeServices(dataSource);
}
/**
* 令牌訪問端點(diǎn)
* tokenService():令牌管理服務(wù)
* @param endpoints
* @throws Exception
*/
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
// authenticationManager:認(rèn)證管理器荞雏,密碼模式
// authorizationCodeServices:授權(quán)碼服務(wù)
endpoints.authenticationManager(authenticationManager)
.authorizationCodeServices(authorizationCodeServices)
// 令牌管理服務(wù)虐秦,都需要
.tokenServices(tokenService())
// 允許的POST提交
.allowedTokenEndpointRequestMethods(HttpMethod.POST);
}
}
瀏覽器訪問:http://127.0.0.1:53020/uaa/oauth/authorize?client_id=c1&response_type=code&redirect_uri=http://www.baidu.com
,如果沒有指定scope凤优,默認(rèn)就是全部的scope悦陋,如果指定具體的scope則為http://127.0.0.1:53020/uaa/oauth/authorize?client_id=c1&scope=ROLE_API&response_type=code&redirect_uri=http://www.baidu.com
如下: