1. Shiro is an open source project under Apache, which we call Apache Shiro. It is a very easy-to-use security framework for Java-key purposes, providing authentication, authorization, encryption, session management, and, like Spring security, a secure framework for permissions, but compared to spring security, Shiro Use a more straightforward and easy-to-use licensing approach. Shiro is a lightweight framework that is much simpler and less complex than security. So here I also briefly introduce the use of Shiro.
2, very simple, its basic function point as shown:
Authentication : identity Authentication/login, verify that the user has the corresponding identity;
Authorization : authorization, which is authentication of permissions, verifies that a authenticated user has a permission, that is, whether a user can do something, as usual: Verifying that a user has a role. or fine-grained verification that a user has a certain permission on a resource;
Session Manager : session 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 it can be a web environment;
Cryptography : encryption, protection of data security, such as password encryption stored in the database, rather than plaintext storage;
Web Support : Web support, can be very easy to integrate into the web environment;
Caching: Cache, such as user login, its user information, the role/permissions do not need to check every time, this can improve efficiency;
Concurrency :Shiro supports concurrent authentication for multi-threaded applications, such as opening another thread in one thread to automatically propagate the past;
Testing : provide testing support;
Run as : allows one user to pretend to access the identity of another user (if they allow it);
Remember Me : Remember me, this is a very common feature, that is, once logged in, the next time you come back without logging in.
Remember one thing, Shiro. do not maintain the user, maintenance rights, these need we to design/ and then injected to the Shiro via the appropriate interface . can be.
3, here I will briefly introduce springboot and Shiro integration and basic use.
1) directory Structure
2) required Base package: Pom.xml
<?xml version= "1.0" encoding= "UTF-8"? ><project xmlns= "http://maven.apache.org/POM/4.0.0" xmlns:xsi= "http: Www.w3.org/2001/XMLSchema-instance "xsi:schemalocation=" http://maven.apache.org/POM/4.0.0/http Maven.apache.org/xsd/maven-4.0.0.xsd "> <modelVersion>4.0.0</modelVersion> <groupid>com.troy </groupId> <artifactId>springshiro</artifactId> <version>1.0-SNAPSHOT</version> < ;p arent> <groupId>org.springframework.boot</groupId> <artifactid>spring-boot-starter-pa rent</artifactid> <version>1.5.6.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <ARTIFACTID>SPR Ing-boot-starter-web</artifactid> <version>1.5.6.RELEASE</version> </dependency> <dependency> <gRoupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-data-jpa</artifacti d> <version>1.5.6.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactid>spring-boot-autoconfigure</art ifactid> <version>1.5.6.RELEASE</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-Java</artifactId> <version>5.1.9</version> </dependency> <dependency> <groupid>o Rg.apache.shiro</groupid> <artifactId>shiro-spring</artifactId> <version>1.3 .2</version> </dependency> <dependency> <groupid>com.alibaba</groupid& Gt <artifactid>druid</artifactid> <version>1.1.4</version> </dependency> </depen Dencies></project>
3) Basic Configuration Application.yml
Server: port:8082spring: datasource: driver-class-name:com.mysql.jdbc.driver url:jdbc:mysql:// Localhost:3306/spring_shiro?useunicode=true&characterencoding=utf-8 username:root Password: Root type:com.alibaba.druid.pool.DruidDataSource JPA: show-sql:true hibernate: Ddl-auto : Update http: encoding: charset:utf-8 enabled:true
4) Here we basically need 3 entities, users, roles and permissions
(1) Role: User.class
@Entitypublic class User { @Id @GeneratedValue (strategy = generationtype.auto) private Long Id; @Column (unique = true) private String name; private Integer password; @OneToMany (cascade = Cascadetype.all,mappedby = "user") private list<role> roles; Public Long getId () { return ID; } public void SetId (Long id) { this.id = ID; } Public String GetName () { return name; } public void SetName (String name) { this.name = name; } Public list<role> GetRoles () { return roles; } public void Setroles (list<role> roles) { this.roles = roles; } Public Integer GetPassword () { return password; } public void SetPassword (Integer password) { this.password = password; }}
Note: Here I only consider a user to multiple roles, regardless of the many-to-many relationship
(2) Role: Role.class
@Entitypublic class Role { @Id @GeneratedValue (strategy = generationtype.auto) private Long Id; Private String roleName; @ManyToOne (fetch = Fetchtype.eager) private user user; @OneToMany (cascade = Cascadetype.all,mappedby = "role") private list<permission> permissions; Public Long getId () { return ID; } public void SetId (Long id) { this.id = ID; } Public String Getrolename () { return roleName; } public void Setrolename (String roleName) { this.rolename = roleName; } Public User GetUser () { return user; } public void SetUser (user user) { this.user = user; } Public list<permission> getPermissions () { return permissions; } public void SetPermissions (list<permission> permissions) { this.permissions = permissions; }}
(3) Permission: Permission.class
@Entitypublic class Permission { @Id @GeneratedValue (strategy = generationtype.auto) private Long Id; Private String permission; @ManyToOne (fetch = Fetchtype.eager) private role role; Public Long getId () { return ID; } public void SetId (Long id) { this.id = ID; } Public String getpermission () { return permission; } public void SetPermission (String permission) { this.permission = permission; } Public role Getrole () { return role; } public void Setrole (role role) { this.role = role; }}
5) Then the configuration of the corresponding validation, and filter conditions
(1) authentication, and the addition of permissions Myshirorealm.class
Implement Authorizingrealm Interface user authentication public class Myshirorealm extends authorizingrealm{//for user queries @Autowired private Ilogi Nservice Loginservice; Role permissions and corresponding permissions add @Override protected Authorizationinfo dogetauthorizationinfo (principalcollection principalcollection) {//Get login user name string name= (String) Principalcollection.getprimaryprincipal (); Query user name username user = Loginservice.findbyname (name); Add roles and Permissions Simpleauthorizationinfo simpleauthorizationinfo = new Simpleauthorizationinfo (); for (role Role:user.getRoles ()) {//Add role Simpleauthorizationinfo.addrole (Role.getrolename ()); For (Permission permission:role.getPermissions ()) {//Add permission Simpleauthorizationinfo.add Stringpermission (Permission.getpermission ()); }} return simpleauthorizationinfo; }//user authentication @Override protected authenticationinfo dogetauthenticationinfo (Authenticationtoken authentIcationtoken) throws Authenticationexception {//Plus this step is intended to be an advanced authentication at the time of the post request, and then on to the request if (AUTHENTICATIONTOKEN.GETP Rincipal () = = null) {return null; }//Get user information String name = Authenticationtoken.getprincipal (). toString (); User user = Loginservice.findbyname (name); if (user = = null) {//returns a corresponding exception after this return null; } else {//Here Verify the information of Authenticationtoken and Simpleauthenticationinfo Simpleauthenticationinfo simpleauthen Ticationinfo = new Simpleauthenticationinfo (name, User.getpassword (). toString (), GetName ()); return simpleauthenticationinfo; } }}
(2) Filter configuration: Shiroconfiguration.class
@Configurationpublic class Shiroconfiguration {//Add your own authentication method to the container @Bean public Myshirorealm Myshirorealm () { Myshirorealm Myshirorealm = new Myshirorealm (); return Myshirorealm; }//Rights Management, configuration is mainly realm management certification @Bean public SecurityManager SecurityManager () {Defaultwebsecuritymanager Securi Tymanager = new Defaultwebsecuritymanager (); Securitymanager.setrealm (Myshirorealm ()); return SecurityManager; }//filter factory, set the corresponding filter conditions and jump conditions @Bean public Shirofilterfactorybean Shirofilterfactorybean (SecurityManager securityma Nager) {Shirofilterfactorybean Shirofilterfactorybean = new Shirofilterfactorybean (); Shirofilterfactorybean.setsecuritymanager (SecurityManager); map<string,string> map = new hashmap<string, string> (); Logout Map.put ("/logout", "logout"); For all user authentication Map.put ("/**", "authc"); Login Shirofilterfactorybean.setloginurl ("/login"); Home ShirofilterFactorybean.setsuccessurl ("/index"); Error page, authentication does not pass jump Shirofilterfactorybean.setunauthorizedurl ("/error"); Shirofilterfactorybean.setfilterchaindefinitionmap (map); return Shirofilterfactorybean; }//Add annotations to use, do not add this annotation does not take effect @Bean public authorizationattributesourceadvisor authorizationattributesourceadvisor (secur Itymanager SecurityManager) {authorizationattributesourceadvisor authorizationattributesourceadvisor = new Authori Zationattributesourceadvisor (); Authorizationattributesourceadvisor.setsecuritymanager (SecurityManager); return authorizationattributesourceadvisor; }}
6) Next is the data access layer, the business layer, and the control layer
(1) Data layer: Baserepository.class,userrepository.class,rolerepository.class
@NoRepositoryBeanpublic interface Baserepository<t,i extends serializable> extends Pagingandsortingrepository <t,i>,jpaspecificationexecutor<t>{}
Public interface Userrepository extends baserepository<user,long>{ User findbyname (String name);
Public interface Rolerepository extends baserepository<role,long> {}
(2) Business layer: Loginserviceimpl.class
@Service @transactionalpublic class Loginserviceimpl implements Iloginservice {@Autowired private userrepository use Rrepository; @Autowired private Rolerepository rolerepository; Add user @Override Public user addUser (map<string, object> Map) {User user = new user (); User.setname (Map.get ("username"). toString ()); User.setpassword (Integer.valueof (Map.get ("password"). ToString ())); Userrepository.save (user); return user; }//Add role @Override Public role Addrole (map<string, object> Map) {User user = Userrepository.findone (Long.valueof (Map.get ("UserId"). ToString ())); Role role = new role (); Role.setrolename (Map.get ("RoleName"). toString ()); Role.setuser (user); Permission permission1 = new Permission (); Permission1.setpermission ("create"); Permission1.setrole (role); Permission permission2 = new Permission (); Permission2.setpermission ("Update"); PerMission2.setrole (role); list<permission> permissions = new arraylist<permission> (); Permissions.add (Permission1); Permissions.add (Permission2); Role.setpermissions (permissions); Rolerepository.save (role); return role; }//query user @Override Public user findbyname (String name) {return Userrepository.findbyname (name) via username; }}
(3) control layer: Loginresource.class
@RestControllerpublic class Loginresource {@Autowired private iloginservice loginservice; Exit is a GET request, mostly used to exit @RequestMapping (value = "/login", method = requestmethod.get) public String login () {RET Urn "login"; }//post Login @RequestMapping (value = "/login", method = requestmethod.post) public String login (@RequestBody map map {//Add user authentication information Subject Subject = Securityutils.getsubject (); Usernamepasswordtoken Usernamepasswordtoken = new Usernamepasswordtoken (Map.get ("username"). toString (), Map.get ("password"). toString ()); To verify that the exception can be caught here, and then return the corresponding information subject.login (Usernamepasswordtoken); return "Login"; } @RequestMapping (value = "/index") public String Index () {return ' index '; }//Logout @RequestMapping (value = "/logout") public String logout () {return "logout"; }//Error page showing @RequestMapping (value = "/error", method = requestmethod.post) public String Error () {return "error ok!"; }//Data initialization @RequestMapping (value = "/adduser") public String addUser (@RequestBody map<string,object> Map) { User user = Loginservice.adduser (map); Return "AddUser is ok! \ n "+ user; }//Role initialization @RequestMapping (value = "/addrole") public String addrole (@RequestBody map<string,object> Map) { Role role = Loginservice.addrole (map); Return "Addrole is ok! \ n "+ role; }//annotations are used @RequiresRoles ("admin") @RequiresPermissions ("Create") @RequestMapping (value = "/create") public String Create () {return ' Create success! '; }}
Note: The use of annotations here is very important in the last one!
7) The use of Shiro is basically like this, mainly the control of the Authority, the other main is to do jump and switch use
8) finally with database information: Combined with the control layer to watch
User
Role
Permission
This article is reproduced from
The original small treasure not good
Original link: https://www.cnblogs.com/ll409546297/p/7815409.html
Spring Boot uses Shiro for login authorization authentication