(ii) Shiro integration--"springboot and Shiro Integration"

Source: Internet
Author: User

2.1 Introduction of Shiro related dependencies

<dependency>              <groupId>commons-logging</groupId>              <artifactid>commons-logging </artifactId>              <version>1.1.3</version>          </dependency>          <dependency>              <groupId>org.apache.shiro</groupId>              <artifactId>shiro-core</artifactId>              <version>1.2.2</version>          </dependency>           <dependency>              <groupId> org.apache.shiro</groupid>              <artifactId>shiro-web</artifactId>              <version>1.2.2 </version>          </dependency>   

2.2 Customizing Realm 

@Component Public classUserrealmextendsauthorizingrealm{@AutowiredPrivateUserService UserService; /*** License *@paramPrincipals *@return     */@Overrideprotectedauthorizationinfo Dogetauthorizationinfo (principalcollection principals) {String username =(String) Principals.getprimaryprincipal (); Simpleauthorizationinfo Authorizationinfo=NewSimpleauthorizationinfo (); //querying the database for user-owned roles/permissionsauthorizationinfo.setroles (Userservice.findroles (username));        Authorizationinfo.setstringpermissions (userservice.findpermissions (username)); returnAuthorizationinfo; }        /*** Verification*/@Overrideprotectedauthenticationinfo Dogetauthenticationinfo (Authenticationtoken token)throwsauthenticationexception {String username=(String) Token.getprincipal (); User User=Userservice.findbyusername (username); if(User = =NULL){            Throw NewUnknownaccountexception ();//no account found .        }                if(Boolean.TRUE.equals (user.getlocked ())) {Throw NewLockedaccountexception ();//account is locked} simpleauthenticationinfo AuthenticationInfo=NewSimpleauthenticationinfo (User.getusername (), User.getpassword (), Byteso Urce. Util.bytes (User.getcredentialssalt ()),//Salt = Username+saltgetName ()); returnAuthenticationInfo; }}

2.3 Shiroconfig

@Configuration Public classShiroconfig {@Bean PublicShirofilterfactorybean shirofilter (SecurityManager securitymanager) {Shirofilterfactorybean shiroFilterFactory Bean=NewShirofilterfactorybean ();        Shirofilterfactorybean.setsecuritymanager (SecurityManager); //interceptors. Map<string,string> Filterchaindefinitionmap =NewLinkedhashmap<string,string>(); //Configure the exit filter, where the specific exit code Shiro has been implemented for USFilterchaindefinitionmap.put ("Logout", "logout");Filterchaindefinitionmap.put ("/user/login", "anon"); //authc: All URLs must be authenticated before they can be accessed; anon: all URLs can be accessed anonymouslyFilterchaindefinitionmap.put ("/user/**", "anon");
Filterchaindefinitionmap.put ("/test/**", "authc");
filterchaindefinitionmap.put ("/page/**", "authc"); // if not set default will automatically look for "/login.jsp" page under Web project root directory Shirofilterfactorybean.setloginurl ("/login.html");
Shirofilterfactorybean.setunauthorizedurl ("/page/fail.html");//not authorized to jump//Login Successful Jump link (this does not know how to use, I have to jump to achieve their own)Shirofilterfactorybean.setsuccessurl ("/page/main.html"); Shirofilterfactorybean.setfilterchaindefinitionmap (FILTERCHAINDEFINITIONMAP); returnShirofilterfactorybean; } /*** Voucher Match * Due to our password calibration to Shiro's simpleauthenticationinfo for processing *@return */@Bean PublicHashedcredentialsmatcher Hashedcredentialsmatcher () {hashedcredentialsmatcher Hashedcredentialsmatcher =NewHashedcredentialsmatcher (); Hashedcredentialsmatcher.sethashalgorithmname ("MD5");//hashing algorithm: The MD5 algorithm is used here; Hashedcredentialsmatcher.sethashiterations (2);//the number of hashes, such as hashing two times, is equivalent to MD5 (MD5 (""));  returnHashedcredentialsmatcher; } @Bean PublicUserrealm Myshirorealm () {Userrealm Myshirorealm=NewUserrealm ();
//Using encryption
Myshirorealm.setcredentialsmatcher (Hashedcredentialsmatcher ());
 returnMyshirorealm; } @Bean PublicSecurityManager SecurityManager () {Defaultwebsecuritymanager SecurityManager=NewDefaultwebsecuritymanager (); Securitymanager.setrealm (Myshirorealm ()); returnSecurityManager; } @Bean Publiclifecyclebeanpostprocessor lifecyclebeanpostprocessor () {return Newlifecyclebeanpostprocessor (); } /*** Register Global exception Handling *@return */@Bean (Name= "Exceptionhandler")  Publichandlerexceptionresolver Handlerexceptionresolver () {return NewExceptionhandler (); } }

2.4 Creating Usercontroller

@RestController @requestmapping ("/USER") Public classUsercontroller {@AutowiredPrivateUserService UserService; @RequestMapping ("/login")     PublicModelandview Login (User loginuser,servletrequest request) {Modelandview View=NewModelandview (); Subject Subject=Securityutils.getsubject (); Usernamepasswordtoken token=NewUsernamepasswordtoken (Loginuser.getusername (), Loginuser.getpassword ()); if(!subject.isauthenticated ())        {Subject.login (token); }//Gets the last request path Savedrequest savedrequest=webutils.getsavedrequest (Request); String URL= ""; if(Savedrequest! =NULL) {URL=Savedrequest.getrequesturl (); }Else{URL= "/page/main.html"; } view.setviewname ("Redirect:" +URL); returnview; } @RequestMapping ("/register")     Publicmodelandview Add (user user) {Modelandview view=NewModelandview ();        Userservice.createuser (user); View.setviewname ("Redirect:/login.html"); returnview; } @RequestMapping ("/logout")     PublicString Logout (User loginuser) {Subject Subject=Securityutils.getsubject ();        Subject.logout (); return"Logged Out"; }}

UserService

    @Override    public  Long createUser (user user) {        Passwordhelper.encryptpassword ( user);         return userdao.createuser (user);    }

Passwordhelper (encrypted, used when saving to the database)

    Private StaticRandomNumberGenerator RandomNumberGenerator =NewSecurerandomnumbergenerator (); //these are consistent with realm.    Private StaticString algorithmname = "MD5"; Private Final Static intHashiterations = 2; Static  Public  voidencryptpassword (user user) {//Add SaltUser.setsalt (Randomnumbergenerator.nextbytes (). Tohex ()); String NewPassword=NewSimplehash (Algorithmname, User.getpassword (), ByteSource.Util.bytes (User.getcredentialssalt ()),        hashiterations). Tohex ();    User.setpassword (NewPassword); }

Let's test it (the page code is not written here)

We first visited http://localhost:8080/page/main.html because all the files under the page directory set in Shiroconfig need to be carefully passed to access

Filterchaindefinitionmap.put ("/page/**", "authc");

This will jump to the login page

Register a user first

View Database

At this time, you can access the homepage by logging in.

Very simple one user authentication function, below we continue to improve

SOURCE Point here

(ii) Shiro integration--"springboot and Shiro Integration"

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.