Spring-Security : Username is sent empty for login

2020-03-12 05:06发布

问题:

I am working on a Spring-MVC based application in which we are using Spring-Security for login, authorization. We were using version 3.2.5 before and the upgrade was 4.1.1. After upgrading though, the login mechanism is broken as username sent out is null. I don't know what is going wrong. Any help would be nice.

securityApplicationContext.xml :

<security:http pattern="/resources/**" security="none"/>

    <security:http create-session="ifRequired" use-expressions="true" auto-config="false" disable-url-rewriting="true">
        <security:form-login login-page="/login" login-processing-url="/j_spring_security_check" default-target-url="/dashboard" always-use-default-target="false" authentication-failure-url="/denied" />
        <!--<security:remember-me key="_spring_security_remember_me" user-service-ref="userDetailsService" token-validity-seconds="1209600" data-source-ref="dataSource"/>-->
        <security:logout delete-cookies="JSESSIONID" invalidate-session="true" logout-url="/j_spring_security_logout"/>
<!--     <security:intercept-url pattern="/**" requires-channel="https"/> -->
        <security:intercept-url pattern="/j_spring_security_check" access="permitAll" />
        <security:port-mappings>
        <security:port-mapping http="8080" https="8443"/>
    </security:port-mappings>
    <security:logout logout-url="/logout" logout-success-url="/" success-handler-ref="myLogoutHandler"/>

     <security:session-management session-fixation-protection="migrateSession">
         <security:concurrency-control session-registry-ref="sessionRegistry" max-sessions="5" expired-url="/login"/>
     </security:session-management>
    <security:csrf disabled="true"/>
    </security:http>
 <security:authentication-manager alias="authenticationManager">
        <security:authentication-provider user-service-ref="LoginServiceImpl">
           <security:password-encoder  ref="encoder"/>
        </security:authentication-provider>
    </security:authentication-manager>

    <beans:bean id="encoder"
                class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder">
        <beans:constructor-arg name="strength" value="11" />
    </beans:bean>

    <beans:bean id="daoAuthenticationProvider"
                class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
                <beans:property name="userDetailsService" ref="LoginServiceImpl"/>
               <beans:property name="passwordEncoder" ref="encoder"/>
    </beans:bean>

web.xml :

<context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/root-context.xml,/WEB-INF/spring/appServlet/security-applicationContext.xml</param-value>
    </context-param>

    <session-config>
        <session-timeout>2440</session-timeout>
    </session-config>
    <listener>
        <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
    </listener>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
 <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
        <async-supported>true</async-supported>
        <init-param>
            <param-name>contextAttribute</param-name>
            <param-value>org.springframework.web.context.WebApplicationContext.ROOT</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

Debug log :

