Java实现Google授权登录,OAuth 2.0登录

首先创建OAuth 2.0 客户端 ID
在这里插入图片描述
配置url,必须是https的,同时复制好客户端id 和密钥

在这里插入图片描述
配置回调url
在这里插入图片描述

    /**
     * Google授权登录跳转。但是会重定向,建议前端跳转
     *
     * 前端js
     * // 构建 Google 授权 URL
     * const authParams = new URLSearchParams({
     *   response_type: 'code', //固定
     *   client_id: 'YOUR_CLIENT_ID', // 请将 YOUR_CLIENT_ID 替换为实际的客户端 ID
     *   scope: 'openid email profile',  //固定
     *   redirect_uri: 'YOUR_REDIRECT_URI', // 在Google配置的回调url
     * });
     *
     * const authUrl = `https://accounts.google.com/o/oauth2/v2/auth?${authParams}`;
     *
     通过Java接口跳转Google登录页面,会重定向,建议前端跳转
     * @param response
     * @return
     * @throws IOException
     */
    @GetMapping("/google-login")
    @NoAuth
    public CommonResult<String> googleLogin(HttpServletResponse response) throws IOException {
        HttpTransport httpTransport = new NetHttpTransport();
        JsonFactory jsonFactory = GsonFactory.getDefaultInstance();

        // 设置 OAuth 2.0 授权码流对象
        AuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
                httpTransport, jsonFactory, CLIENT_ID, CLIENT_SECRET, SCOPES)
                .setAccessType("offline")
                .setApprovalPrompt("force") // 可选,强制用户重新授权
                .build();

        // 生成用户授权的 URL
        AuthorizationCodeRequestUrl authorizationUrl = flow.newAuthorizationUrl()
                .setRedirectUri(REDIRECT_URI);

        // 重定向用户到授权 URL
        response.sendRedirect(authorizationUrl.build());
        return new CommonResult("success");
    }

回调接口

 @GetMapping("/google-callback")
    @NoAuth //不需要登录
    public ResponseEntity<String> googleCallback(@RequestParam("code") String authorizationCode) throws IOException {
        System.out.println("google-callback code = "+authorizationCode);

        // 创建 Google 授权码流对象
        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
                new NetHttpTransport(),
                JacksonFactory.getDefaultInstance(),
                CLIENT_ID,
                CLIENT_SECRET,
                Arrays.asList("openid", "email", "profile"))
                .setAccessType("offline")
                .build();

        // 交换授权码为访问令牌
        TokenResponse tokenResponse = flow.newTokenRequest(authorizationCode)
                .setRedirectUri(REDIRECT_URI)
                .execute();
        String accessToken = tokenResponse.getAccessToken();

//        System.out.println("google accessToken: "+accessToken);

        String userInfo = getUserInfo(accessToken);
//        System.out.println("userInfo: "+userInfo);
        /** 格式
         * {
         *   "iss": "https://accounts.google.com",
         *   "sub": "123456789012345678901",  表示用户的唯一标识符,通常是用户的Google ID。
         *   "aud": "your-client-id",
         *   "email": "user@example.com",
         *   "email_verified": true,
         *   "exp": 1627889766,
         *   "iat": 1627886166
         * }
         */
        JSONObject jsonObject = JSONObject.parseObject(userInfo);
        String email =  jsonObject.getString("email") ;
        //登录逻辑
        JSONObject userJson = loginByEmail(email);
        String redirectUrl = "https://funflixvideo.com/#/?userId="+userJson.getString("userId")+"&sessionId="+userJson.getString("sessionId");
        // 重定向到 H5 页面,并带上 session ID
        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(URI.create(redirectUrl));
        return new ResponseEntity<>(headers, HttpStatus.FOUND);
    }
    
    //获取用户信息
 public  String getUserInfo(String accessToken) {

        String url = "https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + accessToken;
        try {
            return HttpClient4Utils.httpGet(url, null, "utf-8", 30);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

pywanggui

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

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

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

打赏作者

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

抵扣说明:

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

余额充值