My initial understanding of Shiro

Source: Internet
Author: User

 PackageCom.shiro;Importorg.apache.shiro.SecurityUtils;ImportOrg.apache.shiro.authc.*;Importorg.apache.shiro.config.IniSecurityManagerFactory;ImportOrg.apache.shiro.mgt.SecurityManager;Importorg.apache.shiro.session.Session;Importorg.apache.shiro.subject.PrincipalCollection;ImportOrg.apache.shiro.subject.Subject;Importorg.apache.shiro.util.Factory;ImportOrg.slf4j.Logger;Importorg.slf4j.LoggerFactory;/** * @since0.9 RC2*/ Public classHelloshiro {Private Static Final transientLogger log = Loggerfactory.getlogger (Helloshiro.class);  Public Static voidMain (string[] args) {//Create one of the simplest ways to configure Shiro SecurityManager//servers, users, roles, and permissions are using a simple INI configuration. //we will do it by using a factory that can ingest. INI file and//returns a SecurityManager instance://use Shiro. INI file at the root of the classpath//(file: and URL prefix payload from file and URL respectively)://1 Get a Shiro factory class based on the configuration fileFactory<securitymanager> Factory =NewInisecuritymanagerfactory ("Classpath:shiro.ini"); //2 Obtaining the Shiro Security manager in the factory classSecurityManager SecurityManager =factory.getinstance (); //3 Put the SecurityManager into the securityutilsSecurityutils.setsecuritymanager (SecurityManager); //4 using Securityutils to get the currently logged on userSubject CurrentUser =Securityutils.getsubject (); //5 Getting the current user's session state Shiro built -in sessionsSession session =currentuser.getsession (); //you can put some attributes into the session and then handle it according to your own business logic.Session.setattribute ("Somekey", "Avalue"); String value= (String) session.getattribute ("Somekey"); if(Value.equals ("Avalue") {log.info ("Retrieved the correct value! ["+ Value +"] "); }        //6 Determine if the current user has authenticated        if(!currentuser.isauthenticated ()) {System.out.println ("Current user is not logged in---->"); //7 Impersonation Create a login tokenUsernamepasswordtoken token =NewUsernamepasswordtoken ("Lonestarr", "Vespa"); Token.setrememberme (true); Try {                //8 Sign-in Operation//Login Process//Currentuser.login (token);---> Call the Securitymanager.login (this, token) method//The login method of the---securitymanager first invokes the Authenticatingsecuritymanager authenticate (Authenticationtoken token) method /c4>//---Then the Authenticate method of Authenticatingsecuritymanager calls the doauthenticate of Modularrealmauthenticator ( Authenticationtoken Authenticationtoken)//---Then modularrealmauthenticator the DoAuthenticate method to get the config file of realm, if the profile does not define realm, the default is to use Simpleaccountrealm 
    //--If the configuration file is configured with multiple realms, traverse these realms and call the Getauthenticationinfo method in realm to get AuthenticationInfo (authentication information) to verify the current logged in user //---from the above process description, we can achieve a custom authentication method by customizing multiple realms and then overriding the Getauthenticationinfo methodCurrentuser.login (token); //principal because it is an object type, we can extend this class ourselves in real business.System.out.println ("User is logged in----> Username:" +Currentuser.getprincipal (). toString ()); } Catch(unknownaccountexception UAE) {log.info ("There is no user with username of" +Token.getprincipal ()); } Catch(Incorrectcredentialsexception ice) {Log.info ("Password for Account" + token.getprincipal () + "was incorrect!"); } Catch(Lockedaccountexception Lae) {Log.info ("The account for username" + token.getprincipal () + "is locked. "+" your administrator to unlock it. "); }            Catch(Authenticationexception ae) {}}//9 Determine the role of the currently logged on user---//as can be seen from the source code, Currentuser.hasrole ("Schwartz")---Call the method of Securitymanager.hasrole (Getprincipals (), Roleidentifier) //then called the Authorizingrealm hasrole (principalcollection principal, String Roleidentifier) method,//Authorizingrealm's Hasrole method uses Getavailableauthorizationcache () to get authorizationinfo in the cache first, If there is no authorizationinfo in the cache//The default subclass Simpleaccountrealm Gets the Dogetauthorizationinfo method Authorizationinfo (authorization information), and the subclass Simpleaccountrealm is Factory.getinstance (), when you put the user and the role in a map,//That means we can implement our custom authentication authorization information by customizing the Authorizingrealm and then overriding the Dogetauthorizationinfo method        if(Currentuser.hasrole ("Schwartz") {log.info ("May the Schwartz is with you!"); } Else{log.info ("Hello, mere mortal."); }        //test a typed permission (not instance-level)//10 Permission Validation//from the source code it can be seen that currentuser.ispermitted ("Lightsaber:weild")---called securitymanager.ispermitted (getprincipals (), permission),//----then called Authorizingrealm's ispermitted (principalcollection principals, String permission), This method gets the default Permissionresolver, which is the parser for the permission character//the---then called Authorizingrealm. Getauthorizationinfo (), first gets the authorizationinfo in the cache, if not, then from the Simpleaccountrealm of the subclass Dogetauthorizationinfo to get authorizationinfo.//----That is, we can use the Authorizingrealm class and then implement the Dogetauthenticationinfo method to implement the authorization validation of our own business logic        if(Currentuser.ispermitted ("Lightsaber:weild") {log.info ("You could use a lightsaber ring." Use it wisely. "); } Else{log.info ("Sorry, lightsaber rings is for Schwartz Masters only."); }        //A (very powerful) Instance level permission:        if(Currentuser.ispermitted ("Winnebago:drive:eagle5") {log.info ("You're permitted to ' drive ', the Winnebago with license plate (ID) ' Eagle5 '. "+" Here is the Keys-have fun! "); } Else{log.info ("Sorry, aren ' t allowed to drive the ' eagle5 ' winnebago!"); }        //All done-log out!currentuser.logout (); System.exit (0); }}

My initial understanding of Shiro

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.