Spring Security 3 programmatically login

2019-03-17 07:16发布

I'm creating a REST web service using spring and I need to implement login/logout functions in it. The url for the functions should be something like .../api/login and .../api/logout. The username and password will be past using a POST method.

I have a services layer below the REST web service. In the service layer i have the "login" and "logout" functions' code. I want to use spring security to save the logged in user in the context of spring. I found several answers but nothing gives a complete example of how to do it. I also wonder what's the state-of-the-art way of doing this custom authentication with spring security (without using any login form, just programmatic login/logout).

3条回答
欢心
2楼-- · 2019-03-17 07:36

If you're after the basic authentication manager, the following code will get it in your app without extra xml config:

@SuppressWarnings({"SpringJavaAutowiringInspection"})
@Resource(name = "org.springframework.security.authenticationManager")
private AuthenticationManager authenticationManager;
查看更多
混吃等死
3楼-- · 2019-03-17 07:38

Not sure if this is what you need. Programmatically call http://localhost:8080/webappname/j_spring_security_check Pass the username password in form parameters j_username and j_password. In the security-app-context.xml replace form-login element with

<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" />

Implement spring's AuthenticationSuccessHandler and AuthenticationFailureHandler. The default behavior is to redirect to login form.

查看更多
萌系小妹纸
4楼-- · 2019-03-17 07:50

The best way is to plugin your authentication implementation into Spring Security. You can do it by registering your own "authentication provider" into Spring Security.

For example:

<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"/>

Another thing: I know it's a time consuming, but after reading Spring Security reference you will definitely get the "big picture" :-)

查看更多
登录 后发表回答