如何在Spring应用程序中应用GitHub OAuth时修复“Whitelabel Error Page”错误?

huangapple go评论72阅读模式
英文:

How to fix 'Whitelabel Error Page' when applying GitHub OAuth in a Spring application?

问题

在我的Spring应用程序中尝试应用GitHub OAuth时出现Whitelabel Error Page错误。
这个应用程序没有明确的映射路径/error,所以你看到它作为一个后备页面。

2023年5月28日20:58:39 IRDT
发生了意外错误(类型=内部服务器错误,状态=500)。
由于输入结束,没有内容可映射到[来源:(字符串)"";行:1,列:0]。

这是我尝试打印或返回userDataResult.body后登录后出现错误的Java代码:

@RestController
public class LoginController {
    private String clientSecret = "541a3c6bdca41a233d593ed263f628915317c434";
    private String clientId = "f3cc203f5df4b2e30d5c";

    @GetMapping("/auth")
    public ResponseEntity<String> auth(@RequestBody String code) {
        String accessTokenString = String.format(
                "https://github.com/login/oauth/access_token?client_id=%s&client_secret=%s&code=%s", clientId,
                clientSecret, code);

        HttpClient client = HttpClient.newHttpClient();
        URI accessTokenUri = URI.create(accessTokenString);
        HttpRequest.Builder accessTokenBuilder = HttpRequest.newBuilder().uri(accessTokenUri);
        HttpRequest accessTokenRequest = accessTokenBuilder.POST(HttpRequest.BodyPublishers.noBody())
                .header("Accept", "Application/json").build();

        HttpResponse<String> accessTokenResult = null;
        try {
            accessTokenResult = client.send(accessTokenRequest, HttpResponse.BodyHandlers.ofString());
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
        ObjectMapper mapper = new ObjectMapper();
        HashMap<String, Object> resultBody = new HashMap<>();
        try {
            resultBody = mapper.readValue(accessTokenResult.body(), HashMap.class);
        } catch (JsonProcessingException e1) {
            e1.printStackTrace();
        }
        String accessToken = (String) resultBody.get("access_token");

        URI userDataUri = URI.create("https://api.github.com/user");
        HttpRequest.Builder userDataBuilder = HttpRequest.newBuilder().uri(userDataUri);
        HttpRequest req = userDataBuilder.GET().header("Authorization", String.format("token %s", accessToken)).build();
        try {
            HttpResponse<String> userDataResult = client.send(req, HttpResponse.BodyHandlers.ofString());
            GithubUser user = mapper.readValue(userDataResult.body(), GithubUser.class);
            System.out.println(userDataResult.body());

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}

还编写了一个HTML来检查:

<a href="https://github.com/login/oauth/authorize?client_id=f3cc203f5df4b2e30d5c&amp;scope=user"><h1>Click to login using github</h1></a>

已经尝试检查令牌是否为空,但我不知道为什么会为空,还尝试打印accessTokenResult.body()

英文:

Getting Whitelabel Error Page when try to apply Github OAuth in my spring application
This application has no explicit mapping for /error, so you are seeing this as a fallback.

Sun May 28 20:58:39 IRDT 2023
There was an unexpected error (type=Internal Server Error, status=500).
No content to map due to end-of-input at [Source: (String)""; line: 1, column: 0]

Here is my java code which I try to get userDataResult.body printed or even returned but getting the error after log-in:

@RestController
public class LoginController {
    private String clientSecret = &quot;541a3c6bdca41a233d593ed263f628915317c434&quot;;
    private String clientId = &quot;f3cc203f5df4b2e30d5c&quot;;

    @GetMapping(&quot;/auth&quot;)
    public ResponseEntity&lt;String&gt; auth(@RequestBody String code) {
        String accessTokenString = String.format(
                &quot;https://github.com/login/oauth/access_token?client_id=%s&amp;client_secret=%s&amp;code=%s&quot;, clientId,
                clientSecret, code);

        HttpClient client = HttpClient.newHttpClient();
        URI accessTokenUri = URI.create(accessTokenString);
        HttpRequest.Builder accessTokenBuilder = HttpRequest.newBuilder().uri(accessTokenUri);
        HttpRequest accessTokenRequest = accessTokenBuilder.POST(HttpRequest.BodyPublishers.noBody())
                .header(&quot;Accept&quot;, &quot;Application/json&quot;).build();

        HttpResponse&lt;String&gt; accessTokenResult = null;
        try {
            accessTokenResult = client.send(accessTokenRequest, HttpResponse.BodyHandlers.ofString());
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
        ObjectMapper mapper = new ObjectMapper();
        HashMap&lt;String, Object&gt; resultBody = new HashMap&lt;&gt;();
        try {
            resultBody = mapper.readValue(accessTokenResult.body(), HashMap.class);
        } catch (JsonProcessingException e1) {
            e1.printStackTrace();
        }
        String accessToken = (String) resultBody.get(&quot;access_token&quot;);

        URI userDataUri = URI.create(&quot;https://api.github.com/user&quot;);
        HttpRequest.Builder userDataBuilder = HttpRequest.newBuilder().uri(userDataUri);
        HttpRequest req = userDataBuilder.GET().header(&quot;Authorization&quot;, String.format(&quot;token %s&quot;, accessToken)).build();
        try {
            HttpResponse&lt;String&gt; userDataResult = client.send(req, HttpResponse.BodyHandlers.ofString());
            GithubUser user = mapper.readValue(userDataResult.body(), GithubUser.class);
            System.out.println(userDataResult.body());

        } catch (Exception e) {
            e.printStackTrace();
        }


        return null;
    }

Also wrote a html to check that out:

&lt;a href=&quot;https://github.com/login/oauth/authorize?client_id=f3cc203f5df4b2e30d5c&amp;scope=user&quot;&gt;&lt;h1&gt;Click to login using github&lt;/h1&gt;&lt;/a&gt;

Already tried checking if the token is empty and I don't know why it should be, also tried to print accessTokenResult.body()

答案1

得分: 0

以下是您要求的翻译代码部分:

    @GetMapping(value = "/auth", produces = MediaType.APPLICATION_JSON_VALUE)
    public String auth(@RequestParam(value = "code") String code) throws Exception {
        String accessTokenURL = String.format(
                "https://github.com/login/oauth/access_token?client_id=%s&client_secret=%s&code=%s",
                clientId, clientSecret, code
        );
        HttpClient client = HttpClient.newHttpClient();
        URI accessTokenURI = URI.create(accessTokenURL);
        HttpRequest.Builder accessTokenBuilder = HttpRequest.newBuilder().uri(accessTokenURI);
        HttpRequest accessTokenRequest = accessTokenBuilder.POST(HttpRequest.BodyPublishers.noBody())
                .header("Accept", "application/json").build();
        HttpResponse<String> accessTokenResult = client.send(accessTokenRequest, HttpResponse.BodyHandlers.ofString());
        ObjectMapper mapper = new ObjectMapper();
        HashMap<String, Object> resultBody = mapper.readValue(accessTokenResult.body(), HashMap.class);
        String accessToken = (String) resultBody.get("access_token");
        URI userDateURI = URI.create("https://api.github.com/user");
        HttpRequest.Builder userDataBuilder = HttpRequest.newBuilder().uri(userDateURI);
        HttpRequest req = userDataBuilder.GET().header("Authorization", String.format("token %s", accessToken)).build();
        HttpResponse<String> userDataResult = client.send(req, HttpResponse.BodyHandlers.ofString());
        HashMap<String, Object> userData = mapper.readValue(userDataResult.body(), HashMap.class);
        return userDataResult.body();
    }
英文:

Changed the code and this worked:

    @GetMapping(value = &quot;/auth&quot;, produces = MediaType.APPLICATION_JSON_VALUE)
    public String auth(@RequestParam(value = &quot;code&quot;) String code) throws Exception {
        String accessTokenURL = String.format(
                &quot;https://github.com/login/oauth/access_token?client_id=%s&amp;client_secret=%s&amp;code=%s&quot;,
                clientId, clientSecret, code
        );
        HttpClient client = HttpClient.newHttpClient();
        URI accessTokenURI = URI.create(accessTokenURL);
        HttpRequest.Builder accessTokenBuilder = HttpRequest.newBuilder().uri(accessTokenURI);
        HttpRequest accessTokenRequest = accessTokenBuilder.POST(HttpRequest.BodyPublishers.noBody())
                .header(&quot;Accept&quot;, &quot;application/json&quot;).build();
        HttpResponse&lt;String&gt; accessTokenResult = client.send(accessTokenRequest, HttpResponse.BodyHandlers.ofString());
        ObjectMapper mapper = new ObjectMapper();
        HashMap&lt;String, Object&gt; resultBody = mapper.readValue(accessTokenResult.body(), HashMap.class);
        String accessToken = (String) resultBody.get(&quot;access_token&quot;);
        URI userDateURI = URI.create(&quot;https://api.github.com/user&quot;);
        HttpRequest.Builder userDataBuilder = HttpRequest.newBuilder().uri(userDateURI);
        HttpRequest req = userDataBuilder.GET().header(&quot;Authorization&quot;, String.format(&quot;token %s&quot;, accessToken)).build();
        HttpResponse&lt;String&gt; userDataResult = client.send(req, HttpResponse.BodyHandlers.ofString());
        HashMap&lt;String, Object&gt; userData = mapper.readValue(userDataResult.body(), HashMap.class);
        return userDataResult.body();
    }

huangapple
  • 本文由 发表于 2023年5月29日 00:40:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76352533.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定