- OAuth2 源码分析(一.核心类)
- 1. 好基友一辈子OAuth2Authentication和OAuth2AccessToken
- 2. TokenGranter、TokenStore、TokenExtractor
4. 资源服务器配置 ResourceServerConfigurerAdapter
5. 授权服务器配置 AuthorizationServerConfigurerAdapter
6.TokenEndPoint,AuthorizationEndPoint,CheckTokenEndPoint- 7.总结
- OAuth2 源码分析(二.授权码模式源码)
- OAuth2 源码分析(三.密码模式源码)
OAuth2 源码分析(一.核心类)
原文章链接:https://blog.csdn.net/qq_30905661/article/details/81112305
Spring Security源码解析篇
介绍了Spring Security的原理,复习下几个概念
Principle GrantedAuthority Authentication AbstractAuthenticationToken UsernamePasswordAuthenticationToken
AuthenticationManager AuthenticationProvider DaoAuthenticationProvider ProviderManager
UserDetail CredentialsContainer UserDetailsService UserCache
WebSecurityConfigurerAdapter WebSecurity HttpSecuirty FilterChainProxy
接下来介绍oauth2的相关概念。oauth2是建立在spring security基础上的一套规范,并非框架。
主要角色有
- 授权服务器 AuthorizationServer 配置client,tokenStore,authenticationManager等
- 资源服务器 ResourceServer 配置HttpSecurity,哪些uri需要验证;配置ResourceServerSecurityConfigurer,如设置tokenService
- 客户端 client 包含clientid,secret
- 用户 user 包含username,password
一般来说,资源服务器和授权服务器都是一个机构提供的,授权服务器给客户端授权,客户端再去请求资源服务器(授权服务器和资源服务器可以是一个应用程序也可以是两个应用程序)。下面例子中的QQ既是资源服务器,也是授权服务器。
用户想登录csdn(客户端),发现还没有注册csdn(客户端)的账号,刚好看见有一个通过QQ登录的方式,遂输入QQ的账户密码,点击授权。此时QQ服务器(授权服务器)对csdn(客户端)和用户密码进行验证,验证成功后给csdn(客户端)发放令牌,csdn凭借令牌去获取用户的QQ头像(资源服务器)等信息。
[
](https://blog.csdn.net/qq_30905661/article/details/81112305)
1. 好基友一辈子OAuth2Authentication和OAuth2AccessToken
1.1 OAuth2Authentication
OAuth2Authentication顾名思义是Authentication的子类,存储用户信息和客户端信息,但多了2个属性
private final OAuth2Request storedRequest;private final Authentication userAuthentication;
这样OAuth2Authentication可以存储2个Authentication,一个给client(必要),一个给user(只是有些授权方式需要)。除此之外同样有principle,credentials,authorities,details,authenticated等属性。
OAuth2Request用于存储request中的Authentication信息(grantType,responseType,resouceId,clientId,scope等),这里就引出了OAuth2 中的三大request。
1.2 BaseRequest
BaseRequest是抽象类,有3个属性:clienId、scope和requestParameters。
abstract class BaseRequest implements Serializable {private String clientId;private Set<String> scope = new HashSet<String>();private Map<String, String> requestParameters = Collections.unmodifiableMap(new HashMap<String, String>());/** setter,getter */}
继承类见下图,3个类都在OAuth2包中,这些request都会存在于OAuth2的验证流程中,用于传递clientId,scope,requestParameters等属性,与HttpServletRequest有本质区别!

1.2.1 AuthorizationRequest
向授权服务器AuthorizationEndPoint (/oauth/authorize)请求授权,AuthorizationRequest作为载体存储state,redirect_uri等参数,生命周期很短且不能长时间存储信息,可用OAuth2Request代替存储信息。
public class AuthorizationRequest extends BaseRequest implements Serializable {// 用户同意授权传递的参数,不可改变private Map<String, String> approvalParameters = Collections.unmodifiableMap(new HashMap<String, String>());// 客户端发送出的状态信息,从授权服务器返回的状态应该不变才对private String state;// 返回类型集合private Set<String> responseTypes = new HashSet<String>();// resource ids 可变private Set<String> resourceIds = new HashSet<String>();// 授权的权限private Collection<? extends GrantedAuthority> authorities = new HashSet<GrantedAuthority>();// 终端用户是否同意该request发送private boolean approved = false;// 重定向uriprivate String redirectUri;// 额外的属性private Map<String, Serializable> extensions = new HashMap<String, Serializable>();// 持久化到OAuth2Requestpublic OAuth2Request createOAuth2Request() {return new OAuth2Request(getRequestParameters(), getClientId(), getAuthorities(), isApproved(), getScope(), getResourceIds(), getRedirectUri(), getResponseTypes(), getExtensions());}// setter,getter}
1.2.2 TokenRequest
向授权服务器TokenEndPoint(/oauth/token)发送请求获得access_token时,tokenRequest作为载体存储请求中grantType等参数。常和tokenGranter.grant(grantType,tokenRequest)结合起来使用。
TokenRequest携带了新属性grantType,和方法createOAuth2Request(用于持久化)
private String grantType;public OAuth2Request createOAuth2Request(ClientDetails client) {Map<String, String> requestParameters = getRequestParameters();HashMap<String, String> modifiable = new HashMap<String, String>(requestParameters);// Remove password if present to prevent leaksmodifiable.remove("password");modifiable.remove("client_secret");// Add grant type so it can be retrieved from OAuth2Requestmodifiable.put("grant_type", grantType);return new OAuth2Request(modifiable, client.getClientId(), client.getAuthorities(), true, this.getScope(),client.getResourceIds(), null, null, null);}
1.2.3 OAuth2Request
用来存储TokenRequest或者AuthorizationRequest的信息,只有构造方法和getter方法,不提供setter方法。它作为OAuth2Authentication的一个属性(StoredRequest),存储request中的authentication信息(grantType,approved,responseTypes)。
1.2.4 OAuth2RequestFactory
工厂类生成OAuth2Request、TokenRequest、AuthenticationRequest。
public interface OAuth2RequestFactory {/*** 从request请求参数中获取clientId,scope,state* clientDetailsService loadClientByClientId(clientId) 获取clientDetails resourcesId Authorities* 根据以上信息生成AuthenticationRequest*/AuthorizationRequest createAuthorizationRequest(Map<String, String> authorizationParameters);/*** AuthorizationRequest request 有生成OAuth2Request的方法* request.createOAuth2Request()*/OAuth2Request createOAuth2Request(AuthorizationRequest request);OAuth2Request createOAuth2Request(ClientDetails client, TokenRequest tokenRequest);TokenRequest createTokenRequest(Map<String, String> requestParameters, ClientDetails authenticatedClient);TokenRequest createTokenRequest(AuthorizationRequest authorizationRequest, String grantType);}
1.3 OAuth2AccessToken
OAuth2AccessToken是一个接口,提供安全令牌token的基本信息,不包含用户信息,仅包含一些静态属性(scope,tokenType,expires_in等)和getter方法,如String getScope,OAuth2RefreshToken getRefreshToken,String getTokenType,String getValue()等。TokenGranter.grant()返回的值即OAuth2AccessToken。
OAuth2AccessToken和OAuth2Authentication是一对好基友,谁要先走谁是狗!!!
TokenStore同时存储OAuth2AccessToken和OAuth2Authentication,也可根据OAuth2Authentication中的OAuth2Request信息可获取对应的OAuth2AccessToken。
DefaultTokenServices有如下方法,都可以通过一个获得另一个的值
OAuth2AccessToken createAccessToken(OAuth2Authentication authentication)OAuth2Authentication loadAuthentication(String accessTokenValue)// 当tokenStore是jdbcTokenStore,表示从数据库中根据OAuth2Authentication获取OAuth2AccessTokenOAuth2AccessToken existingAccessToken = tokenStore.getAccessToken(authentication);

DefaultOAuth2AccessToken是OAuth2AccessToken的实现类,多了构造方法,setter方法和OAuth2AccessToken valueOf(Map
{"access_token": "1e95d081-0048-4397-a081-c76f7823fe54","token_type": "bearer","refresh_token": "7f6db28b-50dc-40a2-b381-3e356e30af2b","expires_in": 1799,"scope": "read write"}
OAuth2RefreshToken是接口,只有String getValue()方法。
DefaultOAuth2RefreshToken是OAuth2RefreshToken的实现类。
2. TokenGranter、TokenStore、TokenExtractor
2.1 TokenGranter(/oauth/token)
一般在用户请求TokenEndPoints中的路径/oauth/token时,根据请求参数中的grantType,username,password,client_id,client_secret等,调用TokenGranter给用户分发OAuth2AccessToken。
根据grantType(password,authorization-code)和TokenRequest(requestParameters,clientId,grantType)授予人OAuth2AccessToken令牌。
public interface TokenGranter {OAuth2AccessToken grant(String grantType, TokenRequest tokenRequest);}
回忆下TokenRequest包含了基本信息clientId,scope,requestParameters,grantType等。根据tokenRequest获取OAuth2Request,初始化获得OAuth2Authentication,再去数据库里找oauth2accesstoken,如果有则直接返回,如果没有则创建新的oauth2accesstoken,并且和OAuth2Authentication一起存入数据库中。
2.1.1 AbstractTokenGranter
TokenGranter抽象继承类AbstractTokenGranter,实现了grant方法,源码如下。
执行顺序为根据tokenRequest====》clientId====》clientDetails====》OAuth2Authentication(getOAuth2Authentication(client,tokenRequest))====》OAuth2AccessToken(tokenService.createAccessToken)
public OAuth2AccessToken grant(String grantType, TokenRequest tokenRequest) {if (!this.grantType.equals(grantType)) {return null;}String clientId = tokenRequest.getClientId();ClientDetails client = clientDetailsService.loadClientByClientId(clientId);validateGrantType(grantType, client);logger.debug("Getting access token for: " + clientId);// getAccessToken 先获得OAuth2Authentication,再创建OAuth2AccessTokenreturn getAccessToken(client, tokenRequest);}protected OAuth2AccessToken getAccessToken(ClientDetails client, TokenRequest tokenRequest) {return tokenServices.createAccessToken(getOAuth2Authentication(client, tokenRequest));}// AbstractTokenGranter的继承类重写了该方法protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {OAuth2Request storedOAuth2Request = requestFactory.createOAuth2Request(client, tokenRequest);return new OAuth2Authentication(storedOAuth2Request, null);}
实现AbstractTokenGranter的类有5种。其中如果用password的方式进行验证,那么TokenGranter类型是ResourceOwnerPasswordTokenGranter,该类中重写了getOAuth2Authentication方法,里面调用了authenticationManager.manage()方法。
用户可自行定义granter类继承AbstractTokenGranter,重写getOAuth2Authentication()方法,并将该granter类添加至CompositeTokenGranter中。
TokenGranter的继承类如下图所示

2.1.2 CompositeTokenGranter
有继承类CompositeTokenGranter,包含List
public class CompositeTokenGranter implements TokenGranter {private final List<TokenGranter> tokenGranters;public CompositeTokenGranter(List<TokenGranter> tokenGranters) {this.tokenGranters = new ArrayList<TokenGranter>(tokenGranters);}public OAuth2AccessToken grant(String grantType, TokenRequest tokenRequest) {for (TokenGranter granter : tokenGranters) {OAuth2AccessToken grant = granter.grant(grantType, tokenRequest);if (grant!=null) {return grant;}}return null;}public void addTokenGranter(TokenGranter tokenGranter) {if (tokenGranter == null) {throw new IllegalArgumentException("Token granter is null");}tokenGranters.add(tokenGranter);}}
2.2 TokenStore(/oauth/token)
一般在TokenGranter执行grant方法完毕后,将OAuth2AccessToken和OAuth2Authentication存储起来,方便以后根据其中一个查询另外一个(如根据access_token查询获得OAuth2Authentication)。
存储OAuth2AccessToken和OAuth2Authentication(比Authentication多了两个属性storedRequest,userAuthentication),存储方法如下。还有各种read,remove方法
void storeAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication);
实现类有5类,其中JdbcTokenStore是通过连接数据库来存储OAuth2AccessToken的,这也是我们一般存储token的方法。条件是数据库里的表结构必须按照标准建立。(JwtTokenStore不存储token和authentication,直接根据token解析获得authentication)
oauth_access_token表结构如下,可见表里存储了OAuth2AccessToken和OAuth2Authentication两个对象,值得注意的是token_id并不等于OAuth2AccessToken.getValue(),value经过MD5加密后才是token_id。同理authentication_id 和 refresh_token也是经过加密转换存储的。
第一次获得token,直接存入数据库表里。
如果重复post请求/oauth/token, JdbcTokenStore会先判断表中是否已有该用户的token,如果有先删除,再添加。

2.3 TokenExtractor (OAuth2AuthentiactionProcessingFilter)
用户携带token访问资源,过滤器进行到OAuth2AuthentiactionProcessingFilter时,从HttpServletRequest中获取access_token(可以从header或者params中获取),拼接成PreAuthenticatedAuthenticationToken(Authentication子类)
Authentication extract(HttpServletRequest request);
BearerTokenExtractor是它的实现类,实现了从request中获取Authentication的方法。
1.header中 Authentication:Bearer xxxxxxxx—xxx
2.request parameters中 access_token=xxxx-xxxx-xxxx
protected String extractToken(HttpServletRequest request) {// 1.直接从header中提取key为Authentication,value是以Bearer 开头的header// 如Authentication:Bearer f732723d-af7f-41bb-bd06-2636ab2be135String token = extractHeaderToken(request);// bearer type allows a request parameter as wellif (token == null) {logger.debug("Token not found in headers. Trying request parameters.");// 2.如果header中不包含,则从param中获取"access_token"对应的值token = request.getParameter(OAuth2AccessToken.ACCESS_TOKEN);if (token == null) {logger.debug("Token not found in request parameters. Not an OAuth2 request.");}else {request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_TYPE, OAuth2AccessToken.BEARER_TYPE);}}return token;}
2.4 ResourceServerTokenServices
两个方法。用户携access_token访问资源服务器时,资源服务器会将该字符串进行解析,获得OAuth2Authentication和OAuth2AccessToken。
loadAuthentication根据字符串accessToken获得OAuth2Authentication;
readAccessToken根据字符串accessToken获得OAuth2AccessToken。
public interface ResourceServerTokenServices {/*** Load the credentials for the specified access token.** @param accessToken The access token value.* @return The authentication for the access token.* @throws AuthenticationException If the access token is expired* @throws InvalidTokenException if the token isn't valid*/OAuth2Authentication loadAuthentication(String accessToken) throws AuthenticationException, InvalidTokenException;/*** Retrieve the full access token details from just the value.** @param accessToken the token value* @return the full access token with client id etc.*/OAuth2AccessToken readAccessToken(String accessToken);}
有两重要继承类,DefaultTokenServices和RemoteTokenServices
2.4.1 DefaultTokenServices
实现了两个接口AuthorizationServerTokenServices和ResourceServerTokenServices。常在granter().grant()方法中调用tokenServices.createAccessToken()方法获得oauth2accesstoken。
其中重要方法createAccessToken(OAuth2Authentication oauth2)源码如下
@Transactionalpublic OAuth2AccessToken createAccessToken(OAuth2Authentication authentication) throws AuthenticationException {OAuth2AccessToken existingAccessToken = tokenStore.getAccessToken(authentication);OAuth2RefreshToken refreshToken = null;// 如果数据库中已存了authentication和accesstoken,则直接提取if (existingAccessToken != null) {if (existingAccessToken.isExpired()) {if (existingAccessToken.getRefreshToken() != null) {refreshToken = existingAccessToken.getRefreshToken();// The token store could remove the refresh token when the// access token is removed, but we want to// be sure...tokenStore.removeRefreshToken(refreshToken);}tokenStore.removeAccessToken(existingAccessToken);}else {// Re-store the access token in case the authentication has changedtokenStore.storeAccessToken(existingAccessToken, authentication);return existingAccessToken;}}// Only create a new refresh token if there wasn't an existing one// associated with an expired access token.// Clients might be holding existing refresh tokens, so we re-use it in// the case that the old access token// expired.if (refreshToken == null) {refreshToken = createRefreshToken(authentication);}// But the refresh token itself might need to be re-issued if it has// expired.else if (refreshToken instanceof ExpiringOAuth2RefreshToken) {ExpiringOAuth2RefreshToken expiring = (ExpiringOAuth2RefreshToken) refreshToken;if (System.currentTimeMillis() > expiring.getExpiration().getTime()) {refreshToken = createRefreshToken(authentication);}}// 第一次创建access_token,并且存储到数据库中OAuth2AccessToken accessToken = createAccessToken(authentication, refreshToken);tokenStore.storeAccessToken(accessToken, authentication);// In case it was modifiedrefreshToken = accessToken.getRefreshToken();if (refreshToken != null) {tokenStore.storeRefreshToken(refreshToken, authentication);}return accessToken;}
2.4.2 RemoteTokenServices
当授权服务和资源服务不在一个应用程序的时候,资源服务可以把传递来的accesstoken递交给授权服务的/oauth/check_token进行验证,而资源服务自己无需去连接数据库验证access_token,这时就用到了RemoteTokenServices。
loadAuthentication方法,设置head表头Authorization 存储clientId和clientSecret信息,请求参数包含access_token字符串,向AuthServer的CheckTokenEndpoint(/oauth/check_token)发送请求,返回验证结果map(包含clientId,grantType,scope,username等信息),拼接成OAuth2Authentication。
**重要!!!_**
AuthServer需要配置checkTokenAcess,否则默认为“denyAll()”,请求访问/oauth/check_token会提示没权限。
@Overridepublic void configure(AuthorizationServerSecurityConfigurer oauthServer) {oauthServer.realm(QQ_RESOURCE_ID).allowFormAuthenticationForClients();// 访问/oauth/check_token 需要client验证oauthServer.checkTokenAccess("isAuthenticated()");、// 也可配置访问/oauth/check_token无需验证// oauthServer.checkTokenAccess("permitAll()");}
不支持readAccessToken方法。
public class RemoteTokenServices implements ResourceServerTokenServices {protected final Log logger = LogFactory.getLog(getClass());private RestOperations restTemplate;private String checkTokenEndpointUrl;private String clientId;private String clientSecret;private String tokenName = "token";private AccessTokenConverter tokenConverter = new DefaultAccessTokenConverter();@Overridepublic OAuth2Authentication loadAuthentication(String accessToken) throws AuthenticationException, InvalidTokenException {MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>();formData.add(tokenName, accessToken);HttpHeaders headers = new HttpHeaders();headers.set("Authorization", getAuthorizationHeader(clientId, clientSecret));Map<String, Object> map = postForMap(checkTokenEndpointUrl, formData, headers);if (map.containsKey("error")) {logger.debug("check_token returned error: " + map.get("error"));throw new InvalidTokenException(accessToken);}Assert.state(map.containsKey("client_id"), "Client id must be present in response from auth server");return tokenConverter.extractAuthentication(map);}@Overridepublic OAuth2AccessToken readAccessToken(String accessToken) {throw new UnsupportedOperationException("Not supported: read access token");}}
3. ClientDetails ClientDetailsService
这两个概念简单的有些可怕,完全就是UserDetails和UserDetailsService的翻版。一个是对应user,一个是对应client。
client需要事先注册到授权服务器,这样授权服务器会根据client的授权请求获取clientId,secret等信息,进行验证后返回token。
3.1 ClientDetails
client的信息,存于授权服务器端,这样只需要知道客户端的clientId,就可以获取到客户端能访问哪些资源,是否需要密码,是否限制了scope,拥有的权限等等。
public interface ClientDetails extends Serializable {String getClientId();// client能访问的资源idSet<String> getResourceIds();// 验证client是否需要密码boolean isSecretRequired();String getClientSecret();// client是否限制了scopeboolean isScoped();// scope集合Set<String> getScope();// 根据哪些grantType验证通过clientSet<String> getAuthorizedGrantTypes();// 注册成功后跳转的uriSet<String> getRegisteredRedirectUri();// client拥有的权限Collection<GrantedAuthority> getAuthorities();// client的token时效Integer getAccessTokenValiditySeconds();// client的refreshToken时效Integer getRefreshTokenValiditySeconds();// true:默认自动授权;false:需要用户确定才能授权boolean isAutoApprove(String scope);// 额外的信息Map<String, Object> getAdditionalInformation();}
3.2 ClientDetailsService
根据clientId获取clientDetails
public interface ClientDetailsService {/*** Load a client by the client id. This method must not return null.** @param clientId The client id.* @return The client details (never null).* @throws ClientRegistrationException If the client account is locked, expired, disabled, or invalid for any other reason.*/ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException;}
有两个子类InMemoryClientDetailsService(内存) 和 JdbcClientDetailsService(数据库,OAUTH_CLIENT_DETAILS、OAUTH_CLIENT_TOKEN表等)。说白了就是一个是把ClientDetails存内存里,一个存数据库里(oauth_client_details表)。
一般在AuthServer中配置ClientDetailsServiceConfigurer。
1、配置JdbcDetailsService
@Beanpublic ClientDetailsService clientDetails() {return new JdbcClientDetailsService(dataSource);}/*** 配置客户端 a configurer that defines the client details service.* Client details can be initialized, or you can just refer to an existing store.*/@Overridepublic void configure(ClientDetailsServiceConfigurer clients) throws Exception {clients.withClientDetails(clientDetails());}
2、配置InMemoryClientDetailsService
@Overridepublic void configure(ClientDetailsServiceConfigurer clients) throws Exception {// @formatter:offclients.inMemory().withClient("aiqiyi").resourceIds(QQ_RESOURCE_ID).authorizedGrantTypes("authorization_code", "refresh_token", "implicit").authorities("ROLE_CLIENT")// , "get_fanslist".scopes("get_fanslist").secret("secret").redirectUris("http://localhost:8081/aiqiyi/qq/redirect").autoApprove(true).autoApprove("get_user_info").and().withClient("youku").resourceIds(QQ_RESOURCE_ID).authorizedGrantTypes("authorization_code", "refresh_token", "implicit").authorities("ROLE_CLIENT").scopes("get_user_info", "get_fanslist").secret("secret").redirectUris("http://localhost:8082/youku/qq/redirect");// @formatter:on}
3.3 ClientDetailsServiceBuilder
创建InMemoryClientDetailsService或者JdbcClientDetailsService,有内部类ClientBuilder。
public class ClientDetailsServiceBuilder<B extends ClientDetailsServiceBuilder<B>> extendsSecurityConfigurerAdapter<ClientDetailsService, B> implements SecurityBuilder<ClientDetailsService> {private List<ClientBuilder> clientBuilders = new ArrayList<ClientBuilder>();public InMemoryClientDetailsServiceBuilder inMemory() throws Exception {return new InMemoryClientDetailsServiceBuilder();}public JdbcClientDetailsServiceBuilder jdbc() throws Exception {return new JdbcClientDetailsServiceBuilder();}@SuppressWarnings("rawtypes")public ClientDetailsServiceBuilder<?> clients(final ClientDetailsService clientDetailsService) throws Exception {return new ClientDetailsServiceBuilder() {@Overridepublic ClientDetailsService build() throws Exception {return clientDetailsService;}};}// clients.inMemory().withClient("clientId").scopes().secret()...public ClientBuilder withClient(String clientId) {ClientBuilder clientBuilder = new ClientBuilder(clientId);this.clientBuilders.add(clientBuilder);return clientBuilder;}@Overridepublic ClientDetailsService build() throws Exception {for (ClientBuilder clientDetailsBldr : clientBuilders) {addClient(clientDetailsBldr.clientId, clientDetailsBldr.build());}return performBuild();}protected void addClient(String clientId, ClientDetails build) {}protected ClientDetailsService performBuild() {throw new UnsupportedOperationException("Cannot build client services (maybe use inMemory() or jdbc()).");}public final class ClientBuilder {// ...public ClientDetailsServiceBuilder<B> and() {return ClientDetailsServiceBuilder.this;}}}
4. 资源服务器配置 ResourceServerConfigurerAdapter
配置哪些路径需要认证后才能访问,哪些不需要。自然就联想到了HttpSecurity(配置HttpSecurity就相当于配置了不同uri对应的filters)。
Spring Security中我们是这样配置WebSecurityConfigurerAdapter的。
@Configuration@EnableWebSecuritypublic class SecurityConfig extends WebSecurityConfigurerAdapter{@Overrideprotected void configure(HttpSecurity http) throws Exception {http.csrf().disable().authorizeRequests().anyRequest().authenticated()//所有请求必须登陆后访问.and().httpBasic().and().formLogin().loginPage("/login").defaultSuccessUrl("/index").failureUrl("/login?error").permitAll()//登录界面,错误界面可以直接访问.and().logout().logoutUrl("/logout").logoutSuccessUrl("/login").permitAll().and().rememberMe();//注销请求可直接访问}@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.inMemoryAuthentication().withUser("user").password("password").roles("USER").and().withUser("admin").password("password").roles("USER", "ADMIN");}}
作为资源服务器ResourceServerConfigurerAdapter,需要和@EnableResourceServer搭配,然后和上面一样需配置HttpSecurity就好了。还能配置ResourceServerSecurityConfigurer,设置tokenService等
/*** 配置资源服务器*/@Configuration@EnableResourceServerprotected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {@Autowiredprivate CustomAuthenticationEntryPoint customAuthenticationEntryPoint;@Autowiredprivate CustomLogoutSuccessHandler customLogoutSuccessHandler;@Overridepublic void configure(HttpSecurity http) throws Exception {http.exceptionHandling().authenticationEntryPoint(customAuthenticationEntryPoint).and().logout().logoutUrl("/oauth/logout").logoutSuccessHandler(customLogoutSuccessHandler).and().authorizeRequests()// hello路径允许直接访问.antMatchers("/hello/").permitAll()// secure路径需要验证后才能访问.antMatchers("/secure/**").authenticated();}// 远程连接authServer服务@Autowiredpublic RemoteTokenServices remoteTokenServices;@Overridepublic void configure(ResourceServerSecurityConfigurer resources) throws Exception {resources.tokenServices(remoteTokenServices);}}
5. 授权服务器配置 AuthorizationServerConfigurerAdapter
注册client信息,可以同时配置多个不同类型的client。
/*** 配置认证服务器 @EnableAuthorizationServer自动注册到spring context中*/@EnableAuthorizationServerprotected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter implements EnvironmentAware {private static final String ENV_OAUTH = "authentication.oauth.";private static final String PROP_CLIENTID = "clientid";private static final String PROP_SECRET = "secret";private static final String PROP_TOKEN_VALIDITY_SECONDS = "tokenValidityInSeconds";private RelaxedPropertyResolver propertyResolver;@Autowiredprivate DataSource dataSource;@Beanpublic TokenStore tokenStore() {return new JdbcTokenStore(dataSource);}@Autowired@Qualifier("authenticationManagerBean")private AuthenticationManager authenticationManager;/*** 可以设置tokenStore,tokenGranter,authenticationManager,requestFactory等接口使用什么继承类,但一般沿用默认的就好了* 如果使用的是密码方式授权,则必须设置authenticationManager*/@Overridepublic void configure(AuthorizationServerEndpointsConfigurer endpoints)throws Exception {endpoints.tokenStore(tokenStore()).authenticationManager(authenticationManager);}/*** 注册clients到授权服务器,这里是注册到内存中,且配置了scopes,authorities等信息*/@Overridepublic void configure(ClientDetailsServiceConfigurer clients) throws Exception {clients.inMemory().withClient(propertyResolver.getProperty(PROP_CLIENTID)).scopes("read", "write").authorities(Authorities.ROLE_ADMIN.name(), Authorities.ROLE_USER.name()).authorizedGrantTypes("password", "refresh_token").secret(propertyResolver.getProperty(PROP_SECRET))// 给客户端的token时效为1800秒.accessTokenValiditySeconds(propertyResolver.getProperty(PROP_TOKEN_VALIDITY_SECONDS, Integer.class, 1800));}@Overridepublic void setEnvironment(Environment environment) {this.propertyResolver = new RelaxedPropertyResolver(environment, ENV_OAUTH);}}
6.TokenEndPoint,AuthorizationEndPoint,CheckTokenEndPoint
6.1 TokenEndPoint
客户端post请求”/oauth/token”,验证用户信息并获取OAuth2AccessToken,必须先经过client验证。这一步的最终目的是存储OAuth2AccessToken+OAuth2Authentication并返回OAuth2AccessToken。
@RequestMapping(value = "/oauth/token", method=RequestMethod.POST)public ResponseEntity<OAuth2AccessToken> postAccessToken(Principal principal, @RequestParamMap<String, String> parameters) throws HttpRequestMethodNotSupportedException {if (!(principal instanceof Authentication)) {throw new InsufficientAuthenticationException("There is no client authentication. Try adding an appropriate authentication filter.");}String clientId = getClientId(principal);ClientDetails authenticatedClient = getClientDetailsService().loadClientByClientId(clientId);TokenRequest tokenRequest = getOAuth2RequestFactory().createTokenRequest(parameters, authenticatedClient);...// AuthorizationServerEndpointsConfigurerOAuth2AccessToken token = getTokenGranter().grant(tokenRequest.getGrantType(), tokenRequest);if (token == null) {throw new UnsupportedGrantTypeException("Unsupported grant type: " + tokenRequest.getGrantType());}return getResponse(token);}
6.2 AuthorizationEndPoint
这个一般只适用于authorization code模式,客户端请求authorization server中的/oauth/authorize(请求前先得登录oauth server获得authentication),验证client信息后根据redirect_uri请求重定向回client,同时带上code值。client附带code值再次向/oauth/token请求,返回accesstoken。
具体流程将在下章中介绍,这里只引出相关概念。
@RequestMapping(value = "/oauth/authorize")public ModelAndView authorize(Map<String, Object> model, @RequestParam Map<String, String> parameters,SessionStatus sessionStatus, Principal principal) {// Pull out the authorization request first, using the OAuth2RequestFactory. All further logic should// query off of the authorization request instead of referring back to the parameters map. The contents of the// parameters map will be stored without change in the AuthorizationRequest object once it is created.AuthorizationRequest authorizationRequest = getOAuth2RequestFactory().createAuthorizationRequest(parameters);Set<String> responseTypes = authorizationRequest.getResponseTypes();if (!responseTypes.contains("token") && !responseTypes.contains("code")) {throw new UnsupportedResponseTypeException("Unsupported response types: " + responseTypes);}if (authorizationRequest.getClientId() == null) {throw new InvalidClientException("A client id must be provided");}try {if (!(principal instanceof Authentication) || !((Authentication) principal).isAuthenticated()) {throw new InsufficientAuthenticationException("User must be authenticated with Spring Security before authorization can be completed.");}ClientDetails client = getClientDetailsService().loadClientByClientId(authorizationRequest.getClientId());// The resolved redirect URI is either the redirect_uri from the parameters or the one from// clientDetails. Either way we need to store it on the AuthorizationRequest.String redirectUriParameter = authorizationRequest.getRequestParameters().get(OAuth2Utils.REDIRECT_URI);String resolvedRedirect = redirectResolver.resolveRedirect(redirectUriParameter, client);if (!StringUtils.hasText(resolvedRedirect)) {throw new RedirectMismatchException("A redirectUri must be either supplied or preconfigured in the ClientDetails");}authorizationRequest.setRedirectUri(resolvedRedirect);// We intentionally only validate the parameters requested by the client (ignoring any data that may have// been added to the request by the manager).oauth2RequestValidator.validateScope(authorizationRequest, client);// Some systems may allow for approval decisions to be remembered or approved by default. Check for// such logic here, and set the approved flag on the authorization request accordingly.authorizationRequest = userApprovalHandler.checkForPreApproval(authorizationRequest,(Authentication) principal);// TODO: is this call necessary?boolean approved = userApprovalHandler.isApproved(authorizationRequest, (Authentication) principal);authorizationRequest.setApproved(approved);// Validation is all done, so we can check for auto approval...if (authorizationRequest.isApproved()) {if (responseTypes.contains("token")) {return getImplicitGrantResponse(authorizationRequest);}if (responseTypes.contains("code")) {// 生成code值并返回return new ModelAndView(getAuthorizationCodeResponse(authorizationRequest,(Authentication) principal));}}// Place auth request into the model so that it is stored in the session// for approveOrDeny to use. That way we make sure that auth request comes from the session,// so any auth request parameters passed to approveOrDeny will be ignored and retrieved from the session.model.put("authorizationRequest", authorizationRequest);return getUserApprovalPageResponse(model, authorizationRequest, (Authentication) principal);}catch (RuntimeException e) {sessionStatus.setComplete();throw e;}}
6.3 CheckTokenEndpoint
当采用RemoteTokenServices时,resouceServer无法自行验证access_token字符串是否正确,遂递交给另一个应用程序中的authserver里CheckTokenEndpoint(/oauth/check_token)进行检验,检验结果返回给resourceServer。
@RequestMapping(value = "/oauth/check_token")@ResponseBodypublic Map<String, ?> checkToken(@RequestParam("token") String value) {OAuth2AccessToken token = resourceServerTokenServices.readAccessToken(value);if (token == null) {throw new InvalidTokenException("Token was not recognised");}if (token.isExpired()) {throw new InvalidTokenException("Token has expired");}OAuth2Authentication authentication = resourceServerTokenServices.loadAuthentication(token.getValue());Map<String, ?> response = accessTokenConverter.convertAccessToken(token, authentication);return response;}
7.总结
复习下这章讲到的知识点。
四大角色:ResouceServer AuthorizationServer client user
OAuth2AccessToken OAuth2Authentiaction
OAuth2Request TokenRequest AuthorizationRequest
TokenGranter TokenStore TokenExtractor DefaultTokenServices RemoteTokenServices
ResourceServerConfigurerAdapter AuthorizationServerConfigurerAdapter
TokenEndPoint(/oauth/token) AuthorizationEndPoint(/oauth/authorize) CheckTokenEndpoint(/oauth/check_token)
OAuth2 源码分析(二.授权码模式源码)
原文链接:https://blog.csdn.net/qq_30905661/article/details/82424552
上一章介绍了与OAuth2相关的核心类,让我们再复习一遍,如果有遗忘的地方请移步到上一章查看。
四大角色:ResouceServer AuthorizationServer client user
OAuth2AccessToken OAuth2Authentiaction
OAuth2Request TokenRequest AuthorizationRequest
TokenGranter TokenStore TokenExtractor DefaultTokenServices
ResourceServerConfigurerAdapter AuthorizationServerConfigurerAdapter
TokenEndPoint(/oauth/token) AuthorizationEndPoint(/oauth/authorize)
上面介绍的全是乐高积木的小部件,如何把积木拼起来才是关键。说到oauth2不可避免的就要聊到5种授权模式。
(1)授权码模式(Authorization Code)
(2)授权码简化模式(Implicit)
(3)Pwd模式(Resource Owner Password Credentials)
(4)Client模式(Client Credentials)
(5)扩展模式(Extension)
无论哪一种,核心思想都是client向authorization server发出请求,请求参数有client_id,client_secret,scope,response_type或redirect_uri等,authorization server经过验证后,返回client一个access_token。凭借这个access_token,client再去resource server中获取资源。这章只介绍授权码模式的流程
1.授权码模式流程图

没了解原理前是看着挺费劲的,一般的验证只需要client发出一次请求就能获得access_token,但授权码模式多了一个Authorization code。这样就分两步走,第一步请求/oauth/authorize获得Authorization code,第二步请求/oauth/token获得access_token。
这里就以登录csdn为例来解释授权码模式。
1.打开csdn登录页面,选择QQ登录。此时client为csdn,qq为authroization server和resouce server。qq授权服务器里存储了很多client信息,csdn只是众多client中的一个。

2.页面跳转至QQ授权页面,url地址是
https://graph.qq.com/oauth2.0/show?which=Login&display=pc&response_type=code&client_id=100270989&redirect_uri=https%3A%2F%2Fpassport.csdn.net%2Faccount%2Flogin%3Foauth_provider%3DQQProvider&state=test
里面有3个关键的参数,response_type,client_id以及redirect_uri。点击了下图中授权并登录的按钮后,页面自动跳转到了csdn主页,且获取到了QQ相关信息。看似很简单的跳转其实包含了很多步骤。


3.用户填写用户名、密码后,点击授权并登录,首先访问qq授权服务器的/login路径,spring security验证username和password后给用户发放JSessionId的cookie,session中存储了Authentication。
4.再访问qq授权服务器/oauth/authorize,请求参数有response_type,redirect_uri,client_id,验证通过后请求重定向到redirect_uri,且传递Authorization code。
5.redirect_uri路径指向的是client中的一个endpoint,client接收到了code,表明client信息已经在QQ授权服务器验证成功。再凭借这个code值外加client_id,client_secret,grant_type=authorization_code,code,redirect_uri等参数,去访问QQ的/oauth/token,返回access_token。
6.获得access_token后,client再去找qq的资源服务器要资源。
一句话概括,就是按顺序依次获得authentication —-> Authorization code ——> access_token。
2. 源码分析
为了方便理解,这里先给出来自github lexburner的例子,项目地址是https://github.com/lexburner/oauth2-demo
项目内有Aiqiyi和qq两个服务,分别是client和authorization server,操作说明详见readme.md,这里不做赘述。

2.1 第一次请求/oauth/authorize
请求的完整url如下,有参数client_id,response_type,redirect_uri。
http://localhost:8080/oauth/authorize?client_id=aiqiyi&response_type=code&redirect_uri=http://localhost:8081/aiqiyi/qq/redirect
访问AuthorizationEndPoint中的/oauth/authorize,里面会判断client信息和用户信息,如果user没有Authentication,则会报错,跳转到ExceptionTranslationFilter类中,请求转发到/login路径,并将现请求路径存储到session的saverequest中。
@RequestMapping(value = "/oauth/authorize")public ModelAndView authorize(Map<String, Object> model, @RequestParam Map<String, String> parameters,SessionStatus sessionStatus, Principal principal) {AuthorizationRequest authorizationRequest = getOAuth2RequestFactory().createAuthorizationRequest(parameters);Set<String> responseTypes = authorizationRequest.getResponseTypes();if (!responseTypes.contains("token") && !responseTypes.contains("code")) {throw new UnsupportedResponseTypeException("Unsupported response types: " + responseTypes);}// 判断clientId是否为空if (authorizationRequest.getClientId() == null) {throw new InvalidClientException("A client id must be provided");}try {// 判断user是否认证,认证失败则跳转到/login路径if (!(principal instanceof Authentication) || !((Authentication) principal).isAuthenticated()) {throw new InsufficientAuthenticationException("User must be authenticated with Spring Security before authorization can be completed.");}// 验证client信息ClientDetails client = getClientDetailsService().loadClientByClientId(authorizationRequest.getClientId());...}}
2.2 ExceptionTranslationFilter
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)throws IOException, ServletException {HttpServletRequest request = (HttpServletRequest) req;HttpServletResponse response = (HttpServletResponse) res;try {chain.doFilter(request, response);logger.debug("Chain processed normally");}catch (IOException ex) {throw ex;}catch (Exception ex) {// Try to extract a SpringSecurityException from the stacktraceThrowable[] causeChain = throwableAnalyzer.determineCauseChain(ex);RuntimeException ase = (AuthenticationException) throwableAnalyzer.getFirstThrowableOfType(AuthenticationException.class, causeChain);if (ase == null) {ase = (AccessDeniedException) throwableAnalyzer.getFirstThrowableOfType(AccessDeniedException.class, causeChain);}if (ase != null) {// 进入到此方法中handleSpringSecurityException(request, response, chain, ase);}...}}private void handleSpringSecurityException(HttpServletRequest request,HttpServletResponse response, FilterChain chain, RuntimeException exception)throws IOException, ServletException {if (exception instanceof AuthenticationException) {logger.debug("Authentication exception occurred; redirecting to authentication entry point",exception);// 没有验证身份信息,跳转到/login界面sendStartAuthentication(request, response, chain,(AuthenticationException) exception);}...}protected void sendStartAuthentication(HttpServletRequest request,HttpServletResponse response, FilterChain chain,AuthenticationException reason) throws ServletException, IOException {SecurityContextHolder.getContext().setAuthentication(null);// 将saveRequest存到session中,方便身份验证成功后调用requestCache.saveRequest(request, response);logger.debug("Calling Authentication entry point.");// 请求重定向到/loginauthenticationEntryPoint.commence(request, response, reason);}
2.3 requestCache.saveRequest(request,response)
requestCache的常用的实现类是HttpSessionRequestCache,一般是访问url时系统判断用户未获得授权,ExceptionTranslationFilter会存储savedRequest到session中,名为“SPRING_SECURITY_SAVED_REQUEST”。
SavedRequest里面包含原先访问的url地址、cookie、header、parameter等信息,一旦Authentication认证成功,successHandler.onAuthenticationSuccess(SavedRequestAwareAuthenticationSuccessHandler)会从session中抽取savedRequest,继续访问原先的url。
public class HttpSessionRequestCache implements RequestCache {static final String SAVED_REQUEST = "SPRING_SECURITY_SAVED_REQUEST";/*** HttpSessionRequestCache Stores the current request, provided the configuration properties allow it.*/public void saveRequest(HttpServletRequest request, HttpServletResponse response) {if (requestMatcher.matches(request)) {DefaultSavedRequest savedRequest = new DefaultSavedRequest(request,portResolver);if (createSessionAllowed || request.getSession(false) != null) {// Store the HTTP request itself. Used by// AbstractAuthenticationProcessingFilter// for redirection after successful authentication (SEC-29)request.getSession().setAttribute(this.sessionAttrName, savedRequest);logger.debug("DefaultSavedRequest added to Session: " + savedRequest);}}else {logger.debug("Request not saved as configured RequestMatcher did not match");}}}
2.4 重定向到/login
由于是第一次访问qq认证服务器,所以需要用户登录校验身份。在WebSecurityConfigurerAdapter的继承类中,找到存储在缓存中的用户名密码,填写完毕。

点击“Sign In”按钮后,post请求/login路径,按照FilterChainProxy的filter链运行到UsernamePasswordAuthenticationFilter,验证通过后执行successHandler.onAuthenticationSuccess(request, response, authResult),获取session中的savedrequest,重定向到原先的地址/oauth/authorize,并附带完整请求参数。
public class SavedRequestAwareAuthenticationSuccessHandler extendsSimpleUrlAuthenticationSuccessHandler {protected final Log logger = LogFactory.getLog(this.getClass());private RequestCache requestCache = new HttpSessionRequestCache();@Overridepublic void onAuthenticationSuccess(HttpServletRequest request,HttpServletResponse response, Authentication authentication)throws ServletException, IOException {// HttpSessionRequestCache.getRequest ,找名为SPRING_SECURITY_SAVED_REQUEST的sessionSavedRequest savedRequest = requestCache.getRequest(request, response);if (savedRequest == null) {super.onAuthenticationSuccess(request, response, authentication);return;}String targetUrlParameter = getTargetUrlParameter();if (isAlwaysUseDefaultTargetUrl()|| (targetUrlParameter != null && StringUtils.hasText(request.getParameter(targetUrlParameter)))) {requestCache.removeRequest(request, response);super.onAuthenticationSuccess(request, response, authentication);return;}clearAuthenticationAttributes(request);// Use the DefaultSavedRequest URL// 获得原先存储在SavedRequest中的redirectUrl,即/oauth/authorizeString targetUrl = savedRequest.getRedirectUrl();logger.debug("Redirecting to DefaultSavedRequest Url: " + targetUrl);getRedirectStrategy().sendRedirect(request, response, targetUrl);}public void setRequestCache(RequestCache requestCache) {this.requestCache = requestCache;}}
2.5 第二次请求/oauth/authorize
这次请求就硬气多了,请求中携带了Authentication的session,系统验证通过,生成授权码,存储在InMemoryAuthorizationCodeServices中的concurrenthashmap中,且返回给请求参数中的redirect_uri,即http://localhost:8081/aiqiyi/qq/redirect。
http://localhost:8080/oauth/authorize?client_id=aiqiyi&response_type=code&redirect_uri=http://localhost:8081/aiqiyi/qq/redirect
@RequestMapping(value = "/oauth/authorize")public ModelAndView authorize(Map<String, Object> model, @RequestParam Map<String, String> parameters,SessionStatus sessionStatus, Principal principal) {...if (authorizationRequest.isApproved()) {if (responseTypes.contains("token")) {return getImplicitGrantResponse(authorizationRequest);}if (responseTypes.contains("code")) {// 返回code给redirect_urireturn new ModelAndView(getAuthorizationCodeResponse(authorizationRequest,(Authentication) principal));}}...}
public class InMemoryAuthorizationCodeServices extends RandomValueAuthorizationCodeServices {protected final ConcurrentHashMap<String, OAuth2Authentication> authorizationCodeStore = new ConcurrentHashMap<String, OAuth2Authentication>();@Overrideprotected void store(String code, OAuth2Authentication authentication) {this.authorizationCodeStore.put(code, authentication);}@Overridepublic OAuth2Authentication remove(String code) {OAuth2Authentication auth = this.authorizationCodeStore.remove(code);return auth;}}
到了这里我们总结下刚才都发生了什么。首先aiqiyi向qq发出/oauth/authorize的请求,qq服务器的AuthorizationEndPoint判断用户是否登录,如果没有登录则先跳转到/login界面,同时存储首次request的信息,保存在session中。用户登录并授权后,程序自动获取刚存储在session中的savedrequest,再次访问/oauth/authorize。验证client信息和user信息成功后,重定向到redirect_uri,并传参数code。
aiqiyi接到code后,再附带client_id,client_secret,grant_type,redirect_uri等信息post请求/oauth/token,从而获得access_token。
2.6 client接收code并向oauth server请求/oauth/token
以下代码自行写在client的controller里,用于接收qq服务端传递来的code,并请求/oauth/token。
@RequestMapping("/aiqiyi/qq/redirect")public String getToken(@RequestParam String code){log.info("receive code {}",code);HttpHeaders headers = new HttpHeaders();headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);MultiValueMap<String, String> params= new LinkedMultiValueMap<>();params.add("grant_type","authorization_code");params.add("code",code);params.add("client_id","aiqiyi");params.add("client_secret","secret");params.add("redirect_uri","http://localhost:8081/aiqiyi/qq/redirect");HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers);ResponseEntity<String> response = restTemplate.postForEntity("http://localhost:8080/oauth/token", requestEntity, String.class);String token = response.getBody();log.info("token => {}",token);return token;}
2.7 TokenEndPoint生成access_token
具体代码在上一章已介绍,这里不做详述。注意的是会从InMemoryAuthorizationCodeServices中提取hashmap验证code是否正确。
3 总结

github地址:https://github.com/lexburner/oauth2-demo
OAuth2 源码分析(三.密码模式源码)
原文链接:https://blog.csdn.net/qq_30905661/article/details/82704746
上章介绍了授权码模式,现在再来介绍密码模式,简单的如同砍瓜切菜。
所谓密码模式,即用户提供username,password,clientId,clientSecret,grantType=password等信息,请求/oauth/token,获得access_token,用户即可通过access_token访问资源。
还是以oauth2-demo-master项目为例,只用添加client的认证方法password。
启动QQ项目,程序自动会启动几个endpoints,如/oauth/token,/oauth/authorize等。
1. 访问/oauth/token
此时FilterChainProxy的filter顺序如下。重要的Filter有ClientCredentialsTokenEndpointFilter和BasicAuthenticationFilter,前者从request parameters中抽取client信息,后者从header Authorization Basic XXXX中抽取client信息。

1.1 parameters
用postman发送请求,所有参数写在parameters中,返回access_token。
localhost:8080/oauth/token?username=250577914&password=123456&grant_type=password&client_id=aiqiyi&client_secret=secret
ClientCredentialsTokenEndpointFilter会从parameter中抽取client_id,client_secret信息,并进行client的身份验证。
@Overridepublic Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)throws AuthenticationException, IOException, ServletException {if (allowOnlyPost && !"POST".equalsIgnoreCase(request.getMethod())) {throw new HttpRequestMethodNotSupportedException(request.getMethod(), new String[] { "POST" });}String clientId = request.getParameter("client_id");String clientSecret = request.getParameter("client_secret");// If the request is already authenticated we can assume that this// filter is not neededAuthentication authentication = SecurityContextHolder.getContext().getAuthentication();if (authentication != null && authentication.isAuthenticated()) {return authentication;}if (clientId == null) {throw new BadCredentialsException("No client credentials presented");}if (clientSecret == null) {clientSecret = "";}clientId = clientId.trim();UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(clientId,clientSecret);return this.getAuthenticationManager().authenticate(authRequest);}
1.2 Basic Auth
Postman发送请求如下,Basic Auth中填写client_id和client_secret信息。点击updaterequests后,postman会将client信息用base64加密,写在header——Authorization中。

这样一来,ClientCredentialsTokenEndpointFilter会由于参数中没有client_id自动跳过。BasicAuthenticationFilter会获取header中的Authorization Basic,提取出客户端信息。
@Overrideprotected void doFilterInternal(HttpServletRequest request,HttpServletResponse response, FilterChain chain)throws IOException, ServletException {final boolean debug = this.logger.isDebugEnabled();String header = request.getHeader("Authorization");if (header == null || !header.startsWith("Basic ")) {chain.doFilter(request, response);return;}try {// Base64 反解码String[] tokens = extractAndDecodeHeader(header, request);assert tokens.length == 2;String username = tokens[0];if (authenticationIsRequired(username)) {UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, tokens[1]);authRequest.setDetails(this.authenticationDetailsSource.buildDetails(request));Authentication authResult = this.authenticationManager.authenticate(authRequest);SecurityContextHolder.getContext().setAuthentication(authResult);this.rememberMeServices.loginSuccess(request, response, authResult);onSuccessfulAuthentication(request, response, authResult);}}catch (AuthenticationException failed) {...}chain.doFilter(request, response);}
无论是哪一种方式访问/oauth/token,都事先验证了client信息,并作为authentication存储在SecurityContextHolder中。传递到TokenEndPoint的principal是client,paramters包含了user的信息和grantType。
2. 携带Access_token访问api
2.1 access_token放在parameter中
OAuth2AuthentiactionProcessingFilter,从request中提取access_token,构建PreAuthenticatedAuthenticationToken并验证。
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException,ServletException {final boolean debug = logger.isDebugEnabled();final HttpServletRequest request = (HttpServletRequest) req;final HttpServletResponse response = (HttpServletResponse) res;try {// 从request中提取access_tokenAuthentication authentication = tokenExtractor.extract(request);if (authentication == null) {if (stateless && isAuthenticated()) {SecurityContextHolder.clearContext();}}else {request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_VALUE, authentication.getPrincipal());if (authentication instanceof AbstractAuthenticationToken) {AbstractAuthenticationToken needsDetails = (AbstractAuthenticationToken) authentication;needsDetails.setDetails(authenticationDetailsSource.buildDetails(request));}// OAuth2AuthenticationManager 验证PreAuthenticatedAuthenticationTokenAuthentication authResult = authenticationManager.authenticate(authentication);eventPublisher.publishAuthenticationSuccess(authResult);SecurityContextHolder.getContext().setAuthentication(authResult);}}catch (OAuth2Exception failed) {SecurityContextHolder.clearContext();eventPublisher.publishAuthenticationFailure(new BadCredentialsException(failed.getMessage(), failed),new PreAuthenticatedAuthenticationToken("access-token", "N/A"));authenticationEntryPoint.commence(request, response,new InsufficientAuthenticationException(failed.getMessage(), failed));return;}chain.doFilter(request, response);}
tokenExtractor.extract(request)实际调用的是BearTokenExtractor里的extract方法,从Authorization header “Bearer xxxx”中抽取token,或者从request parameters抽取名为“access_token”的参数值。
@Overridepublic Authentication extract(HttpServletRequest request) {String tokenValue = extractToken(request);if (tokenValue != null) {// 记为PreAuthenticatedAuthenticationTokenPreAuthenticatedAuthenticationToken authentication = new PreAuthenticatedAuthenticationToken(tokenValue, "");return authentication;}return null;}
构建后的authentication参数如下,tokenType=”Bearer”,principal=token值。再根据OAuth2AuthenticationManager验证该authentication的合法性。
2.2 access_token存于header中
postman发送如下请求,将access_token写在Authorization的header里,前缀是Bearer。
同样是OAuth2AuthenticationProcessingFilter拦截,从request header中提取token,记为PreAuthenticatedAuthenticationToken,用OAuth2AuthenticationManager进行验证。
3. 访问/oauth/check_token
当oauthserver和resourceserver不在一个应用程序时,访问resource,会自动转交到oauthserver的/oauth/check_token,获得access_token的验证结果。
3.1 配置ResouceServer
配置application.yml
server:port: 8081security:oauth2:client:client-id: aiqiyiclient-secret: secretaccess-token-uri: http://localhost:8080/oauth/tokenuser-authorization-uri: http://localhost:8080/oauth/authorizeuser-logout-uri: http://localhost:8080/oauth/logoutresource:id: qqtoken-info-uri: http://localhost:8080/oauth/check_tokenprefer-token-info: truefilter-order: 3basic:enabled: false
配置ResouceServerConfigurerAdapter
@Configuration@EnableResourceServer@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)public class ResourceServerConfig extends ResourceServerConfigurerAdapter {@Value("${security.oauth2.resource.id}")public String RESOURCE_ID;@Autowiredpublic RemoteTokenServices remoteTokenServices;@Overridepublic void configure(ResourceServerSecurityConfigurer resources) throws Exception {// 存入resource_id,到时候与oauthserver中client对应的resourceid进行比对resources.resourceId(RESOURCE_ID).stateless(true);resources.tokenServices(remoteTokenServices);}}
