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

前端回调地址:

后端回调地址:和前端一样即可

前端JS调用谷歌登录代码:

前端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调用谷歌登录代码

    @GetMapping("/googleLoginUrl")
    public AjaxResult googleLoginUrl(HttpServletResponse response){
        HttpTransport httpTransport = new NetHttpTransport();
        JsonFactory jsonFactory = GsonFactory.getDefaultInstance();

        List<String> SCOPES =         
        Arrays.asList("https://www.googleapis.com/auth/userinfo.email");

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

        // 生成用户授权的 URL
        AuthorizationCodeRequestUrl authorizationUrl = flow.newAuthorizationUrl()
                .setRedirectUri("http://localhost:8075/code");

        return AjaxResult.success(authorizationUrl.build());
    }

 后端重定向接口随意写,写前端域名也可以

    @GetMapping("/code")
    public String getCode(HttpServletRequest request) {
        System.out.println("调用code接口");
        return request.getParameter("code");
    }

 后端获取code码进行验证

/**
     * 使用code进行验证
     * @param googleDTO
     * @return
     * @throws GeneralSecurityException
     * @throws IOException
     */
    @PostMapping("/googleLogin")
    public AjaxResult googleLogin(@RequestBody GoogleDTO googleDTO) throws GeneralSecurityException, IOException {

        try {
            // 创建 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(googleDTO.getCode())
                    .setRedirectUri("http://localhost:8075/code")
                    .execute();
            String accessToken = tokenResponse.getAccessToken();

            String userInfo = getUserInfo(accessToken);

            JSONObject jsonObject = JSONObject.parseObject(userInfo);

            String email =  jsonObject.getString("email") ;
            String userId =  jsonObject.getString("id") ;
            String pictureUrl =  jsonObject.getString("picture") ;
            //国家
            String locale =  jsonObject.getString("locale") ;
            String name =  jsonObject.getString("name") ;

            //校验账号是否存在
            GlobalUser checkGlobalUser = globalUserService.checkSubject(userId);
            if (Objects.nonNull(checkGlobalUser)){
                GlobalUser globalUser = new GlobalUser();
                globalUser.setPictureUrl(pictureUrl);
                globalUser.setEmail(email);
                globalUser.setgoogleId(userId);
                globalUser.setStatus(0);
                globalUser.setId(checkGlobalUser.getId());
                globalUserService.updateGlobalUser(globalUser);
            }else{
                GlobalUser globalUser = new GlobalUser();
                globalUser.setEmail(email);
                globalUser.setgoogleId(userId);
                globalUser.setStatus(0);
                globalUser.setPictureUrl(pictureUrl);
                globalUserService.insertGlobalUser(globalUser);
            }
            Map<String, String> map = new HashMap<>();
            map.put("email", email);
            map.put("name", name);
            map.put("status","0");
            // 生成令牌
            String token = JWTUtils.getToken(map);

            AjaxResult ajax = AjaxResult.success();

            ajax.put(Constants.TOKEN, token);
            ajax.put(Constants.USERNAME, email);

            return ajax;
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error();
        }
    }

获取用户信息

    //获取用户信息
    public  String getUserInfo(String accessToken) {

        String url = "https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + accessToken;
        try {
            return HttpClient4Util.getResponse4GetAsString(url,"utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

 添加依赖maven

<dependency>
    <groupId>com.google.auth</groupId>
    <artifactId>google-auth-library-oauth2-http</artifactId>
    <version>0.22.2</version>
</dependency>
<dependency>
    <groupId>com.google.api-client</groupId>
    <artifactId>google-api-client</artifactId>
    <version>1.32.1</version>
</dependency>
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值