springboot-shiro:整合thymeleaf
阿新 • • 發佈:2022-03-09
1 引入thymeleaf-shiro整合依賴
pom.xml
<!--thymeleaf-shiro整合包-->
<dependency>
<groupId>com.github.theborakompanioni</groupId>
<artifactId>thymeleaf-extras-shiro</artifactId>
<version>2.1.0</version>
</dependency>
2 配置一個shiro的Dialect,在ShiroConfig中增加一個Bean
src/main/java/com/lv/config/ShiroConfig.java
//整合ShiroDialect:用來整合shiro thymeleaf
@Bean
public ShiroDialect getShiroDialect(){
return new ShiroDialect();
}
3 修改首頁
增加了三部分:
- 在標頭檔案中加入了shiro的約束
- 添加了登入的連結,和通過 th:if 實現該連結是否顯示的判斷.
- 添加了通過 shiro:hasPermission 對add和update連結顯示與否的判斷
src/main/resources/templates/index.html
<!DOCTYPE html> <html lang="en" xmlns:shiro="http://www.thymeleaf.org/thymeleaf-extras-shiro"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>首頁</h1> <p th:text="${msg}"></p> <!--從session中判斷值--> <div th:if="${session.loginUser == null}"> <a th:href="@{/toLogin}">登入</a> </div> <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>
4 在UserRealm 新增存入使用者資訊的程式碼
在使用者認證成功後,將使用者資訊放入session中
src/main/java/com/lv/config/UserRealm.java
//認證
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("執行了=>認證doGetAuthorizationInfo");
UsernamePasswordToken userToken = (UsernamePasswordToken) token;
//連線真實的資料庫
User user = userService.queryUserByName(userToken.getUsername());
if (user == null){ //沒有這個人
return null; //UnknownAccountException
}
//使用者登入成功將使用者資訊存入session
Subject currentSubject = SecurityUtils.getSubject();
Session session = currentSubject.getSession();
session.setAttribute("loginUser",user);
//密碼認證,交給shiro做(可以加密: MD5,MD5鹽值加密)
return new SimpleAuthenticationInfo(user,user.getPwd(),"");
}
5 啟動專案測試
訪問首頁,未登入狀態下,顯示了登入按鈕,點選登入
跳轉到了登陸頁面,登入admin1使用者
登入成功後,登入按鈕消失,並且只顯示add按鈕,admin1使用者只有訪問add許可權
再登入admin2使用者,只顯示了update按鈕,admin2使用者只有訪問update許可權
說明許可權控制成功實現,thymeleaf語法生效了,shiro整合thymeleaf完成