Spring Boot OAuth 2.0 客户端

授权服务器负责生成并发放访问令牌(access_token),客户端在访问受保护的资源时会带上访问令牌,资源服务器需要解析并验证客户端带的这个访问令牌。

如果你的资源服务器同时也是一个授权服务器(资源服务器和授权服务器在一起),那么资源服务器就不需要考虑令牌解析的事情了,否则这一步是不可或缺的。

To use the access token you need a Resource Server (which can be the same as the Authorization Server). Creating a Resource Server is easy, just add @EnableResourceServer and provide some configuration to allow the server to decode access tokens. If your application is also an Authorization Server it already knows how to decode tokens, so there is nothing else to do. If your app is a standalone service then you need to give it some more configuration.

同时,把它们放在一起的话还有一个问题需要注意,我们知道过滤器是顺序执行的,因此需要确保那些通过访问令牌来访问的资源路径不能被主过滤拦下了,需要单独摘出来。

Note: if your Authorization Server is also a Resource Server then there is another security filter chain with lower priority controlling the API resources. Fo those requests to be protected by access tokens you need their paths not to be matched by the ones in the main user-facing filter chain, so be sure to include a request matcher that picks out only non-API resources in the WebSecurityConfigurer above.

关于Spring Security中过滤器的顺序可以参见 

这里偷个懒将它们放在一起:

package com.cjs.example.config; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer; import org.springframework.security.oauth2.provider.expression.OAuth2WebSecurityExpressionHandler; @Configuration @EnableResourceServer public class ResourceServerConfig extends ResourceServerConfigurerAdapter { @Override public void configure(ResourceServerSecurityConfigurer resources) throws Exception { super.configure(resources); } /** * 用于配置对受保护的资源的访问规则 * 默认情况下所有不在/oauth/**下的资源都是受保护的资源 * {@link OAuth2WebSecurityExpressionHandler} */ @Override public void configure(HttpSecurity http) throws Exception { http.requestMatchers().antMatchers("/haha/**") .and() .authorizeRequests() .anyRequest().authenticated(); } }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zzdjpd.html