Spring Rest API通过另一个REST API进行身份验证

时间:2015-02-02 21:49:48

标签: security rest authentication spring-security

我有一个spring rest api,它通过数据库使用base64身份验证进行保护。是否有可能再采取另一种休息api并以某种方式通过第一个api进行身份验证?

3 个答案:

答案 0 :(得分:5)

您是否考虑过使用基于OAuth的身份验证和API密钥管理保护API。 HTTP基本身份验证并不是security perspective的理想选择,用户名和密码还有另一套security issues for APIs

无论哪种方式,您都可以考虑使用Stormpath让这对您来说非常简单。看一下this guide,它支持HTTP basic和OAuth。

此示例代码将让您了解这是多么容易。

假设您要公开名为startEngines()的操作并希望保护它。您还需要公开新操作以获取访问令牌,在此示例中为String getAccessToken(ApiKey)

您的用户将运行以下内容:

@Test
public void executeSomeOauth2AuthenticatedOperation() {

    String userApiKeyPath = System.getProperty("user.home") + "/.stormpath/apiKey_4Yrc0TJ5sBFldwtu6nfzf5.properties";
    ApiKey userApiKey = ApiKeys.builder().setFileLocation(userApiKeyPath).build();

    //Developer requests access token
    String accessToken = getAccessToken(userApiKey);

    //Developer executes an authenticated operation (e.g startEngines()) with the provided accessToken
    if (startEngines(accessToken)) {
        System.out.print("Client-side message: Execution allowed");
    } else {
        System.out.print("Client-side message: Execution denied");
    }
}

您的代码如下所示:

String path = System.getProperty("user.home") + "/.stormpath/apiKey.properties";
String applicationUrl = "https://api.stormpath.com/v1/applications/2TqboZ1qo73eDM4gTo2H94";
Client client = Clients.builder().setApiKey(ApiKeys.builder().setFileLocation(path).build()).build();
Application application = client.getResource(applicationUrl, Application.class);

public String getAccessToken(ApiKey apiKey) {
    HttpRequest request = createOauthAuthenticationRequest(apiKey);
    AccessTokenResult accessTokenResult = (AccessTokenResult) application.authenticateApiRequest(request);
    System.out.println(accessTokenResult.getScope());
    return accessTokenResult.getTokenResponse().getAccessToken();
}

public boolean startEngines(String accessToken) {
    HttpRequest request = createRequestForOauth2AuthenticatedOperation(accessToken);
    try {
        OauthAuthenticationResult result = application.authenticateOauthRequest(request).execute();
        System.out.println(result.getAccount().getEmail() + " is about to start the engines!");

        doStartEngines(); //Here you will actually call your internal doStartEngines() operation
        return true;

    } catch (AccessTokenOauthException e) {

        //This accessToken is not allowed to start the engines
        System.out.print("AccessToken: " + accessToken + " just tried to start the engines. He is not allowed to do so.");
        return false;

    }
}

private HttpRequest createOauthAuthenticationRequest(ApiKey apiKey) {
    try {
        String credentials = apiKey.getId() + ":" + apiKey.getSecret();

        Map<String, String[]> headers = new LinkedHashMap<String, String[]>();
        headers.put("Accept", new String[]{"application/json"});
        headers.put("Content-Type", new String[]{"application/x-www-form-urlencoded"});
        headers.put("Authorization", new String[]{"Basic " + Base64.encodeBase64String(credentials.getBytes("UTF-8"))});

        Map<String, String[]> parameters = new LinkedHashMap<String, String[]>();
        parameters.put("grant_type", new String[]{"client_credentials"});

        HttpRequest request = HttpRequests.method(HttpMethod.POST)
                .headers(headers)
                .parameters(parameters)
                .build();
        return request;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

private HttpRequest createRequestForOauth2AuthenticatedOperation(String token) {
    try {
        Map<String, String[]> headers = new LinkedHashMap<String, String[]>();
        headers.put("Accept", new String[]{"application/json"});
        headers.put("Authorization", new String[]{"Bearer " + token});
        HttpRequest request = HttpRequests.method(HttpMethod.GET)
                .headers(headers)
                .build();
        return request;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

private void doStartEngines() {
    System.out.println("Server-side message: Engines started!!!");
}

为了简单起见,我将所有这些代码都运行在同一台机器上(客户端和服务器端代码之间没有网络通信)。实际上,您需要使用Spring通过Rest API公开startEngines()String getAccessToken(ApiKey),让最终用户通过网络访问它们。

试一试,它应该是一个非常简单快速的解决方案。 :)

完全披露 - 我在Stormpath

工作

答案 1 :(得分:0)

Base64是一种编码机制,而不是身份验证方案。我假设您的意思是使用basic authentication,这是Authorization HTTP标头中编码的用户名和密码base64。

如果其他服务也使用基本身份验证并检查相同凭据数据库的用户名和密码,那么您将能够使用相同的base64编码字符串对其他REST服务进行身份验证。

答案 2 :(得分:0)

我所要做的就是让我的第二个API中的类捕获所有请求,调用第一个API,它已经连接到我的数据库,发送基本身份验证标头来验证凭据。