使用Java控制台应用程序(Spring oauth授权服务器)模拟授权代码检索

时间:2018-12-18 20:24:29

标签: java oauth-2.0 spring-oauth2

我有一个启用了csrf的Spring oauth授权服务器。客户端将使用SSO遵循授权代码路径-我转到我的网站,点击登录,重定向到授权页面,登录然后返回。

我正在模拟客户端将通过控制台使用Java应用程序通过浏览器进行客户端处理的过程。这是必需的。将来,我们将在我们的体系结构中为微服务使用此代码。

每当我尝试调用授权服务器auth端点时,都会收到403 CSRF令牌丢失异常(请参见下文)。我认为这是可以预期的。然后的问题是-我如何获得令牌,放入请求的标头并检索该访问代码?

我当前的代码:

private final String clientId = "my_client_id";
private final String authorizeUrl = "http://localhost:8085/oauth/authorize";
private final String callbackURL = "";

private String getUserAuthorizationURL() {
    return authorizeUrl + "?" + "response_type=code&" + "client_id=" + clientId + "&" + "redirect_uri="
            + callbackURL + "&" + "scope=openid";
}

public void getAuthorizationCode() {

    String content = "";

    HttpPost post = null;
    CloseableHttpClient httpclient = null;
    CloseableHttpResponse response = null;
    BufferedReader reader = null;

    try {
        post = new HttpPost(getUserAuthorizationURL());
        // pretty sure I need to add csrf token to post header here, but I dont know how to get it
        httpclient = HttpClients.createDefault();
        response = httpclient.execute(post);

        String line = null;
        HttpEntity entity = response.getEntity();
        reader = new BufferedReader(new InputStreamReader(entity.getContent())); 

        while ((line = reader.readLine()) != null) {
            content += line;
        }

        EntityUtils.consume(entity);
        System.out.println(content);
    } 
    catch (Exception ex) {
        ex.printStackTrace();
    }
}

JSON响应:

  

{“时间戳”:12345,“状态”:403,“错误”:“禁止”,“消息”:“可以   无法验证提供的CSRF令牌,因为您的会话没有   找到了。“,”路径“:” / oauth / authorize“}

我是否需要对服务器进行初始调用,从那里的调用中检索csrf令牌?如果我正在使用未内置会话的Java应用程序,该怎么办?即使当我尝试进行初始呼叫时,也会出现一个例外,我们需要进行完全身份验证才能访问http://localhost:8085/login

0 个答案:

没有答案