SpringBoot two ways to integrate Shiro

Transfer Song Ge: https://www.cnblogs.com/lenve/p/12321204.html

   Three core components: Subject, SecurityManager and Realms.

Subject : namely, "The current user." However, in Shiro, Subject of this concept is not only a person, it can be a third-party process, the background accounts (Daemon Account) or other similar things. It simply means "the current interactive software with something." But considering the purpose and use most, you can think of it as Shiro "user" concept.
  Subject represents the current user's security operation, SecurityManager manage all users of the security operation.

  subject.hasRole ( ""); determine whether there is role

  subject.hasRoles (List); determining whether each user has the contents of each List

  subject.hasAllRoles (); return boolean, requirement parameter requires that all users have roles

  subject.isPermitted ( ""); judging whether the permissions

  Code demonstrates https://www.cnblogs.com/xiaozhang666/p/12040122.html

The SecurityManager : It is the core framework of Shiro, a typical Facade pattern, Shiro to manage the internal component instance by SecurityManager, and through it to provide a variety of services security management.
Realm : Realm to implement authentication (authentication) and / or authorization (authorization) such as login authentication, authorization, login query is successful , Realm act as a "bridge" or "connector" between Shiro and application security data. That is, when a user performs an authentication (login) and authorization (access control) verification, Shiro looks for information from users and their privileges in the application configuration Realm, (see detailed understanding of the code: Realm-> SecurityManager-> ShiroFilterFactoryBean- > Subject)

After a successful authorization control who can log on inquiry what resources (such as page visits / edit data / page operation, etc.) access. In the authorization need to understand a few key objects: main (Subject), resources (Resource), permission (Permission), role (Role)

String Wildcard permissions

Rules: "Resource Identifier: Action: object instance ID" that is, the resources of which instance of which may be what to do. The default wildcard permissions string ":" indicates the division of resources / operations / instance; "" indicates the segment operations; "*" indicates that any resource / operation / examples.

1, the individual resources of a single authority

subject().checkPermissions("system:user:update");

Users have the resources "system: user" of the "update" permissions.

2, a single resource more rights

role41=system:user:update,system:user:delete

Then the code is determined by the following

subject().checkPermissions("system:user:update", "system:user:delete");

Users have the resources "system: user" of the "update" and "delete" permissions.

As can be abbreviated to: ini configuration (role role42 has expressed system: user resource update and delete permissions)

role42="system:user:update,delete"

It may then be determined by the following code

subject().checkPermissions("system:user:update,delete");

By "system: user: update, delete" verification "system: user: update, system: user: delete" is no problem, but the contrary is the rule does not hold.

3, a single resource full access

ini arrangement

role51="system:user:create,update,delete,view"

Then the code is determined by the following

subject().checkPermissions("system:user:create,delete,update:view");

Users have the resources "system: user" of "create", "update", "delete" and "view" all authority. As can be abbreviated as:

ini profiles (5 represents the character has a system: all the permissions the user)

role52=system:user:*

It can also be abbreviated as (top recommended wording):

role53=system:user

Then the code is determined by the following

subject().checkPermissions("system:user:*");
subject().checkPermissions("system:user"); 

By "system: user: *" verification "system: user: create, delete, update: view" can be, but the reverse is not true.

4, full access to all resources

ini arrangement

role61=*:view

Then the code is determined by the following

subject().checkPermissions("user:view");

Users have all the resources of the "view" all authority. Assuming that permission judgment is "" system: user: view " , then you need to" role5 = : : View "write the job

5, instance-level permissions

  • A single instance of a single authority

ini arrangement

role71=user:view:1

You have permission to view an example of a user of resources.

Then the code is determined by the following

subject().checkPermissions("user:view:1");

  • Multiple instances of a single authority

ini arrangement

role72="user:update,delete:1"

Has update, delete permissions on a user's resource instance.

Then the code is determined by the following

subject().checkPermissions("user:delete,update:1"); subject().checkPermissions("user:update:1", "user:delete:1"); 
  • A single instance all rights

ini arrangement

role73=user:*:1

You have all the privileges of a user of the resource instance.

Then the code is determined by the following

subject().checkPermissions("user:update:1", "user:delete:1", "user:view:1");

  • All instances of a single authority

ini arrangement

role74=user:auth:*

You have all the privileges of a user of the resource instance.

Then the code is determined by the following

subject().checkPermissions("user:auth:1", "user:auth:2");

  • All instances of all rights

ini arrangement

role75=user:*:*

You have all the privileges of a user of the resource instance.

Then the code is determined by the following

subject().checkPermissions("user:view:1", "user:auth:2");

————————————————

To do in Spring Boot in rights management, in general, the mainstream program is Spring Security, but only from a technical point of view, can also be used Shiro.

Today, Song Ge will come and we talk about Spring Boot integration Shiro topic!

Generally, Spring Security to Shiro and compared as follows:

  1. Spring Security is a heavyweight security management framework; Shiro is a lightweight security management framework
  2. Spring Security concept complex, cumbersome configuration; Shiro concept is simple, easy configuration
  3. Spring Security is powerful; simple function Shiro
  4. ...

While Shiro simple function, but also to meet most business scenarios. Therefore, in the conventional SSM project, in general, it can be integrated Shiro.

In Spring Boot, because the Spring Boot official offers plenty of convenient out of the box Starter, of course, Spring Security provides the Starter, making it easier to use Spring Security in Spring Boot in, even just need to add a it can rely on to protect all interfaces, so, if it is Spring Boot project, usually selected Spring Security.

This is just a suggestion of combination, purely technically speaking, no matter how they are combined, are no problem.

