SpringBoot2.X+Oauth2授权第三方登录

一、获取码云Client Id与Client Secret

1、登录码云

2、创建第三方应用

2.1、在右上角菜单找到 “设置” 选项

2.2、 在 “安全设置” 下找到 “第三方应用”

 2.3、点击 “创建应用” 开始创建第三方应用

 2.4、填充必要信息后,点击创建应用

 2.5、保存后,就可以找到应用的Client Id与Client Secret

二、上代码 

1、配置application.yml

 2、引依赖

        <!--httpclient-->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.6</version>
        </dependency>
        <!--阿里 JSON-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.47</version>
        </dependency>
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.6.3</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.15</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>

3、配置码云配置信息

@Configuration
public class GiteeProp {

    @Value("${gitee.oauth.clientid}")
    public String clientId;

    @Value("${gitee.oauth.clientsecret}")
    public String clientSecret;

    @Value("${gitee.oauth.callbackUrl}")
    public String callbackUrl;

    @Value("${gitee.oauth.codeUrl}")
    public String codeUrl;

    @Value("${gitee.oauth.tokenUrl}")
    public String tokenUrl;

    @Value("${gitee.oauth.userInfoUrl}")
    public String userInfoUrl;

}

4、直接调用/gitee/auth,然后“同意授权”回调

    /**
     * 请求授权页面
     * Spring MVC项目中页面重定向一般使用return "redirect:/other/controller/";即可。
     * 而Spring Boot使用了@RestController注解,上述写法只能返回字符串,解决方法如下
     * HttpServletResponse response -> response.sendRedirect("some-url");
     */
    @GetMapping(value = "/gitee/auth")
    public void giteeAuth(HttpSession session, HttpServletResponse response) throws IOException {
        // 用于第三方应用防止CSRF攻击
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        session.setAttribute("state", uuid);

        // Step1:获取Authorization Code
        String url = giteeProp.codeUrl.replace("{clientId}", giteeProp.clientId)
                .replace("{callbackUrl}", URLEncoder.encode(giteeProp.callbackUrl, "utf-8"))
                .replace("{state}", uuid);

        //return "redirect:" + url;
        response.sendRedirect(url);
    }

5、当该用户点击“授权”按钮,同意授权后,就会回调到我们在应用中填写的回调地址里去

    /**
     * 授权回调
     */
    @GetMapping(value = "/gitee/callback")
    public String giteeCallback(HttpServletRequest request) throws Exception {
        HttpSession session = request.getSession();
        // 得到Authorization Code
        String code = request.getParameter("code");
        // 我们放在地址中的状态码
        String state = request.getParameter("state");
        String uuid = (String) session.getAttribute("state");

        // 验证信息我们发送的状态码
        if (null != uuid && uuid.equals(state)) {
            // 状态码不正确,直接返回登录页面
        }

        // Step2:通过Authorization Code获取Access Token
        String url = giteeProp.tokenUrl.replace("{clientId}", giteeProp.clientId)
                .replace("{clientSecret}", giteeProp.clientSecret)
                .replace("{code}", code)
                .replace("{callbackUrl}", giteeProp.callbackUrl);
        JSONObject accessTokenJson = GiteeHttpClient.getAccessToken(url);

        if (ObjectUtils.isEmpty(accessTokenJson)) {
            throw new RuntimeException();
        }

        // Step3: 获取用户信息
        url = giteeProp.userInfoUrl.replace("{accessToken}", (String)accessTokenJson.get("access_token"));
        JSONObject jsonObject = GiteeHttpClient.getUserInfo(url);
        log.info(">>>>>>>>>>>>>>>>>【{}】", JSON.toJSONString(jsonObject));
        /**
         * 获取到用户信息之后,就该写你自己的业务逻辑了
         */
        return "成功啦啦啦啦啦啦";
    }

6、获取token与用户信息

public class GiteeHttpClient {

    /**
     * 获取Access Token
     * post
     */
    public static JSONObject getAccessToken(String url) throws IOException {
        HttpClient client = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36");
        HttpResponse response = client.execute(httpPost);
        HttpEntity entity = response.getEntity();
        if (null != entity) {
            String result = EntityUtils.toString(entity, "UTF-8");
            return JSONObject.parseObject(result);
        }
        httpPost.releaseConnection();
        return null;
    }

    /**
     * 获取用户信息
     * get
     */
    public static JSONObject getUserInfo(String url) throws IOException {
        JSONObject jsonObject = null;
        CloseableHttpClient client = HttpClients.createDefault();

        HttpGet httpGet = new HttpGet(url);
        httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36");
        HttpResponse response = client.execute(httpGet);
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            String result = EntityUtils.toString(entity, "UTF-8");
            jsonObject = JSONObject.parseObject(result);
        }

        httpGet.releaseConnection();

        return jsonObject;
    }
}

7、授权回调如下显示如下即成功

改成基于RestTemplete 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

卡布奇诺-海晨

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值