Shiro processing Simple authentication analysis and examples

Source: Internet
Author: User

In two days in see Shiro, open Tao Brother's tutorial or write more easy to read, almost looked at the day, ready to use.
May be thinking too simple, in the use of the time you do encounter some problems, take the simplest authentication to say it:
What needs to be explained is that here is the integration used in Spring , authentication I directly used the Shiro provided by the

Org.apache.shiro.web.filter.authc.FormAuthenticationFilter

If the URL has the interceptor applied, the process is roughly the same:

As a result of the flow chart before using markdown flowers, so it is changed into a picture form.

For example, if we want to use formauthenticationfilter to do a simple authentication, it is also very simple:

    1. First we write the GET request and the POST request to handle the login separately.
@RequestMapping (value ="/login", method = Requestmethod.GET) Public StringShowloginpage () {return"User/login"; } @RequestMapping (value ="/login", method = Requestmethod.post) Public StringSubmitloginform (user user, HttpServletRequestRequest, model model) {StringErrorclassname = (String)Request. getattribute ("Shirologinfailure");StringAuthticationerror =NULL;if(Unknownaccountexception.class. GetName (). Equals (Errorclassname)) {Authticationerror ="User name/Password error"; }Else if(Incorrectcredentialsexception.class. GetName (). Equals (Errorclassname)) {Authticationerror ="User name/Password error"; }Else if(Errorclassname! =NULL) {Authticationerror ="Unknown error:"+ Errorclassname; } model.addattribute ("Authticationerror", Authticationerror);    return Showloginpage (); }

In the POST request, we need to translate the message content that needs to be displayed according to the error message from request. If you need internationalization, you can also use ResourceBundle to do it.
It should be noted that only when the login error will come in this method. If authentication succeeds, it jumps directly to the previous access address or successfulurl. OK, next look at the configuration file:

    <!--voucher match This simply writes a no-encrypt match--    <bean id= "credentialsmatcher" class=" Com.zhu.prototype.shiro.credential.PlainPasswordMatcher ">    </Bean>    <bean id="Jdbcrealm" class="Org.apache.shiro.realm.jdbc.JdbcRealm ">        < property name="Credentialsmatcher" ref="Credentialsmatcher" ></Property >        < property name="Authenticationquery" value="Select Password from user where username =? " ></Property >        < property name="DataSource" ref="DataSource"></Property >    </Bean>    <!--security Manager Defaultwebsecuritymanager uses Servletcontainersessionmanager to manage session--> by default    <bean id= "SecurityManager" class=" Org.apache.shiro.web.mgt.DefaultWebSecurityManager ">        < property name="Realms">            <list>                <ref Bean="Jdbcrealm" />            </list>        </Property >    </Bean>    <!--authentication filters based on form forms- -    <bean id= "formauthenticationfilter"class=" Org.apache.shiro.web.filter.authc.FormAuthenticationFilter ">                < property name="Usernameparam" value="username" />         < property name="Passwordparam" value="password" / >        < property name="loginurl" value="/login" />        < property name="Successurl" value="/news/newslist"> </Property >    </Bean>

Once the login is successful, several properties are set by default in the session:

{org.apache.shiro.subject.support.defaultsubjectcontext_authenticated_session_key=true,
Org.apache.shiro.web.session.httpservletsession.host_session_key=0:0:0:0:0:0:0:1,
Org.apache.shiro.subject.support.defaultsubjectcontext_principals_session_key=zhu}

If we need to register attribute, my idea is to inherit formauthenticationfilter(do not know if Shiro has provided other configurations to complete?). ), and then rewrite onloginsuccess (...), which is defined as follows:

    protectedbooleanonLoginSuccess(AuthenticationToken token, Subject subject,                                     throws Exception {        issueSuccessRedirect(request, response);        //we handled the success redirect directly, prevent the chain from continuing:        returnfalse;    }

can be rewritten as

    protectedbooleanonLoginSuccess(AuthenticationToken token, Subject subject,                                     throws Exception {        issueSuccessRedirect(request, response);        //we handled the success redirect directly, prevent the chain from continuing:        initCustomSessionAttributes(request.getSession(false));        returnfalse;    }

Finally, we give the error that the common validation in Shiro does not pass the report:

    • Disabledaccountexception (Disabled account)
    • Lockedaccountexception (Locked account)
    • Unknownaccountexception (Wrong account)
    • Excessiveattemptsexception (excessive number of logon failures)
    • Incorrectcredentialsexception (Wrong voucher)
    • Expiredcredentialsexception (Expired voucher)
    • ......

Shiro processing Simple authentication analysis and examples

Related Article

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.