grant_type=authorization_code 中 redirect_uri的代码实现参考

OAuth2中grant_type=authorization_code时, 需要填写redirect_uri, 而该uri将如何处理与实现呢, 在此提供具体的讲解与实现参考

redirect_uri在注册ClientDetails时需要提供(当grant_type包含authorization_code时), 且在发起OAUTH2流程时需要在参数中传递redirec_uri, 这两处的值必须一致.

 

在业务中, redirect_uri代码实现主要用于接收返回的code值, 校验state是否合法, 以及通过code换取accessToken操作.

在 spring-oauth-client 项目的 AuthorizationCodeController.java 类中, authorization_code_callback 方法实现了以上的逻辑, 在具体实现是可参考该方法的实现, 代码如下:

@RequestMapping(value = "authorization_code_callback")
public String authorizationCodeCallback(AuthCallbackDto callbackDto, HttpServletRequest request, Model model) throws Exception {

    if (callbackDto.error()) {
        //Server response error
        model.addAttribute("message", callbackDto.getError_description());
        model.addAttribute("error", callbackDto.getError());
        return "redirect:oauth_error";
    } else if (correctState(callbackDto, request)) {
        //Go to retrieve access_token form
        AuthAccessTokenDto accessTokenDto = oauthService.createAuthAccessTokenDto(callbackDto);
        model.addAttribute("accessTokenDto", accessTokenDto);
        model.addAttribute("host", host);
        return "code_access_token";
    } else {
        //illegal state
        model.addAttribute("message", "Illegal \"state\": " + callbackDto.getState());
        model.addAttribute("error", "Invalid state");
        return "redirect:oauth_error";
    }

}

 

这里实现首先检查服务端是否返回error信息,

然后判断state是否正确, 若正确则显示一个页面, 并在code_access_token方法中(同一个类中)使用 httpclient 发起请求(grant_type=authorization_code)通过 code换取access_token.

其它情况则显示error信息.

 

http://git.oschina.net/mkk/spring-oauth-client

Leave a Comment.

This site uses Akismet to reduce spam. Learn how your comment data is processed.