Shiro series of Shiro+mysql for user authentication (authentication)

Source: Internet
Author: User

Most of the information on the web about Apache Shiro is an example of using the INI file as a simple configuration, rarely using a database to implement user authentication. I am also just beginning to contact Shiro, here to introduce an entry-level Shiro+mysql configuration method, this method is only a beginning, and not with the Web,spring,mybatis framework for integration, follow-up I will continue to share with you my learning process and experience.

Now we can start the things that's we really care about.

A user table is created in the database, and the fields can be very simple.

CREATE TABLE ' sec_user ' (  ' user_id ' int (ten) unsigned not NULL auto_increment,  ' user_name ' varchar () COLLATE UTF 8_bin default NULL,  ' password ' varchar ($) COLLATE utf8_bin default null,  ' created_time ' datetime DEFAULT NULL,  ' update_time ' timestamp NULL DEFAULT current_timestamp,  PRIMARY KEY (' user_id ')) Engine=innodb auto_increment=1 DEFAULT Charset=utf8 collate=utf8_bin

Insert a record in the table, user name: [email protected], password: Cmao

Create an INI file under the Resources directory, configure Shiro (subsequent files will move the contents of this file into an XML file). In this configuration file we want to set up a data source and use database query statements when authenticating users. The Jdbcrealm class that comes with Shiro is used here.

[main] Datasource=org.springframework.jdbc.datasource.drivermanagerdatasourcedatasource.driverclassname= Com.mysql.jdbc.driverdatasource.url=jdbc:mysql://127.0.0.1:3306/your_database_namedatasource.username=your_ usernamedatasource.password=your_passwordjdbcrealm= Org.apache.shiro.realm.jdbc.JdbcRealmjdbcRealm.permissionsLookupEnabled = True jdbcrealm.datasource=$  Datasourcejdbcrealm.authenticationquery = SELECT password from sec_user WHERE user_name =? Jdbcrealm.userrolesquery = Select Role_name from sec_role WHERE role_name =? jdbcrealm.permissionsquery = Select Permissio  N from sec_role_permissions WHERE role_name =? securitymanager.realms= $jdbcRealm 

After the configuration file is written, we can write a test method to verify that the user authentication function can be implemented.

Package Com.emerons.learning;import static Org.junit.assert.*;import Org.apache.shiro.securityutils;import Org.apache.shiro.authc.disabledaccountexception;import Org.apache.shiro.authc.excessiveattemptsexception;import Org.apache.shiro.authc.expiredcredentialsexception;import org.apache.shiro.authc.IncorrectCredentialsException; Import Org.apache.shiro.authc.lockedaccountexception;import org.apache.shiro.authc.UnknownAccountException; Import Org.apache.shiro.authc.usernamepasswordtoken;import org.apache.shiro.config.IniSecurityManagerFactory; Import Org.apache.shiro.mgt.securitymanager;import Org.apache.shiro.subject.subject;import Org.apache.shiro.util.factory;import Org.junit.after;import Org.junit.before;import Org.junit.Test;public class jdbcrealmtest {@Beforepublic void SetUp () throws Exception {} @Afterpublic void TearDown () throws Exception {} @Testpublic V OID Test () {//1. Get SecurityManager factory, where INI configuration file is used to initialize securitymanagerfactory<securitymanager> factory = new InisecuritymanagerFactory ("Classpath:shiro-jdbc-realm.ini");//2. Get the SecurityManager instance and bind to Securityutilssecuritymanager SM = Factory.getinstance (); Securityutils.setsecuritymanager (SM);//3. Get Subjectsubject Subject = Securityutils.getsubject ();//4. Create user login Credentials Usernamepasswordtoken token = new Usernamepasswordtoken ("[email protected]", "Chrismao");//5. Login, If the logon failure throws a different exception, try {Subject.login (token) According to the exception output failure reason,//6. Determine if the login is successful assertequals (true, subject.isauthenticated ()); SYSTEM.OUT.PRINTLN ("Login Successful!! ");//7. Log off user subject.logout ();} catch (Incorrectcredentialsexception e) {System.out.println ("Login password error. Password for Account "+ token.getprincipal () +" was incorrect. "); catch (Excessiveattemptsexception e) {System.out.println ("Too many login failures");} catch (Lockedaccountexception e) { SYSTEM.OUT.PRINTLN ("account has been locked. The account is username "+ token.getprincipal () +" was locked. "); catch (Disabledaccountexception e) {System.out.println ("account has been disabled.) The account is username "+ token.getprincipal () +" was disabled. "); catch (expiredcredEntialsexception e) {System.out.println ("account has expired. The account is username "+ token.getprincipal () +" was expired. "); catch (Unknownaccountexception e) {System.out.println ("account does not exist. There is no user with username of "+ token.getprincipal ());}}}

Run the test code to get the following output:

info:org.springframework.jdbc.datasource.drivermanagerdatasource-loaded JDBC Driver:com.mysql.jdbc.DriverINFO:  Org.apache.shiro.realm.authorizingrealm-no Cache or CacheManager properties has been set. Authorization Cache cannot be Obtained.info:org.apache.shiro.config.inisecuritymanagerfactory-realms has been explic itly set on the SecurityManager instance-auto-setting of realms would not occur.INFO:org.apache.shiro.session.mgt.Abstr actvalidatingsessionmanager-enabling Session Validation Scheduler ... Login Successful!!  Info:org.apache.shiro.realm.authorizingrealm-no Cache or CacheManager properties has been set. Authorization cache cannot be obtained. 

  we can see from the log that the program loaded the JDBC driver and explicitly specified realm, which indicates that our Shiro configuration file was successfully loaded. Finally see the output of the "login Success" description of the authentication function has been implemented. You can also try to modify the test code with the user name or password, you can see similar output in the console, indicating that the correct exception can also be thrown.

info:org.springframework.jdbc.datasource.drivermanagerdatasource-loaded JDBC Driver:com.mysql.jdbc.DriverINFO: Org.apache.shiro.realm.authorizingrealm-no Cache or CacheManager properties has been set.  Authorization Cache cannot be Obtained.info:org.apache.shiro.config.inisecuritymanagerfactory-realms has been explic itly set on the SecurityManager instance-auto-setting of realms would not occur. Incorrect login password. Password for account [e-mail protected] was incorrect.

At this point, the ability to implement user authentication (authentication) with Shiro + MySQL has been completed. On this basis, we can improve the implementation of role authorization (authroization), operation can (Permission) and other functions.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Shiro series of Shiro+mysql for user authentication (authentication)

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.