1.创建springboot工程,添加web

2.在maven工程的pom.xml文件中引入shiro-spring-boot-web-starter依赖
<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.9.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
3.在application.properties中配置shiro基本配置项
shiro.web.enabled=true
shiro.loginUrl=/login
4.创建shiro配置类:ShiroConfig;并Realm和ShiroFilterChainDefinition 两个@Bean
import org.apache.shiro.realm.Realm;
import org.apache.shiro.realm.text.TextConfigurationRealm;
import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ShiroConfig {
@Bean
Realm realm(){
TextConfigurationRealm textConfigurationRealm = new TextConfigurationRealm();
textConfigurationRealm.setUserDefinitions("admin=123,admin \n user=123,user");
return textConfigurationRealm;
}
@Bean
ShiroFilterChainDefinition shiroFilterChainDefinition(){
DefaultShiroFilterChainDefinition definition = new DefaultShiroFilterChainDefinition();
definition.addPathDefinition("/doLogin","anon");
definition.addPathDefinition("/**","authc");
return definition;
}
}
6.编写LoginController类进行测试
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class LoginController {
@GetMapping("/login")
public String login(){
return "to doLogin";
}
@PostMapping("/doLogin")
public void doLogin(String username,String password){
Subject subject = SecurityUtils.getSubject();
try{
subject.login(new UsernamePasswordToken(username,password));
System.out.println("login success");
}catch (AuthenticationException auth){
System.out.println(auth.getMessage());
}
}
@GetMapping("/hello")
public String hello(){
return "hello shiro";
}
}
7.登录之前,访问http://localhost:8080/hello返回to doLogin

8.登录之后在访问则能够访问到正确的服务。


本文详细介绍如何在SpringBoot项目中集成Apache Shiro框架,包括添加依赖、配置基本属性、编写配置类及Realm验证器,并通过示例演示登录流程。
777

被折叠的 条评论
为什么被折叠?



