Spring Security 3 programmatically login

2019-03-17 07:05发布

问题:

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).

回答1:

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" :-)



回答2:

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:

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.