Spring security, either http basic or form login a

2020-06-23 08:46发布

问题:

I have a web app developed using spring mvc and spring security 3.2. I want my app using http basic authentication for restful service and form login authentication for other part. Below is my security configuration:

<http pattern="/services/**" create-session="stateless" use-expressions="true">
    <intercept-url pattern="/**" access="hasRole('ROLE_REMOTE,ROLE_USER')"/>
    <http-basic />
</http>

<http auto-config="true" use-expressions="true">
    <intercept-url pattern="/static/**" access="permitAll" />
    <intercept-url pattern="/**" access="hasRole('ROLE_USER')" />
    <form-login login-page="/login.do" always-use-default-target="true"     default-target-url="/main.do" />
    <logout invalidate-session="true" logout-success-url="/login.do"
        logout-url="/j_spring_security_logout" />
</http>

what I expect is: when a user login from the form, then it can invoke the restful service without go through basic authentication (Since it has been authenticated). My thought is that a user with role 'ROLE_USER' should also call the restful service. However, what I got is after I logined from the form, I was also prompted to do basic authentication trying to call the restful service from browser.

Is there anyway to get what I expect?

回答1:

The answer could be in the description of the create-session attribute:

  • never - Spring Security will never create a session, but will make use of one if the application does.
  • stateless - Spring Security will not create a session and ignore the session for obtaining a Spring Authentication.

Since you chose stateless the auth object persisted in the session after the form-login is ignored. Try if never works as you expect.