Spring Boot Sping Boot :OAuth2Credentials示例不支持刷新访问令牌

6za6bjd0  于 2023-06-22  发布在  Spring
关注(0)|答案(1)|浏览(178)

我正在使用Sping Boot ,收到了以下错误消息:{"errors":["OAuth2Credentials instance does not support refreshing the access token. An instance with a new access token should be used, or a derived type that supports refreshing."]}

@GetMapping("/callback")
    public ResponseEntity<String> callback(@RequestParam(value = "code") String code) throws IOException {

        TokenResponse tokenResponse = authService.getTokenResponse(code, CALLBACK_URI);
        List<String> scopes = List.of("https://www.googleapis.com/auth/userinfo.email");

        GoogleCredentials credentials = GoogleCredentials.create(new AccessToken(tokenResponse.getAccessToken(), null));
        GoogleCredentials scopedCredential = credentials.createScoped(scopes);

        HttpRequestInitializer initializer = new HttpCredentialsAdapter(scopedCredential);
        Oauth2 oauth2 = new Oauth2.Builder(httpTransport, jacksonFactory, initializer)
                .setApplicationName("Test") // replace with your application name
                .build();

        Userinfo userinfo = oauth2.userinfo().get().execute();
        String email = userinfo.getEmail();
        System.out.println(email);
        return ResponseEntity.status(HttpStatus.OK).build();
    }

在这行代码中弹出错误:Userinfo userinfo = oauth2.userinfo().get().execute();。我正在尝试获取用户的电子邮件。

moiiocjp

moiiocjp1#

我找到解决办法了。在我的www.example.com中,我必须将www.example.com范围添加到我的GoogleAuthorizationCodeFlow。GoogleAuthService.java I had to add the userinfo.email scope to my GoogleAuthorizationCodeFlow .

public String getAuthorizationUrl(String callbackUrl) {
        List<String> scopes = new ArrayList<>(Arrays.asList(
                "https://www.googleapis.com/auth/userinfo.email",
                CalendarScopes.CALENDAR
        ));
        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, jacksonFactory, googleClientSecrets, scopes)
                .setAccessType("offline")
                .build();
        return flow.newAuthorizationUrl().setRedirectUri(callbackUrl).build();
    }

相关问题