Spring Security 3以编程方式登录

时间:2010-10-15 21:38:04

标签: rest login spring-security

我正在使用spring创建一个REST Web服务,我需要在其中实现登录/注销功能。函数的url应该是...... / api / login和... / api / logout。用户名和密码将使用POST方法过去。

我在REST Web服务下面有一个服务层。在服务层,我有“登录”和“注销”功能的代码。我想使用spring security来保存登录用户在spring的上下文中。我找到了几个答案,但没有给出完整的例子说明如何做到这一点。我也想知道使用spring安全性进行这种自定义身份验证的最先进方法是什么(不使用任何登录表单,只需编程登录/注销)。

3 个答案:

答案 0 :(得分:3)

最好的方法是将您的身份验证实现插入Spring Security。 您可以通过在Spring Security中注册自己的“身份验证提供程序”来实现。

例如:

<bean id="authenticationManager" class="org.springframework.security.providers.ProviderManager">
    <property name="providers">
        <list>
            <ref local="myAuthenticationProvider"/>
        </list>
    </property>
</bean>

<bean id="myAuthenticationProvider" class="org.my.web.restapi.authentication.MyAuthenticationProvider"/>

另一件事:我知道这是一段时间,但在阅读Spring Security reference之后,你肯定会得到“全局”: - )

答案 1 :(得分:0)

如果您使用的是基本身份验证管理器,则以下代码将在您的应用中获取它而无需额外的xml配置:

@SuppressWarnings({"SpringJavaAutowiringInspection"})
@Resource(name = "org.springframework.security.authenticationManager")
private AuthenticationManager authenticationManager;

答案 2 :(得分:-1)

不确定这是否是您所需要的。 以编程方式致电http://localhost:8080/webappname/j_spring_security_check 在表单参数j_username和j_password中传递用户名密码。 在security-app-context.xml中,用

替换form-login元素
<form-login login-page="/login" login-processing-url="/j_spring_security_check"
    authentication-success-handler-ref="myAuthenticationSuccessHandler" 
    authentication-failure-handler-ref="myAuthenticationFailureHandler"/>

<beans:bean id="myAuthenticationSuccessHandler" class="com.something.MyAuthenticationSuccessHandler" />
<beans:bean id="myAuthenticationFailureHandler" class="com.something.MyAuthenticationFailureHandler" />

实现spring的AuthenticationSuccessHandler和AuthenticationFailureHandler。默认行为是重定向到登录表单。