Shiro integration in Spring Boot, there are two different scenarios:

  1. The first is intact, the SSM configuration Shiro integration with Java rewrite it.
  2. The second is to use a Starter Shiro official to configure, but this did not have much Starter configuration simplified.

Native integration

  • Create a project

Spring Boot create a project, you can rely only need to add the Web:

After the project is successfully created, adding Shiro related dependencies, complete pom.xml file dependencies are as follows:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-web</artifactId> <version>1.4.0</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>1.4.0</version> </dependency> </dependencies> 
  • Creating Realm

Next we define the core components from the Realm:

public class MyRealm extends AuthorizingRealm { @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {//授权? return null; } @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {//认证! String username = (String) token.getPrincipal(); if (!"javaboy".equals(username)) { throw new UnknownAccountException("账户不存在!"); } return new SimpleAuthenticationInfo(username, "123", getName()); } } 

In the Realm achieved in a simple operation can be certified, not licensed, authorized by the specific wording and SSM in Shiro same, do not repeat them. Here's certification indicates that the user name must be javaboy, user passwords must be 123 to meet such conditions, will be able to log in successfully!

  • Placed Shiro

Then carry on Shiro's configuration:

@Configuration
public class ShiroConfig { @Bean MyRealm myRealm() { return new MyRealm(); } @Bean SecurityManager securityManager() { DefaultWebSecurityManager manager = new DefaultWebSecurityManager(); manager.setRealm(myRealm()); return manager; } @Bean ShiroFilterFactoryBean shiroFilterFactoryBean() { ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean(); bean.setSecurityManager(securityManager()); bean.setLoginUrl("/login"); bean.setSuccessUrl("/index"); bean.setUnauthorizedUrl("/unauthorizedurl"); Map<String, String> map = new LinkedHashMap<>(); map.put("/doLogin", "anon"); map.put("/**", "authc"); bean.setFilterChainDefinitionMap(map); return bean; } } 

Configuring here on Shiro's main configuration 3 Bean:

  1. First, the need to provide an example of a Realm.
  2. We need to configure a SecurityManager, configuration Realm in the SecurityManager.
  3. Configuring a ShiroFilterFactoryBean, specify the path of the blocking rules ShiroFilterFactoryBean the like.
  4. Configuring login and test interfaces.

Wherein, ShiroFilterFactoryBean configuration slightly more configuration following meanings:

  • setSecurityManager display specified SecurityManager.
  • setLoginUrl represents the specified login page.
  • setSuccessUrl indicates that the specified login success page.
  • The next Map configure the path blocking rules, pay attention, be ordered.

These things are configured, the next configure the login Controller:

@RestController
public class LoginController { @PostMapping("/doLogin") public void doLogin(String username, String password) { Subject subject = SecurityUtils.getSubject(); try { subject.login(new UsernamePasswordToken(username, password)); System.out.println("登录成功!"); } catch (AuthenticationException e) { e.printStackTrace(); System.out.println("登录失败!"); } } @GetMapping("/hello") public String hello() { return "hello"; } @GetMapping("/login") public String login() { return "please login!"; } } 

When tested, the first visit / hello interfaces, due not logged in, it will automatically jump to the / login interfaces:

Then call / doLogin interface to complete the login:

Revisit / hello interfaces, you can successfully visit:

Use Shiro Starter

This is actually equivalent to the above configuration of the SSM to get the XML configuration Spring Boot with Java code re-write it again, except this way, we can directly use Starter Shiro official offer.

  • Create a project, and the same as above

Once created, added  shiro-spring-boot-web-starter , before this reliance can be replaced  shiro-web and  shiro-spring two dependencies, pom.xml file as follows:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring-boot-web-starter</artifactId> <version>1.4.0</version> </dependency> </dependencies> 
  • Creating Realm

Here and in front of the Realm, I will not repeat them.

  • Shiro basic configuration information

Next, the basic configuration information Shiro in application.properties in:

shiro.sessionManager.sessionIdCookieEnabled=true
shiro.sessionManager.sessionIdUrlRewritingEnabled=true
shiro.unauthorizedUrl=/unauthorizedurl
shiro.web.enabled=true
shiro.successUrl=/index
shiro.loginUrl=/login

Configuration explanation:

  1. The first line indicates whether to allow the sessionId put the cookie
  2. The second line indicates whether to allow the address bar in sessionId into Url
  3. When the third row represents unauthorized access to a page, the default path jump
  4. The fourth line will indicate on shiro
  5. The fifth line indicates a successful login page jump
  6. The sixth row represents the login page
  • Configuration ShiroConfig
@Configuration
public class ShiroConfig { @Bean MyRealm myRealm() { return new MyRealm(); } @Bean DefaultWebSecurityManager securityManager() { DefaultWebSecurityManager manager = new DefaultWebSecurityManager(); manager.setRealm(myRealm()); return manager; } @Bean ShiroFilterChainDefinition shiroFilterChainDefinition() { DefaultShiroFilterChainDefinition definition = new DefaultShiroFilterChainDefinition(); definition.addPathDefinition("/doLogin", "anon"); definition.addPathDefinition("/**", "authc"); return definition; } } 

Here configured more like the previous, but no longer the need ShiroFilterFactoryBean example, replaces it ShiroFilterChainDefinition, Shiro path defined herein matching rules.

After you have defined here, the next logon interface definitions and test methods and in front of the same, I will not go into details. You can refer to the above.

to sum up

This paper to introduce a Spring Boot Shiro integration in two ways, one is Java version of the traditional way, and the other is to use Shiro official of Starter, two ways, do not know if you have not learned it?

Guess you like

Origin www.cnblogs.com/Bkxk/p/12617078.html