Shiro Basic Tutorials
Original address: Shiro Basic Tutorial
Blog Address: http://www.extlight.com
First, preface
Apache Shiro is a security framework for Java. Powerful, with a simple Java security framework, it provides developers with an intuitive and comprehensive solution for authentication, authorization, encryption, and session management. Second, Introduction 2.1 Features
The Shiro contains 10 content, as shown below:
1) Authentication: Identity authentication/Login, verify that the user has the appropriate identity.
2) Authorization: Authorization, which is authentication of permissions, verifies whether a authenticated user has a permission, that is, whether a user can do something, a common example: verifying that a user has a role. or fine-grained to verify that a user has a permission on a resource.
3) Session Manager: Conversation management, that is, after the user logs on is a session, before exiting, all its information is in the session, the session can be normal javase environment, or can be such as the WEB environment.
4) Cryptography: Encrypt, protect the security of the data, such as password encryption stored to the database, rather than plaintext storage.
5) Web Support:web support, can be easily integrated into the Web environment.
6) Caching: cache, such as user login, its user information, the role/permissions do not need to check every time, this can improve efficiency.
7) Concurrency:shiro supports concurrent authentication for multithreaded applications, such as opening another thread in one thread to automatically propagate the past.
8) Testing: Provide test support.
9) Run as: Allows one user to pretend to access the identity of another user (if they allow).
Remember me: Remember me, this is a very common feature, that is, once logged in, the next time you come back without logging in. 2.2 Operating principle
Shiro operating principle Figure 1 (Application angle) is as follows:
1) Subject: The subject, which represents the current "user". This user is not necessarily a specific person, anything that interacts with the current application is Subject, such as a web crawler, a robot, etc. All Subject are bound to SecurityManager, and all interactions with Subject are delegated to SecurityManager. We can think of Subject as a façade, SecurityManager is the actual performer.
2) SecurityManager: Security Manager. That is, all security-related operations interact with SecurityManager, and it manages all Subject. As you can see it is the core of Shiro, it is responsible for interacting with the other components described in the post, if you have learned SPRINGMVC, we can think of it as a dispatcherservlet front-end controller.
3) Realm: domain. Shiro obtain security data (such as users, roles, permissions) from the realm, that is, SecurityManager to verify the identity of the user, it needs to obtain the appropriate user from the realm to determine whether the user's identity is legitimate, also need to get the user's corresponding role from realm Permissions to verify that the user is able to operate. We can think of Realm as DataSource, or secure data source.
Shiro Operating principle Figure 2 (Shiro internal architecture angle) is as follows:
1) Subject: Subject, you can see that the subject can be any "user" interacting with the app.
2) SecurityManager: equivalent to Dispatcherservlet in Springmvc or Filterdispatcher in Struts2. It is the core of Shiro, and all specific interactions are controlled through SecurityManager. It manages all Subject, and is responsible for authentication and authorization, as well as session and cache management.
3) Authenticator: Authenticator, responsible for the main certification, this is an extension point, if the user feels Shiro default is not good, we can customize the implementation. It requires authentication policy (authentication strategy), that is, what happens when the user authentication is passed.
4) Authrizer: authorization, or access controller. It is used to determine whether the subject has permission to perform the corresponding operation, which controls what functions the user can access in the app.
5) Realm: There can be 1 or more realms that can be considered as security Entity data sources, that is, for obtaining security entities. It can be either a JDBC implementation or an LDAP implementation, or a memory implementation.
6) SessionManager: If you write a Servlet you should know the concept of the session, the session needs someone to manage its life cycle, this component is SessionManager. And Shiro can be used not only in the WEB environment, but also in the common javase environment.
7) Sessiondao:dao has been used by everyone, data access objects, CRUD for sessions. We can customize the implementation of the Sessiondao to control where the session is stored. such as writing to a database via JDBC or writing to Redis via Jedis. In addition, cache can be used in Sessiondao to improve performance.
8) CacheManager: Cache manager. It manages caches such as users, roles, permissions, and so on. Because these data are rarely changed, the performance of the access can be improved when placed in the cache.
9) Cryptography: Cipher module, Shiro improves some common cryptographic components for password encryption/decryption. 2.3 Filter
When Shiro is applied to a Web project, Shiro automatically creates some default filters to filter client requests. The following are the filters provided by Shiro:
filter abbreviation |
the corresponding Java class |
Anon |
Org.apache.shiro.web.filter.authc.AnonymousFilter |
Authc |
Org.apache.shiro.web.filter.authc.FormAuthenticationFilter |
Authcbasic |
Org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter |
Perms |
Org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter |
Port |
Org.apache.shiro.web.filter.authz.PortFilter |
Rest |
Org.apache.shiro.web.filter.authz.HttpMethodPermissionFilter |
Roles |
Org.apache.shiro.web.filter.authz.RolesAuthorizationFilter |
Ssl |
Org.apache.shiro.web.filter.authz.SslFilter |
User |
Org.apache.shiro.web.filter.authc.UserFilter |
Logout |
Org.apache.shiro.web.filter.authc.LogoutFilter |
Nosessioncreation |
Org.apache.shiro.web.filter.session.NoSessionCreationFilter |
Explain:
/admins/**=anon # Indicates that the URI can be accessed anonymously
/admins/**=auth # means that the URI requires authentication to access
/admins/**=authcbasic # indicates that the URI requires Httpbasic authentication
/admins/**=perms[user:add:*] # indicates that the URI requires the authenticated user to have user:add:* permission to access
/admins/**=port[8081 ] # indicates that the URI needs to use 8081 Port
/admins/**=rest[user] # equivalent to/admins/**=perms[user:method], where method represents get, Post, delete, etc.
/admins/**=roles[admin] # indicates that the URI requires the authentication user to have the Admin role to access
/admins/**=ssl # indicates that the URI needs to be used The HTTPS protocol
/admins/**=user # indicates that the URI requires authentication or can be accessed by remembering my authentication to access
/logout=logout # for logoff, as a fixed configuration
Attention:
Anon,authcbasic,auchc,user is a certified filter.
Perms,roles,ssl,rest,port is an authorization filter. iii. Basic Primer 3.1 Adding 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.4.0</version>
</dependency>
3.2 Configuration Files
Create a configuration file named Shiro.ini in the Src/main/resources directory with the following contents:
[Users]
# Admin=admin represents the account number and password, administrator indicates that the account in front of the comma has Administrator role.
admin=admin,administrator
zhangsan=zhangsan,manager
lisi=lisi,guest
[roles]
# Administrator represents the role name, * indicates that the role has all permissions
administrator=*
manager=user:*,department:*
guest=user:query, Department:query
Where each user can have more than one role, separated by commas. Each role can have multiple permissions, also separated by commas. 3.3 Encoding
public class Shirotest {@Test public void Test () {//Read Shiro.ini file contents Factory<securitymana
Ger> factory = new Inisecuritymanagerfactory ("Classpath:shiro.ini");
SecurityManager SecurityManager = Factory.getinstance ();
Securityutils.setsecuritymanager (SecurityManager);
Subject CurrentUser = Securityutils.getsubject ();
Session session = Currentuser.getsession ();
Session.setattribute ("Somekey", "avalue");
String value = (string) session.getattribute ("Somekey");
if (Value.equals ("Avalue")) {System.out.println ("Value of Somekey:" + value);
}//Login Usernamepasswordtoken token = new Usernamepasswordtoken ("Zhangsan", "Zhangsan");
Token.setrememberme (TRUE);
try {currentuser.login (token);
} catch (Unknownaccountexception UAE) {System.out.println ("User name does not exist:" + Token.getprincipal ()); } catch (Incorrectcredentialsexception ICE) {System.out.println ("account password" + token.getprincipal () + "Incorrect!");}
catch (Lockedaccountexception Lae) {System.out.println ("username" + token.getprincipal () + "Locked!");} After successful authentication if (currentuser.isauthenticated ()) {System.out.println ("user" + Currentuser.getprincipal () + "login successful.
");
Test the role System.out.println ("Have Manager role:" + currentuser.hasrole ("manager"));
Test Permissions System.out.println ("Have user:create permissions" + currentuser.ispermitted ("user:create"));
Exit Currentuser.logout (); }
}
}
Printing results:
Somekey value: Avalue
user Zhangsan login successful.
Whether you have the manager role: True
if you have User:create permissions true
In the backend code of the project, we can detect the authentication status and authorization information of the current logged-in user through the Subject object, the following is a list of methods related to Subject object authentication and authorization: