修改返回token内容与手工获取token

本文基于spring-security-oauth2实现的oauth2.

通过使用TokenEnhancer来修改授权服务器返回token的内容.

    @Bean
    public TokenEnhancer tokenEnhancer(){
        return new TokenEnhancer() {
            @Override
            public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
                if (accessToken instanceof DefaultOAuth2AccessToken){
                    DefaultOAuth2AccessToken token= (DefaultOAuth2AccessToken) accessToken;
                    Map<String, Object> additionalInformation = new LinkedHashMap<String, Object>();
                    additionalInformation.put("username",authentication.getName());
                    token.setAdditionalInformation(additionalInformation);
                }
                return accessToken;
            }
        };
    }
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.tokenEnhancer(tokenEnhancer()).tokenStore(tokenStore()).authenticationManager(authenticationManager);;
    }

不使用org.springframework.security.oauth2.config.annotation.web.configuration.EnableOAuth2Client注解,手工去取token的做法:
1.先发起跳转请求

    @Autowired
    private RandomValueStringGenerator generator;
    @RequestMapping(value = "authorize", method = RequestMethod.GET)
    public void authorize(HttpServletResponse response) throws IOException {
        String authorizeUrl = "http://localhost:81/auth/oauth/authorize";
        Map<String, String> requestParams = new HashMap<String, String>();
        requestParams.put("client_id", "client");
        requestParams.put("redirect_uri", "http://localhost:83/client/token");
        requestParams.put("response_type", "code");
        requestParams.put("scope", "openid");
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(authorizeUrl);
        for (Map.Entry<String, String> param : requestParams.entrySet()) {
            builder.queryParam(param.getKey(), param.getValue());
        }
        builder.queryParam("state", generator.generate());
        String redirectUrl = response.encodeRedirectURL(builder.build().encode().toUriString());
        response.sendRedirect(redirectUrl);
    }

2.拿到返回的授权码去取token

    private static final FormHttpMessageConverter FORM_MESSAGE_CONVERTER = new FormHttpMessageConverter();
    private static final List<HttpMessageConverter<?>> MESSAGE_CONVERTERS = Collections.singletonList(new StringHttpMessageConverter());
    @RequestMapping(value = "token", method = RequestMethod.GET)
    public void token(@RequestParam Map<String, String> parameters, HttpServletResponse response) throws IOException {
        String accessTokenUri = "http://localhost:81/auth/oauth/token";
        final HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", "Basic Y2xpZW50OnNlY3JldA==");
        final MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
        form.add("grant_type", "authorization_code");
        form.add("code", parameters.get("code"));
        form.add("redirect_uri", "http://localhost:83/client/token");
        RequestCallback requestCallback = new RequestCallback() {
            @Override
            public void doWithRequest(ClientHttpRequest request) throws IOException {
                request.getHeaders().putAll(headers);
                request.getHeaders().setAccept(Arrays.asList(MediaType.APPLICATION_JSON, MediaType.APPLICATION_FORM_URLENCODED));
                FORM_MESSAGE_CONVERTER.write(form, MediaType.APPLICATION_FORM_URLENCODED, request);
            }
        };
        ResponseExtractor<String> responseExtractor = new ResponseExtractor<String>() {
            @Override
            public String extractData(ClientHttpResponse response) throws IOException {
                return new HttpMessageConverterExtractor<String>(String.class, MESSAGE_CONVERTERS).extractData(response);
            }
        };
        String result = new RestTemplate().execute(accessTokenUri, HttpMethod.POST, requestCallback, responseExtractor);
        System.out.println(result);
    }
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值