SpringBoot整合Shiro安全框架环境搭建
这是项目结构图
导入thymeleaf和shiro依赖
<!--
subject 用户
SecurityManager管理所有用户
Realm 连接数据
-->
<!--shiro整合spring的包-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.4.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>
自定义一个Realmn在config包下 需要继承AuthorizingRealm类并重写方法
public class UserRealm extends AuthorizingRealm {
//授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
return null;
}
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
return null;
}
需要在ShiroConfig 中注入bean
@Configuration
public class ShiroConfig {
//ShiroFilterFactoryBean
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager){
ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
bean.setSecurityManager(defaultWebSecurityManager);
return bean;
}
//DefaulWebSecurityManager
@Bean(name = "securityManager")
public DefaultWebSecurityManager getdefaultWebSecurityManager(@Qualifier("userRealm")UserRealm userRealm){
DefaultWebSecurityManager SecurityManager = new DefaultWebSecurityManager();
//关联userRealm
SecurityManager.setRealm(userRealm);
return SecurityManager;
}
//创建Realmd对象需要自定义类
@Bean
public UserRealm userRealm(){
return new UserRealm();
}
}
最后建立几个html页面进行测试
然后编写视图controller进行页面跳转
package com.aaa.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class Mycontroller {
@RequestMapping({"/","/index"})
public String toIndex(Model model){
model.addAttribute("msg","Hello,Shiro");
return "index";
}
@RequestMapping("/user/add")
public String toadd(Model model){
return "user/add";
}
@RequestMapping("/user/update")
public String toupd(Model model){
return "user/update";
}
}
index.html
body>
<h1>首页</h1>
<div th:text="${msg}"></div>
<h2>
<a th:href="@{/user/add}">add</a>
<a th:href="@{/user/update}">update</a>
</h2>
</h2>
</body>
add.html和update.html是用于后续权限控制页面跳转
这只是一个简单的环境搭建