IntelliJ IDEA 创建Spring Boot项目
在pom.xml文件中加入apache shiro starter依赖
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring-boot-web-starter</artifactId>
<version>1.8.0</version>
</dependency>
认证流程,即登录
新建config包,新增配置类ApacheShiroConfig,增加@Configuration注解,表明这是一个配置类,分别向容器中注入SimpleAccountRealm,DefaultSecurityManager
@Configuration
public class ApacheShiroConfig {
@Bean
public SimpleAccountRealm simpleAccountRealm(){
return new SimpleAccountRealm();
}
@Bean
public DefaultSecurityManager defaultSecurityManager(){
return new DefaultSecurityManager();
}
}
修改test包中的主启动类的测试类
@SpringBootTest
public class ApacheShiroApplicationTests {
@Test
public void contextLoads() {
}
}
新建一个Authenticator测试类ApacheShiroAuthenticatorTest
public class ApacheShiroAuthenticatorTest extends ApacheShiroApplicationTests {
@Resource
private SimpleAccountRealm accountRealm;
@Resource
private DefaultSecurityManager securityManager;
@Test
public void testLogin(){
accountRealm.addAccount("stark","123456");
accountRealm.addAccount("peter","peter");
securityManager.setRealm(accountRealm);
SecurityUtils.setSecurityManager(securityManager);
// 获取当前认证主体
Subject subject = SecurityUtils.getSubject();
// 输入用户名密码,stark
UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken("stark","123456");
// 执行登录操作
subject.login(usernamePasswordToken);
System.out.println("是否登录成功:" + subject.isAuthenticated());
}
}
执行测试,控制台输出成功登录
授权流程,授予角色权限,在addAccount时给用户增加角色,如accountRealm.addAccount("stark","123456","ADMIN");
新建测试类ApacheShiroAuthorizerTest
public class ApacheShiroAuthorizerTest extends ApacheShiroApplicationTests {
@Resource
private SimpleAccountRealm accountRealm;
@Resource
private DefaultSecurityManager securityManager;
@Test
public void testLogin(){
accountRealm.addAccount("stark","123456","ADMIN");
accountRealm.addAccount("peter","peter","USER");
securityManager.setRealm(accountRealm);
SecurityUtils.setSecurityManager(securityManager);
// 获取当前认证主体
Subject subject = SecurityUtils.getSubject();
// 输入用户名密码,stark
UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken("stark","123456");
// 执行登录操作
subject.login(usernamePasswordToken);
System.out.println(subject.isAuthenticated());
System.out.println(subject.getPrincipal());
System.out.println(subject.getPrincipal() + "是否拥有ADMIN角色:" + subject.hasRole("ADMIN"));
}
}
执行测试,查看控制台打印,说明权限授予成功
用户主体Subject
Subject常用方法: