1

您好,我遇到了 oauth2 问题。我不使用弹簧。我有一些使用 netbeans 包含的球衣罐组成的 JAX-RS Web 服务。我必须使用 oauth 2 保护此服务,以便移动客户端可以在不存储用户凭据的情况下使用它。我什至不知道从哪里开始,因为我看到的所有示例都使用 Spring ...那些不使用 Spring 的示例使用 Oltu 库,其文档无法说服我。一些 oltu 示例甚至不起作用。谁能给我看一个教程,帮助我使用球衣和一些库从头开始构建授权服务器?任何一个甚至是 oltu ...

4

1 回答 1

0

我的回答将基于 Oltu。我将使用CLIENT_CREDENTIALS身份验证。

获取令牌应如下所示:

// We initialize a client
OAuthClient lOAuthClient = new OAuthClient(new URLConnectionClient());
OAuthJSONAccessTokenResponse lOAuthResponse;

// We are creating a request that's already formatted following the Oauth specs
OAuthClientRequest lRequest = OAuthClientRequest
        .tokenLocation(TOKEN_SERVER_URI)
        .setGrantType(GrantType.CLIENT_CREDENTIALS)
        .setClientId(CLIENT_ID)
        .setClientSecret(CLIENT_SECRET)
        .setScope("admin")
        .buildBodyMessage();

//This will submit the request
String code =  lOAuthClient.accessToken(lRequest, OAuthJSONAccessTokenResponse.class).getAccessToken();
System.out.println("Token obtained:" + token);

现在我们可以使用我们的令牌获取我们的资源:

HttpURLConnection resourceConn = (HttpURLConnection) (new URL(RESSOURCE_SERVER_URI).openConnection());
resourceConn.addRequestProperty("Authorization", "Bearer " + token);

InputStream resource = resourceConn.getInputStream();

// Do whatever you want to do with the contents of resource at this point.
BufferedReader r = new BufferedReader(new InputStreamReader(resource, "UTF-8"));
String line = null;
while ((line = r.readLine()) != null)
    System.out.println(line);
于 2017-05-03T13:27:13.417 回答