在REST服务中保持身份验证启用

时间:2013-03-25 17:07:00

标签: java rest authentication jersey

所以问题是:我在Jersey上开发了REST服务,它运行在Glassfish上。 对于身份验证,我实施了基本身份验证。在客户端,我通过 ApacheHTTPClient 实现了身份验证。

我的想法是在注册用户输入时请求身份验证 - 例如登录。 是在客户端应用程序中配置(在用户注销之前保持身份验证有效),还是在我配置基本身份验证的REST服务中配置?

谢谢!


这就是我在客户端应用程序上进行登录的方式:

import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;

public class UserLogin {

    private static final String BASE_URI = "http://localhost:8080/LULServices/webresources";

    public static void main(String[] args) throws Exception {

    final DefaultHttpClient httpclient = new DefaultHttpClient();

    try {
            httpclient.getCredentialsProvider().setCredentials(
                new AuthScope("localhost", 8080),
                new UsernamePasswordCredentials("zzzzz", "xxxxx"));

    HttpPut httpPut = new HttpPut(BASE_URI + "/services.users/login");
    HttpConnectionParams.setConnectionTimeout(httpclient.getParams(), 10000);

    httpPut.addHeader("Content-type", "multipart/form-data");

    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("login", "zzzzz"));
    nameValuePairs.add(new BasicNameValuePair("password","xxxxx"));

    httpPut.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    HttpResponse response = httpclient.execute(httpPut);

    try {
            System.out.println("Executing request " + httpPut.getRequestLine());
            HttpEntity entity = response.getEntity();

            System.out.println("----------------------------------------");
            System.out.println("HTTP Status: " + response.getStatusLine());

            String putResponse = EntityUtils.toString(entity);
            System.out.println(putResponse);
            EntityUtils.consume(entity);

        } finally
            httpPut.releaseConnection();

        } finally
            httpclient.getConnectionManager().shutdown();
    }
}

它返回给用户他的secret_id。

2 个答案:

答案 0 :(得分:1)

Darrel Miller所述,基于REST的服务应该是无状态的。 但为了帮助您解决当前问题,我建议使用 auth 令牌和刷新策略。

说明 每次成功验证后,您的服务器都可以返回唯一 27 [您想要的任何长度]数字字符串。此令牌可能有也可能没有到期策略[取决于您的需求]。因此,对于后续身份验证[当客户端应用程序具有身份验证令牌时],您实际上可以提供新的身份验证令牌并使之前的令牌无效。

此外,对于每个其他API调用,您都可以发送此身份验证令牌以验证请求是否来自经过身份验证的来源。现在,当用户退出应用程序时,您只需从客户端删除身份验证令牌即可。

下次当用户返回应用程序时,该应用程序将没有身份验证令牌,可以重定向到登录屏幕。

答案 1 :(得分:0)

基于REST的服务应该是无状态的。理想情况下,服务器上应该没有登录概念。您可以通过决定是否发送authn标头来模拟客户端上的登录/注销。