Two detailed methods of integrating Shiro with Spring Boot

In general, the mainstream solution for permission management in Spring Boot is Spring Security. However, Shiro can also be used only from a technical point of view.

Comparison between Spring Security and Shiro:

  • Spring Security is a heavyweight security management framework; Shiro is a lightweight security management framework
  • The concept of Spring Security is complex and configuration is tedious; Shiro is simple and configuration is simple
  • Spring Security is powerful; Shiro is simple

Although Shiro has simple functions, it can also meet most business scenarios. So in traditional SSM projects, generally speaking, Shiro can be integrated.

In Spring Boot, Spring Boot officially provides a large number of very convenient out of the box starters as well as Spring Security starters, which makes it easier to use Spring Security in Spring Boot. Even if only one dependency is added, all interfaces can be protected. Therefore, if it is a Spring Boot project, Spring Security is generally selected.

This is just a suggested combination. Technically speaking, no matter how it is combined, there is no problem.

There are two different schemes for integrating Shiro in Spring Boot:

The first is to rewrite the configuration of SSM integrated Shiro in Java.

The second is to use a Starter officially provided by Shiro to configure. However, this Starter does not simplify the configuration much.

Primary integration

Create project

To create a Spring Boot project, you only need to add Web dependency:

After the project is created successfully, Shiro related dependencies are added. The dependencies in the complete pom.xml file 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>

Create Realm

Next, let's define the core component, 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("Account does not exist!");
}
return new SimpleAuthenticationInfo(username, "123", getName());
}
}

It is enough to implement simple authentication operation in Realm without authorization. The specific writing method of authorization is the same as Shiro in SSM and will not be repeated. The authentication here means that the user name must be javaboy and the user password must be 123. If this condition is met, the login will succeed!

Configure Shiro

Next, configure Shiro:

@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;
}
}

Shiro is mainly configured with three beans:

  • First, you need to provide an instance of the Realm.
  • You need to configure a SecurityManager to configure Realm in the SecurityManager.
  • Configure a ShiroFilterFactoryBean, specify path interception rules in ShiroFilterFactoryBean, etc.
  • Configure login and test interfaces.

Among them, ShiroFilterFactoryBean has a little more configuration. The meaning of configuration is as follows:

  • setSecurityManager indicates the specified SecurityManager.
  • setLoginUrl indicates the specified login page.
  • setSuccessUrl indicates the specified login success page.
  • Next, the path interception rules are configured in the Map. Note that they should be orderly.

After all these things are configured, 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("Login successfully!");
} catch (AuthenticationException e) {
e.printStackTrace();
System.out.println("Login failed!");
}
}
@GetMapping("/hello")
public String hello() {
return "hello";
}
@GetMapping("/login")
public String login() {
return "please login!";
}
}

During the test, first access the / hello interface. Since it is not logged in, it will automatically jump to the / login interface:

Then the /doLogin interface is called to complete the login:

By accessing the / hello interface again, you can successfully access:

Using Shiro Starter

In fact, the above configuration method is equivalent to taking the XML configuration in SSM to Spring Boot and rewriting it with Java code. In addition to this method, we can also directly use the Starter officially provided by Shiro.

Create project as above

After the creation is successful, add Shiro spring boot web starter, which can replace the previous two dependencies, Shiro web and Shiro spring. The pom.xml file is 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>

Create Realm

The Realm here is the same as before, I will not repeat it.

Configure Shiro basic information

Next, configure Shiro's basic information in application.properties:

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

Configuration explanation:

  • The first line indicates whether the sessionId is allowed to be placed in the cookie
  • The second line indicates whether the sessionId is allowed to be placed in the Url address block
  • The third line indicates the default jump path when accessing unauthorized pages
  • The fourth line indicates shiro is on
  • The fifth line indicates a successful jump page
  • The sixth line indicates the login page

Configure 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;
}
}

The configuration here is similar to the previous one, but the ShiroFilterFactoryBean instance is no longer needed. Instead, ShiroFilterChainDefinition is used to define the path matching rules of Shiro.

After the definition, the next login interface definition and test methods are consistent with the previous ones, so I will not go over them. You can refer to the above.

Source network, only for learning, if there is infringement, contact delete.

Tags: Programming Shiro Spring xml Apache

Posted on Mon, 23 Mar 2020 00:53:31 -0700 by djremiasz