13

I am a newbie to REST webservice and have just created my first webservice.
In my service the user can create profile via simple form giving his desired Username and password.

Now how to check user credentials when the user logs-in ??
I mean i have a simple form which validates user has logged in but how to validate user when he is to perform various profile operation of add/update/delete ??

For example:
In FB you sign-in and it stores a cookie which has your credentials and when you perform operations like "Post Status",message a friend...etc... it doesn't ask for your credentials anymore because it has a cookie in which your credentials are there and it just uses that cookie...

But in REST we dont use cookie ,so the next option is HTTP headers. And i want to know how to send and recieve user credentials via HTTP header .i.e
Basic HTTP Auth

4

1 回答 1

29

客户端

要将凭据发送到 API,请使用 HTTPAuthorization标头,以Basic username:password. username:password 字符串必须使用称为Base64的编码方案进行编码。因此,示例标头可能如下所示:

Authorization: Basic d2lraTpwZWRpYQ==

由于其余规范规定客户端-服务器通信应该是无状态的,因此您必须在每个请求中包含带有凭据的标头。通常,您将在客户端使用会话 cookie 来识别用户,这样他就不必在每次请求时都输入他的凭据。

服务器端

要检查 Jersey REST 服务中的凭据,您需要捕获并拦截所有传入请求。Jersey 提供了一个概念,称为ContainerRequestFilters执行此操作。例如,如果您使用 Tomcat,您可以在 web.xml 中的 servlet 定义中添加这种类型的过滤器,如下所示:

<init-param>
    <param-name>com.sun.jersey.spi.container.ContainerRequestFilters</param-name>
    <param-value>your.package.BasicAuthFilter</param-value>
</init-param>

被引用的类BasicAuthFilter需要实现 JerseysContainerRequestFilter接口并重写该public ContainerRequest filter(ContainerRequest request)方法。在该方法中,您将基本上执行以下操作:

  • 从请求的 Authorization 标头中获取 Base64 编码的凭据
  • 解码它们(即使用javax.xml.bind.DatatypeConverter.parseBase64Binary()
  • 使用您的 UserDao(或其他数据源提供者)检查凭据是否有效
  • 如果验证失败则返回状态码401 Unauthorized(即throw new WebApplicationException(Status.UNAUTHORIZED)
  • 如果凭据有效,只需返回请求,以便将其委托给负责处理它的 Jersey 资源

你可以在这篇博文中找到一个很好的例子。

于 2013-07-05T14:23:12.180 回答