Spring mvc login with Spring security behave diffe

2019-08-20 08:26发布

问题:

I created a Spring mvc application with Spring security login authentication. Here is the code

Spring security.xml

<http auto-config="true" use-expressions="true">
        <intercept-url pattern="/login" access="isAnonymous()"/>
        <intercept-url pattern="/**" access="hasRole('ROLE_ADMIN')" />

        <!-- access denied page -->
        <access-denied-handler error-page="/403" />
        <form-login 
            login-page="/login" 
            default-target-url="/welcome"
            authentication-failure-url="/login?error" 
            username-parameter="username"
            password-parameter="password" />
        <logout logout-success-url="/login?logout" />
        <!-- enable csrf protection -->
        <csrf />
    </http>

    <authentication-manager>
        <authentication-provider user-service-ref="userDetailsService" >
            <password-encoder hash="bcrypt" />    
        </authentication-provider>
    </authentication-manager>

Here i provide login authentication for all urls in the application. But each time i started the server application behave differently.

  1. When started the server first time it delivers the login page. But is miss out all css and js files.Page delivers with no styles.Then i click login button it goes to logo.png file in the resource folder.

  2. When i start server for the second time, login page displayed with all Styles and js files.But when i click login button it goes a javascript file called app.js in resource folder.

  3. When i start for the third time login page display properly and when click login button it shows the right page.That is home.jsp page.

That means i can use the application only after starting the server more than one time.

If I omit <intercept-url pattern="/login" access="isAnonymous()"/> and change url to

<intercept-url pattern="/home**" access="hasRole('ROLE_ADMIN')" />

It will works smoothly without these problems.

Why would this happened?

回答1:

You should list all the patterns that match your static resources (style and js files), and add, before your an exclusion like

<intercept-url pattern="/resources/**" filters="none"/>

this would load all the css and js files that are under resources folder, which is located under webapp root. You should just adjust the patterns to match the location of your files