修改返回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);
    }
發佈了157 篇原創文章 · 獲贊 32 · 訪問量 140萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章