Spring Security Username Password error return 401 page

Source: Internet
Author: User
Tags assert deprecated

Because to increase the enterprise number verification when landing, you define the Disusernamepasswordauthenticationfilter class and inherit the Abstractauthenticationprocessingfilter class, However, after running, it is found that if the user name password is wrong or other errors such as no permissions are returned to 401-authentication Failed, such as:

650) this.width=650; "Src=" https://s4.51cto.com/wyfs02/M01/A6/08/wKioL1nIVqnQ8_8eAAA6b8BlQiU984.png-wh_500x0-wm_ 3-wmp_4-s_2366503085.png "title=" _20170922173332.png "alt=" Wkiol1nivqnq8_8eaaa6b8blqiu984.png-wh_50 "/>

After the investigation and discovery, There is no path to the incoming logon failure jump When overriding the Abstractauthenticationprocessingfilter class Failureurl. After I found the problem, I found it in Abstractauthenticationprocessingfilter. The class defines the AU Thenticationsuccesshandler and Authenticationfailurehandler, so we can define the code in Application-security.xml:

<beans:bean id= "Simpleurlauthenticationfailurehandler" class= "org.springframework.security.web.authentication . Simpleurlauthenticationfai Lurehandler "> <!--can configure the appropriate jump mode. The property forwardtodestination is true with forward false to Sen Dredirect---<beans:property name= "Defaultfailur Eurl "value="/login.jsp?auth-failure=true "></b eans:property> </beans:bean>

and introduced in the custom Disusernamepasswordauthenticationfilter class

  <!--  Login Processing filter  -->      <beans:bean  Id= "Loginprocessfilter"  class= "com.fpi.safety.common.security.disusername         passwordauthenticationfilter ">           <beans:property name= "Companycode"  value= "Companycode"  />           <beans:property name= "Usernameparameter"  value= "username"  />            <beans:property  Name= "Passwordparameter"  value= "password"  />           <!--  Login failure handling class  -->        <beans:property  name= "Simpleurlauthenticationfailurehandler"  ref= "simpleurlauthen             ticationfailurehandler " />         <beans: Property name= "Authenticationsuccesshandler"  ref= "appsessionsuccesshandler          " />          <beans: Property name= "AuthenticationManager"  ref= "Disuserauthmanager"  />      </beans:bean>


Disusernamepasswordauthenticationfilter.java

