0

我在这里阅读了如何保护 REST 服务的非常好的答案,但所有这些都只是纯粹的理论,并没有太大帮助。使用 REST 时如何实现 JDBCRealm-FORM 身份验证?

登录表单

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Login Form</title>
</head>

<body>
<form method="post" action="j_security_check">
<p>You need to log in to access protected information.</p>
<table>
   <tr>
      <td>User name:</td>
      <td><input type="text" name="j_username" /></td>
   </tr>
   <tr>
      <td>Password:</td>
      <td><input type="password" name="j_password" /></td>
   </tr>
</table>
<p><input type="submit" value="Login" /></p>
</form>
</body>
</html>

web.xml

<security-constraint>
    <web-resource-collection>
        <web-resource-name>How to protect REST</web-resource-name>
        <url-pattern>/protected/*</url-pattern>----> What is that in case of rest?
        <http-method>GET</http-method>
        <http-method>POST</http-method>
        <http-method>HEAD</http-method>
        <http-method>PUT</http-method>
        <http-method>OPTIONS</http-method>
        <http-method>TRACE</http-method>
        <http-method>DELETE</http-method>
    </web-resource-collection>
    <auth-constraint>
        <role-name>admin</role-name>
        <role-name>customer</role-name>
        <role-name>user</role-name>
    </auth-constraint>
</security-constraint>
<login-config>
    <auth-method>FORM</auth-method>
    <realm-name>jdbcRealm</realm-name>

</login-config>
<security-role>
    <role-name>admin</role-name>
</security-role>
<security-role>
    <role-name>user</role-name>
</security-role>
<security-role>
    <description/>
    <role-name>customer</role-name>
</security-role>

问题:

1) 我在 Glassfish 中创建了 JDBCRealm,它正在工作。我用另一个 jsf-app 测试了它。在 clien-REST-service 的情况下,例如:<url-pattern>/protected/*</url-pattern>在正常情况下,它指的是受保护的 jsp/jsf/xhtml 等页面所在的“文件夹”,但现在在哪里?

2)会话呢?我认为在无状态上下文中使用会话是不可能的

3) 甚至可以在 REST 中使用基于 FORM 的身份验证吗?

4)任何比我聪明的人解释如何保护客户端 - 服务器休息应用程序的教程链接。

4

2 回答 2

1

1) 我在 Glassfish 中创建了 JDBCRealm,它正在工作。我用另一个 jsf-app 测试了它。在 clien-REST-service 的情况下,例如:/protected/* 在正常情况下,它指的是受保护的 jsp/jsf/xhtml 等页面所在的“文件夹”,但现在在哪里?

您可以选择保护整个 REST 服务子域或其中的一部分。假设您将 root 配置为/rest,这就是您将在 url-pattern 中放入的内容。

2)会话呢?我认为在无状态上下文中使用会话是不可能的

取决于您的 REST 实现。对于 JAX-RS (Jersey),答案是肯定的,您可以使用 HTTP 会话。@Context你通过注解将它注入到你的资源类中:

@Path("/echo")
public class EchoServiceImpl {
    @Context
    private HttpSession session;
}

确认您可以使用会话后,我强烈建议您不要这样做,因为 RESTful 调用应该是无状态的。

3) 甚至可以在 REST 中使用基于 FORM 的身份验证吗?

对 REST 使用基于表单的身份验证是没有意义的,不。您正在设计服务以供其他计算机系统使用,而不是由人类使用。该过程不应涉及交互式 UI。

4)任何比我聪明的人解释如何保护客户端 - 服务器休息应用程序的教程链接。

这是一个艰难的指南,那里有很多指南,但其中很多都非常特定于 REST 实现中使用的特定技术堆栈。首先,我建议您将当前配置从 FORM 更改为 BASIC,并考虑使用 SSL 保护您的端点。请记住,当您使用基本身份验证时,您需要在 Authorization 标头中包含用户凭据:

Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==

您可以在此处阅读有关如何计算标头的信息

一旦熟悉了基本/摘要式身份验证,您就可以开始查看更高级的安全选项,例如 OAuth。

于 2013-04-09T21:18:13.773 回答
1

不能使用 REST 进行 FORM 身份验证,因为每个请求本身都必须是完整的并且是无状态的。带有重定向的表单不是。您需要使用标准的基于 HTTP 标头的机制,例如 Basic、Digest 等。

于 2013-04-09T18:23:35.310 回答