spring-security-oauth2实现OAuth2.0服务
生活随笔
收集整理的這篇文章主要介紹了
spring-security-oauth2实现OAuth2.0服务
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
關于OAuth的介紹查看我的另一篇文章OAuth的4種授權方式,spring-security-oauth2是實現OAuth2.0的框架,配置稍微有些繁瑣,因此本文記錄下大概的思路,加深印象。
OAuth 2.0中主要有Authorization Service授權服務和Resource Service資源服務,他們可以在同一個應用程序中,也可以在兩個應用程序中,甚至多個資源服務共享一個授權服務。
spring-security提供了相應的endpoints來管理token的請求,/oauth/authorize端點負責授權服務,/oauth/token端點負責token的請求服務;資源服務中的過濾器OAuth2AuthenticationProcessingFilter 負責校驗Token。
下面從總體上介紹授權服務和資源服務的主要配置,詳細的配置在githubspring-security-oauth demo上。
授權服務配置
@Configuration @EnableAuthorizationServer public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {private static final String DEMO_RESOURCE_ID = "openapi";@Autowiredprivate OrderAuthProperties orderAuthProperties;/*** 注意這里AuthenticationManager和UserAccountService* 是在SecurityConfiguration配置的,把倆個配置類關聯了起來*/@AutowiredAuthenticationManager authenticationManager;@Autowiredprivate UserAccountService userAccountService;@Autowiredprivate AuthorizationCodeServices authorizationCodeServices;@AutowiredRedisConnectionFactory redisConnectionFactory;@Autowiredprivate OAuthClientDetailsService oAuthClientDetailsService;@Autowiredprivate DataSource dataSource;/*** 配置第三方客戶端的信息,可以從內存中加載,也可以從數據庫加載(更常用)*/@Overridepublic void configure(ClientDetailsServiceConfigurer clients) throws Exception {clients.jdbc(dataSource);clients.withClientDetails(oAuthClientDetailsService);// 這里將第三方客戶端放到內存里,配置兩個客戶端,一個用于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") // .secret("123456") // .resourceIds(DEMO_RESOURCE_ID) // .authorizedGrantTypes("authorization_code", "code", "password", "refresh_token") // .scopes("select") // .redirectUris("http://www.baidu.com");}/*** 定義token endpoint的安全配置*/@Overridepublic void configure(AuthorizationServerSecurityConfigurer oauthServer) {oauthServer.realm("oauth2-resources").tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()").passwordEncoder(clientPasswordEncoder()).allowFormAuthenticationForClients();}/*** 第三方客戶端使用加密方式*/@Beanpublic PasswordEncoder clientPasswordEncoder() {// 不做加密處理,明文存儲return NoOpPasswordEncoder.getInstance();}/*** 定義授權、token endpoint和token服務,即如何生成token和token存儲在哪里(內存/數據庫/JWT)** <p>* 這里最重要的就是DefaultTokenServices,默認是生成隨機值作為token* <p>*/@Overridepublic void configure(AuthorizationServerEndpointsConfigurer endpoints) {// 這里設置了兩個TokenEnhancer,可改變token值,它會在token生成后/保存前調用TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();tokenEnhancerChain.setTokenEnhancers(Arrays.asList(tokenEnhancer(), accessTokenConverter()));endpoints.authenticationManager(authenticationManager) // 注入authenticationManager開啟密碼授權模式// 必須要配置userDetailsService,才支持refresh token grant,to ensure that the account is still active// 這里和SecurityConfiguration的userAccountService也可以不一樣,為什么?.userDetailsService(userAccountService).authorizationCodeServices(authorizationCodeServices) // 定義authorizationCodeServices支持auth code grant..tokenStore(tokenStore()).tokenEnhancer(tokenEnhancerChain);}/*** TokenEnhancer** JWT提供的,幫助把OAuth認證信息轉為JWT,即access_token,它返回的很多默認字段(jti,ati)都是在這里定義的*/@Beanpublic JwtAccessTokenConverter accessTokenConverter() {JwtAccessTokenConverter converter = new JwtAccessTokenConverter();// 這里使用的密鑰也要定義在資源服務里,以便資源服務也可以校驗token,否則認證服務就要提供校驗token的接口給資源服務converter.setSigningKey(orderAuthProperties.getOauthJwtSecret());return converter;}/*** TokenEnhancer** 向token里添加自定義信息*/@Beanpublic JwtTokenEnhancer tokenEnhancer() {return new JwtTokenEnhancer();}/*** 定義token的存儲方式:可以放在redis/數據庫(oauth_access_token表)/內存,或者jwt中* 這里放在JWT里,根本就不必后端存儲token了,這是JWT很大的優(yōu)勢** 但是JWT也有缺點,1.不容易撤銷授權,所以一般令牌時效性很短,撤銷授權可以在刷新時實現,怎么實現?* 2.如果要存儲的信息很多,令牌會變得很大*/@Beanpublic TokenStore tokenStore() {return new JwtTokenStore(accessTokenConverter());} }總結
以上是生活随笔為你收集整理的spring-security-oauth2实现OAuth2.0服务的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: OAuth2.0的四种授权方式
- 下一篇: nginx实现http服务配置