Spring Security Oauth2.0里如何获取access_token?

  • A+
所属分类:Spring Security

这几天在研究如何使用Spring Security Oauth2.0。按照网上的例子踩了几个坑后,现在状况是调用/oauth/authorize接口可以正常返回授权码,用postman调用/oauth/token接口也可以正常返回access_token

但是,现在问题来了,用Postman是可以,怎么用Spring Security Oauth2.0里封装好的方法得到access_token呢?

答案肯定是可以的。不然还叫什么框架

直接使用框架里封装好的OAuth2RestTemplate类即可。在使用这个类的方法之前,我们得在客户端加上一些配置。注意是加在WebMvcConfigurer的实现类里,完整代码如下:

@Configuration
   @EnableOAuth2Client
   public class Oauth2ClientConfig {

       private String redirectUri = "http://localhost:8082/ui/index";

       @Bean
       public OAuth2RestTemplate oauth2RestTemplate(OAuth2ClientContext context, OAuth2ProtectedResourceDetails details) {
           OAuth2RestTemplate template = new OAuth2RestTemplate(details, context);

           template.setAccessTokenProvider(new AuthorizationCodeAccessTokenProvider());
           return template;
       }

       /**
        * 注册处理redirect uri的filter
        * @param oauth2RestTemplate
        * @param tokenService
        * @return
        */
       @Bean
       public OAuth2ClientAuthenticationProcessingFilter oauth2ClientAuthenticationProcessingFilter(
               OAuth2RestTemplate oauth2RestTemplate)
       {
           OAuth2ClientAuthenticationProcessingFilter filter = new OAuth2ClientAuthenticationProcessingFilter(redirectUri);
           filter.setRestTemplate(oauth2RestTemplate);



           //设置回调成功的页面
           filter.setAuthenticationSuccessHandler(new SimpleUrlAuthenticationSuccessHandler() {
               public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
                   this.setDefaultTargetUrl("/index");
                   super.onAuthenticationSuccess(request, response, authentication);
               }
           });
           return filter;
       }

   }

好了,现在我们就可以使用OAuth2RestTemplate类里的方法了,获取access_token有两种方法。

一种就是直接获取token

oAuth2RestTemplate.getAccessToken();

第二种是获取项目里需要认证后才能访问的资源,这时也会先获取access_token。

ResponseEntity<String> responseEntity = oAuth2RestTemplate.getForEntity(resourceServerUrl, String.class);

这里说明一下,使用这个类是在获取授权码返回到redirect_uri的controller里写的,这时地址里已经带了code参数,所以是可以用code来换取token的,在这两个方法里,成功获取token后会自动保存在内存里,所以我们在网页上再访问其它需要认证的页面或资源都可以访问了。

ZPY

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: