1、pom文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.gupaoedu</groupId>
<artifactId>springboot-Base-shiro</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.15.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.14</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>com.github.theborakompanioni</groupId>
<artifactId>thymeleaf-extras-shiro</artifactId>
<version>2.0.0</version>
</dependency>
</dependencies>
</project>
2、自定义的realm
public class AuthcRealm extends AuthorizingRealm {
@Autowired
private IUserservice userservice;
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
String username = token.getUsername();
System.out.println("认证开始"+username);
User user = new User();
user.setUsername(username);
List<User> userList = userservice.query(user);
System.out.println("认证查询到的list"+userList);
if(userList == null || userList.size() <1){
return null;
}
user = userList.get(0);
return new SimpleAuthenticationInfo(user,user.getPassword(),new SimpleByteSource("aaa"),"authcRealm");
}
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
User user = (User) principalCollection.getPrimaryPrincipal();
System.out.println("授权的账号"+user.getUsername());
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
info.addRole("role1");
return info;
}
public static void main(String[] args) {
Md5Hash md5Hash = new Md5Hash("1234","aaa",1024);
System.out.println(md5Hash);
}
}
3、shiro的配置类
@Configuration
public class ShiroConfig {
private String hashAlgorithmName = "md5";
private Integer hashIterations = 1024;
@Bean
public HashedCredentialsMatcher hashedCredentialsMatcher(){
HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
matcher.setHashAlgorithmName(hashAlgorithmName);
matcher.setHashIterations(hashIterations);
return matcher;
}
@Bean
public AuthcRealm authcRealm(HashedCredentialsMatcher matcher){
AuthcRealm realm = new AuthcRealm();
realm.setCredentialsMatcher(matcher);
return realm;
}
@Bean
public SecurityManager securityManager(AuthcRealm realm){
DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
manager.setRealm(realm);
return manager;
}
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager manager){
ShiroFilterFactoryBean filter = new ShiroFilterFactoryBean();
filter.setSecurityManager(manager);
filter.setLoginUrl("/login.do");
filter.setSuccessUrl("/success.html");
filter.setUnauthorizedUrl("/refuse.html");
Map<String,String> map = new HashMap<>();
map.put("/css/*","anon");
map.put("/js/**","anon");
map.put("/img/**","anon");
map.put("/js/**","anon");
map.put("/login.do","authc");
map.put("/login","authc");
map.put("/**","authc");
filter.setFilterChainDefinitionMap(map);
return filter;
}
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager manager){
AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
advisor.setSecurityManager(manager);
return advisor;
}
@Bean
public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator(){
DefaultAdvisorAutoProxyCreator proxyCreator = new DefaultAdvisorAutoProxyCreator();
proxyCreator.setProxyTargetClass(true);
return proxyCreator;
}
}
4、认证处理类
@Controller
public class AuthcController {
@RequestMapping("/login.do")
public String login(HttpServletRequest request){
Object attribute = request.getAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME);
System.out.println("认证失败的信息"+attribute);
return "login";
}
@RequestMapping("/logout.do")
public String logout(){
SecurityUtils.getSubject().logout();
return "redirect:/login";
}
}
5、授权业务类
@Controller
public class UserController {
@Autowired
private IUserservice userservice;
@RequiresRoles(value = {"role1","role2"},logical = Logical.OR)
@RequestMapping("/query")
public String query(Model model){
User user = new User();
model.addAttribute("list",userservice.query(user));
return "user";
}
@RequiresRoles(value = {"role2","role3"},logical = Logical.OR)
@RequestMapping("/query2")
public String query2(Model model){
User user = new User();
model.addAttribute("list",userservice.query(user));
return "user";
}
}
6、异常处理类
@Component
public class MyHandlerExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
System.out.println("全局的自定义异常出现。。。");
ModelAndView modelAndView = new ModelAndView();
if(e instanceof NullPointerException){
modelAndView.setViewName("error1");
modelAndView.addObject("errorMsg","空指针异常");
}else if(e instanceof IndexOutOfBoundsException){
modelAndView.setViewName("error2");
modelAndView.addObject("errorMsg","数组越界异常");
}else if(e instanceof AuthorizationException){
modelAndView.setViewName("error2");
modelAndView.addObject("errorMsg","无访问权限");
}else{
modelAndView.setViewName("error");
modelAndView.addObject("errorMsg","其他异常");
}
return modelAndView;
}
}
7、shiro与thymeleaf的整合
@SpringBootApplication
@MapperScan("com.gupaoedu.mapper")
public class StartAPP {
public static void main(String[] args) {
SpringApplication.run(StartAPP.class,args);
}
@Bean
public ShiroDialect shiroDialect(){
return new ShiroDialect();
}
}
8、页面
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>登录管理</h1>
<form th:action="@{/login.do}" method="post">
<label>账号:</label><input type="text" name="username"><br>
<label>密码:</label><input type="password" name="password"><br>
<input type="submit" value="提交">
</form>
</body>
</html>
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
xmlns:shiro="http://www.pollix.at/thymeleaf/shiro"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>用户信息</title>
</head>
<body>
<h1>用户管理</h1>
<table border="1" style="width: 300px">
<tr>
<th>用户ID</th>
<th>用户姓名</th>
</tr>
<tr th:each="user:${list}">
<td th:text="${user.username}"></td>
<td th:text="${user.password}"></td>
</tr>
</table>
<br>
<br>
<hr>
<span shiro:authenticated>已登录<br/></span>
<span shiro:hasRole="role1" >role1</span>
<span shiro:hasRole="role2" >role2</span>
<span shiro:hasRole="role3" >role3</span>
</body>
</html>