2.第一个文件为UserRealm文件:
package com.whx.config; import com.whx.pojo.User; import com.whx.service.UserService; import org.apache.shiro.authc.*; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import org.springframework.beans.factory.annotation.Autowired; public class UserRealm extends AuthorizingRealm { @Autowired UserService userService; // 授权 @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { System.out.println("执行了>=doGetAuthorizationInfo()"); return null; } // 认证 @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { System.out.println("执行了>=doGetAuthenticationInfo()"); 用户名和密码从数据库中取,此处先伪造一些数据方便验证 // String name="root"; // String password="123456"; // UsernamePasswordToken userToken=(UsernamePasswordToken)authenticationToken; 用户名验证 // if(!userToken.getUsername().equals(name)){ // return null; // } // 通过数据库连接 UsernamePasswordToken userToken=(UsernamePasswordToken)authenticationToken; User user = userService.queryUserByName(userToken.getUsername()); if(user==null){ return null; } // 密码验证,有shiro自己做,可以加密MD5以及MD5延值加密 return new SimpleAuthenticationInfo("",user.getPwd(),""); } }
用假数据写用户名和密码时,可以通过以下进行测试是否书写正确。
package com.whx; import com.whx.service.UserServiceImpl; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class SpringbootShiro1ApplicationTests { @Autowired UserServiceImpl userService; @Test void contextLoads() { System.out.println(userService.queryUserByName("小儿")); } }
在shiro配置文件中设置了权限,怎么赋值给用户呐?
死数据取值:
通过从数据库取值,在数据库中添加一条perms属性:
1.shiro与thymeleaf的整合
1.1 首先导入依赖
<dependency> <groupId>com.github.theborakompanioni</groupId> <artifactId>thymeleaf-extras-shiro</artifactId> <version>2.0.0</version> </dependency>
1.2 完成使用前的配置
在ShiroConfig文件中进行配置:
@Bean public ShiroDialect getShiroDialect(){ return new ShiroDialect();
1.3相关的应用实例
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.thymeleaf.org/thymeleaf-extras-shiro"> <head> <meta charset="UTF-8"> <title>首页</title> </head> <body> <h1>首页</h1> <div > <a th:href="@{/toLogin}">登录</a> <div/> <p th:text="${msg}"></p> <hr> <div shiro:hasPermission="user:add"> <a th:href="@{/user/add}">add</a> </div> <div shiro:hasPermission="user:update"> <a th:href="@{/user/update}">update</a> </div> </body> </html>