public class disusernamepasswordauthenticationfilter extends  abstractauthenticationprocessingfilter  {    public static final  string spring_security_form_username_key =  "J_username";    public  static final string spring_security_form_password_key =  "J_password";     public static final String SPRING_SECURITY_FORM_COMPANY_CODE_KEY =  " Company_code ";     public static final string username_loginid_split  =  "-";         /**     * @ Deprecated if you want to retain the username, cache it in  a customized {@code  AuthenticationFailureHandler}     */      @Deprecated     public static final string spring_security_last_username_key =  "SPRING_SECURITY_LAST _username ";     private string usernameparameter = spring_security_form _username_key;    private string passwordparameter = spring_security_ Form_password_key;    private string companycode = spring_security_ form_company_code_key;    private simpleurlauthenticationfailurehandler  Simpleurlauthenticationfailurehandler;        private boolean  postonly = true;    //~ constructors =========================== ========================================================================    public  Disusernamepasswordauthenticationfilter ()  {        super ("/j_ Spring_security_check ");     }    //~ methods =============================================== =========================================================    public authentication  attemptauthentication (httpservletrequest request, httpservletresponse response)   throws authenticationexception {        if  (postOnly  && !request.getmethod (). Equals ("POST"))  {             throw new authenticationserviceexception ("Authentication method  not supported:  " + request.getmethod ());         }        string username = obtainusername (Request );         string password = obtainpassword (request);         string companycode = obtaincompanycode (Request);                 if  (Username == null)  {            username =  "";         }        if  (password  == null)  {            password  =  "";        }                 if (companycode == null | |  companycode.equals ("")) {        companycode =  "null";         }                username = username.trim ();        companycode =   Companycode.trim ();                 username = username+USERNAME_LOGINID_SPLIT+companyCode;         UsernamePasswordAuthenticationToken authRequest = new  Usernamepasswordauthenticationtoken (Username, password);         / / allow subclasses to set the  "Details"  property         setdetails (request, authrequest);         Return this.getauthenticationmanager (). Authenticate (Authrequest);    }         protected string obtaincompanycode (HttpServletRequest  Request) &NBSP;{&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBsp;return request.getparameter (Companycode);    }    /**      * enables subclasses to override the composition of  the password, such as by including additional values      * and a separator.<p>This might be used for  Example if a postcode/zipcode was required in addition to the      * password. A delimiter such as a pipe  ( |)  should be used to separate the password and extended  Value (s).  the     * <code>authenticationdao</code> will  need to generate the expected password in a corresponding  Manner.</p>     *     *  @param  request so that request  attributes can be retrieved     *     *  @return  the password that will be presented in the <code> authentication</code> request token to the     *          <code>AuthenticationManager</code>      */    protected string obtainpassword (HttpServletRequest  Request)  {        return request.getparameter ( Passwordparameter);    }    /**     *  enables subclasses to override the composition of the username,  Such as by including additional values     * and a separator.      *     *  @param  request so that request  attributes can be retrieved     *     *  @return  the username that will be presented in the <code> authentication</code> request token to the     *          <code>AuthenticationManager</code>      */    protected string obtainusername (HttpServletRequest  Request)  {        return request.getparameter ( Usernameparameter);    }    /**     *  Provided so that subclasses&nbSp;may configure what is put into the authentication request ' s  details     * property.     *      *  @param  request that an authentication request is being  created for     *  @param  authrequest the authentication  request object that should have its details set      */    protected void setdetails (Httpservletrequest request,  usernamepasswordauthenticationtoken authrequest)  {         authrequest.setdetails (Authenticationdetailssource.builddetails (Request));     }     /**     * Sets the parameter name  which will be used to obtain the username from the login request.      *     *  @param  usernameparameter the parameter name.  Defaults to  "J_username" .     */    public  Void setusernameparameter (String usernameparameter)  {         assert.hastext (usernameparameter,  "Username parameter must not be empty  or null ");        this.usernameparameter =  usernameparameter;    }    /**     *  Sets the parameter name which will be used to obtain the  password from the login request.      *     *  @param  passwordparameter the parameter name. defaults to  "J_password" .      */    public void setpasswordparameter (String passwordParameter )  {        assert.hastext (passwordparameter,  "Password  Parameter must not be empty or null ");         this.passwordParameter = passwordParameter;    }              @Override     public void  Afterpropertiesset ()  {    super.afterpropertiesset ();    /*           * the processor implements the  AuthenticationFailureHandler           * for handling login failure, jump interface            */ &nBsp;    this.setauthenticationfailurehandler (Simpleurlauthenticationfailurehandler);     }            /**      * defines whether only http post requests will be  allowed by this filter.     * if set to true ,  and an authentication request is received which is not a  post request, an exception will     * be raised  immediately and authentication will not be attempted. the <tt >unsuccessfulauthentication () </tt> method     * will be  called as if handling a failed authentication.     *  <p>     * defaults to <tt>true</tt> but may be  Overridden by subclasses.     */    public void  setpostonly (boolean postonly)  {        this.postonly  = postOnly;    }    public final String  Getusernameparameter ()  {        return usernameParameter;     }    public final string getpasswordparameter ()  {        return passwordparameter;    } Public string getcompanycode ()  {return companycode;} Public void setcompanycode (String companycode)  {this.companycode = companycode;} Public simpleurlauthenticationfailurehandler getsimpleurlAuthenticationfailurehandler ()  {return simpleurlauthenticationfailurehandler;} Public void setsimpleurlauthenticationfailurehandler (simpleurlauthenticationfailurehandler  Simpleurlauthenticationfailurehandler)  {this.simpleUrlAuthenticationFailureHandler =  Simpleurlauthenticationfailurehandler;}         }

This will enable the login error to successfully return to the landing page, the problem is resolved.

This article is from the "13085720" blog, please be sure to keep this source http://13095720.blog.51cto.com/13085720/1968316

Spring Security Username Password error return 401 page

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.