Spring 基于 MVC 的 RESTfull Web Services 身份验证,使用 'Remember Me'



我有休息的API。我使用了Spring MVC注释。我需要对用户 ID 进行身份验证,并在身份验证时创建一个会话并允许用户调用其他 API,直到会话持续。我的问题是:创建会话并维持它是否违背了休息的想法。如果是,如何保护我的 Restful API?如果我不保护它,网络中的任何人都可以点击 URL 并获得响应。请指教!

事实上,你是对的,REST应该是无状态的,这意味着保留带有会话ID的cookie违背了原则。但不要绝望,有解决方案。

基本

我假设您正在使用弹簧安全性。最简单的选择是对 REST 路径使用无状态 HTTP Basic 身份验证,并为站点的其余部分保留表单登录,这在 spring-security 中直接支持。安全配置 XML 如下所示:

<!-- for the REST api, the ROLE_API_CONSUMER is a custom role
     I usually use so that not all users are allowed to use the API -->
<security:http pattern="/api/**" auto-config="false" create-session="stateless">
    <security:http-basic />
    <security:intercept-url pattern="/api/**" access="ROLE_API_COSUMER" />
</security:http>
<!-- for the other MVC controllers -->
<security:http auto-config="true">
    <security:form-login />
</security:http>
<!-- usual stuff to keep track of users -->
<security:authentication-manager>
    <security:authentication-provider
        user-service-ref="userDetailsService">
        <security:password-encoder ref="encoder" />
    </security:authentication-provider>
</security:authentication-manager>

此方法要求HTTPS真正安全,并且缺点是REST客户端必须存储用户的用户名和密码。如果客户端是智能手机,则窃取手机将以纯文本形式访问用户的凭据。

OAuth

OAuth(1.0a 或 2)是大多数现代 API 使用的,并提供额外的安全级别。要访问 API,REST 客户端首先请求对服务器的访问权限,而不是存储用户的凭据。简而言之,服务器随后向用户显示"您是否批准此客户端访问 API?-某种通知,如果用户批准,REST 客户端将获得一个令牌,该令牌可用于以用户身份进行身份验证,但没有用户的密码。如果用户的手机被盗,小偷在那里看不到任何密码,并且访问令牌可能无效。

我没有在 spring-security 中设置 OAuth 的经验,但确实有一个模块,请检查 http://static.springsource.org/spring-security/oauth/

我希望对您有所帮助!

最新更新