Apache Shiro practice

Source: Internet
Author: User

Because Shiro is used by the company, I took the time to write a small example for further reference:

1. This is the project architecture diagram (the actual content of the class will be posted later ):

2. Data Structure Description:

User: user, including username and password

Role: Role, including rolename

Permission: permission, including premissionname

Securityservice is a data access interface. The implementation class content is as follows:

 

package org.pan.service.impl;import org.pan.bean.Permission;import org.pan.bean.Role;import org.pan.bean.User;import org.pan.service.SecurityService;import java.util.HashSet;import java.util.Set;/** * Created by panmingzhi on 2014/6/25. */public class SecurityServiceImpl implements SecurityService {    @Override    public Set<Permission> findPermissionsByRoleName(String roleName) {        HashSet<Permission> result = new HashSet<Permission>();        if(roleName.equals("admin")){            result.add(new Permission("carpark:*"));        }        if(roleName.equals("manager")){            result.add(new Permission("carpark:view"));        }        return result;    }    @Override    public Set<Role> findRoleByUserName(String userName) {        if(userName.equals("pan")){            HashSet<Role> roles = new HashSet<Role>();            roles.add(new Role("admin"));            return roles;        }        if(userName.equals("fang")){            HashSet<Role> roles = new HashSet<Role>();            roles.add(new Role("manager"));            return roles;        }        return new HashSet<Role>();    }    @Override    public User findUserByUserName(String username) {        if(username.equals("pan")){            return new User("pan","1234");        }        if(username.equals("fang")){            return new User("fang","1234");        }        return null;    }}

3. Implement myrealm. class through Shiro final permission Control

Import Org. apache. shiro. authc. *; import Org. apache. shiro. authz. authorizationinfo; import Org. apache. shiro. authz. simpleauthorizationinfo; import Org. apache. shiro. realm. authorizingrealm; import Org. apache. shiro. subject. principalcollection; import Org. pan. bean. permission; import Org. pan. bean. role; import Org. pan. bean. user; import Org. pan. service. securityservice; import Org. pan. service. impl. securityserviceimpl; Import Java. util. iterator; import Java. util. set;/*** created by panmingzhi on 2014/6/24. */public class myrealm extends {private securityservice = new securityserviceimpl (); @ override protected authorizationinfo extract (principalcollection) {simpleauthorizationinfo sai = new simpleauthorizationinfo (); string username = (string) P Rincipalcollection. fromrealm (getname ()). iterator (). next (); // find the set <role> roleset = securityservice. findrolebyusername (username); iterator <role> iterator = roleset. iterator (); While (iterator. hasnext () {role = iterator. next (); Sai. addrole (role. getrolename (); // set <permission> permissionsbyrolename = securityservice. findpermissionsbyrolename (role. getrolename (); iterator <permiss Ion> permissioniterator = permissionsbyrolename. iterator (); While (permissioniterator. hasnext () {Sai. addstringpermission (permissioniterator. next (). getpremissionname () ;}} return sai ;}@ override protected authenticationinfo dogetauthenticationinfo (authenticationtoken) throws authenticationexception {token = (token) authenticationtoken; u Ser user = securityservice. finduserbyusername (token. GetUserName (); If (user! = NULL) {return New simpleauthenticationinfo (user. GetUserName (), user. GetPassword (), getname () ;}else {return NULL ;}}}


4. function test shirotest. Class

Import Org. apache. shiro. securityutils; import Org. apache. shiro. authc. incorrectcredentialsexception; import Org. apache. shiro. authc. usernamepasswordtoken; import Org. apache. shiro. mgt. defaultsecuritymanager; import Org. JUnit. assert; import Org. JUnit. beforeclass; import Org. JUnit. test;/*** created by panmingzhi on 2014/6/25. */public class shirotest {@ beforeclass public static void before () {defasecursecuritymanager defaultsecuritymanager = new defaultsecuritymanager (New myrealm (); securityutils. setsecuritymanager (defasecursecuritymanager);} @ test public void logintestsuccess () {usernamepasswordtoken upt = new usernamepasswordtoken ("pan", "1234"); securityutils. getsubject (). login (upt) ;}@ test (expected = incorrectcredentialsexception. class) Public void logintestfaile () {usernamepasswordtoken upt = new usernamepasswordtoken ("pan", "12345"); securityutils. getsubject (). login (upt) ;}@ test public void premissiontest () {// The Administrator logs on to usernamepasswordtoken upt = new usernamepasswordtoken ("pan", "1234"); securityutils. getsubject (). login (upt); // indicates whether the log has an administrator role, Boolean admin = securityutils. getsubject (). hasrole ("admin"); assert. assertequals (true, admin); // determines whether there is a normal administrator role Boolean manager = securityutils. getsubject (). hasrole ("manager"); assert. assertequals (false, manager); // premission: carpark. * Indicates all permissions in the parking lot. // determines whether the parking lot has the permission to modify Boolean permitted = securityutils. getsubject (). ispermitted ("carpark: edit"); assert. assertequals (true, permitted); // you can check whether a parking lot is available. boolean permitted2 = securityutils. getsubject (). ispermitted ("carpark: View"); assert. assertequals (true, permitted2) ;}@ test public void premissiontest2 () {// The Administrator logs on to usernamepasswordtoken upt = new usernamepasswordtoken ("fang", "1234"); securityutils. getsubject (). login (upt); // indicates whether the log has an administrator role, Boolean admin = securityutils. getsubject (). hasrole ("admin"); assert. assertequals (false, admin); // determines whether there is a normal administrator role Boolean manager = securityutils. getsubject (). hasrole ("manager"); assert. assertequals (true, manager); // determines whether the permission to modify a parking lot is Boolean permitted = securityutils. getsubject (). ispermitted ("carpark: edit"); assert. assertequals (false, permitted); // you can check whether a parking lot is available. boolean permitted2 = securityutils. getsubject (). ispermitted ("carpark: View"); assert. assertequals (true, permitted2 );}}

In actual projects, I usually like to use the annotations provided by Shiro to determine roles and permissions, which can separate permission control from business code.
Project Source: https://github.com/panmingzhi815/shiro.git

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.