DEBUG: org.springframework.security.web.util.matcher.AntPathRequestMatcher - Checking match of request : '/j_spring_security_check'; against '/resources/**'
DEBUG: org.springframework.security.web.FilterChainProxy - /j_spring_security_check at position 1 of 12 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
DEBUG: org.springframework.security.web.context.HttpSessionSecurityContextRepository - HttpSession returned null object for SPRING_SECURITY_CONTEXT
DEBUG: org.springframework.security.web.context.HttpSessionSecurityContextRepository - No SecurityContext was available from the HttpSession: org.apache.catalina.session.StandardSessionFacade@56af71ce. A new one will be created.
DEBUG: org.springframework.security.web.FilterChainProxy - /j_spring_security_check at position 2 of 12 in additional filter chain; firing Filter: 'ConcurrentSessionFilter'
DEBUG: org.springframework.security.web.FilterChainProxy - /j_spring_security_check at position 3 of 12 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
DEBUG: org.springframework.security.web.FilterChainProxy - /j_spring_security_check at position 4 of 12 in additional filter chain; firing Filter: 'HeaderWriterFilter'
DEBUG: org.springframework.security.web.header.writers.HstsHeaderWriter - Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher@2a868e9a
DEBUG: org.springframework.security.web.FilterChainProxy - /j_spring_security_check at position 5 of 12 in additional filter chain; firing Filter: 'LogoutFilter'
DEBUG: org.springframework.security.web.util.matcher.AntPathRequestMatcher - Checking match of request : '/j_spring_security_check'; against '/j_spring_security_logout'
DEBUG: org.springframework.security.web.FilterChainProxy - /j_spring_security_check at position 6 of 12 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter'
DEBUG: org.springframework.security.web.util.matcher.AntPathRequestMatcher - Checking match of request : '/j_spring_security_check'; against '/j_spring_security_check'
DEBUG: org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter - Request is to process authentication
DEBUG: org.springframework.security.authentication.ProviderManager - Authentication attempt using org.springframework.security.authentication.dao.DaoAuthenticationProvider
Username is 
DEBUG: org.springframework.security.authentication.dao.DaoAuthenticationProvider - User '' not found
DEBUG: org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter - Authentication request failed: org.springframework.security.authentication.BadCredentialsException: Bad credentials
DEBUG: org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter - Updated SecurityContextHolder to contain null Authentication
DEBUG: org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter - Delegating to authentication failure handler org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler@75d32cb4
DEBUG: org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler - Redirecting to /denied
DEBUG: org.springframework.security.web.DefaultRedirectStrategy - Redirecting to '/denied'

Login code :

<div class="col-xs-12 col-sm-10 col-sm-offset-1 col-md-8 col-md-offset-2 col-lg-4 col-lg-offset-4">
    <div class="container-fluid white-div">
        <div class="col-xs-12 col-md-12">
            <h2><spring:message code="login.title"/></h2>
            <form id="login-form" class="login-page" action="<c:url value='/j_spring_security_check'/>" method="POST">
                <div class="form-group">
                    <label><spring:message code="login.label.email"/> <span id="eMailError" class="red-font"></span></label>
                    <input type="email" name="j_username" id="j_username" value="" class="form-control input" placeholder="<spring:message code="common.input.email.placeholder"/>">
                </div>
                <div class="form-group">
                    <label><spring:message code="login.label.password"/> <span id="passwordError" class="red-font"></span></label>
                    <input type="password" name="j_password" id="j_password"  class="form-control input"  placeholder="<spring:message code="login.password.placeholder"/>">
                </div>
                <div class="checkbox">
                    <a href="#" class="forgotpassword pull-right" data-toggle="modal" data-target="#passwordForgotModal"><spring:message code="login.forgotpassword"/></a>
                </div>
                <br>
                <div class="form-group">
                    <button class="btn btn-primary btn-lg pull-right"><spring:message code="login.submit"/></button>
                </div>
                <div class="form-group">
                    <span><spring:message code="login.registration.text"/> <a href="/registration" class="forgotpassword"><spring:message code="login.registration.link"/></a></span>
                </div>
            </form>
        </div>
    </div>

Any help would be nice. Thanks a lot.

回答1:

Probably the problem is that starting from Spring Security version 4.+ parameters names for form login changed their names:

  • username instead of j_username
  • password instead of j_password
  • POST to /login URL instead of /j_spring_security_check

So you should either rename parameters in your login form or override these parameters name using form-login parameters like this:

<form-login login-page="/login"
                    username-parameter="j_username" 
                    password-parameter="j_password" 
                    login-processing-url="/j_spring_security_check" 
                    ..../>

Please take a look at this resourse, it might be helpful for your migration - http://docs.spring.io/spring-security/site/migrate/current/3-to-4/html5/migrate-3-to-4-xml.html#m3to4-xmlnamespace-form-login



回答2:

In your securityApplicationContext.xml add username-parameter="j_username" password-parameter="j_password" as below:

<security:form-login username-parameter="j_username" password-parameter="j_password" login-page="/login" login-processing-url="/j_spring_security_check" default-target-url="/dashboard" always-use-default-target="false" authentication-failure-url="/denied" />