日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

springboot 与shiro整合

發布時間:2023/12/10 编程问答 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 springboot 与shiro整合 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

shiro~

    • shiro快速入門
    • springboot 整合shiro
      • 核心目標
      • 清爽pom
      • 用戶認證授權認證,與數據庫交互
      • shiro configuration
      • 核心controller 獲取shiro 中的token
      • 頁面控制功能的隱藏和顯示

https://github.com/sevenyoungairye/spring-boot-study/tree/main/springboot-shiro-07

shiro快速入門

  • 什么是shiro
    • apache shiro 是一個java的安全(權限)框架。
    • shiro可以非常容易的開發出足夠好的應用,可以在javase環境,也可用在javaee環境
    • shiro可以完成 認證,授權,加密,會話管理,web繼承,緩存等。
    • 下載地址:http://shiro.apache.org
  • shiro快速入門代碼簡單分析~
    git來拿來的
  • import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.*; import org.apache.shiro.config.IniSecurityManagerFactory; import org.apache.shiro.mgt.SecurityManager; import org.apache.shiro.session.Session; import org.apache.shiro.subject.Subject; import org.apache.shiro.util.Factory; import org.slf4j.Logger; import org.slf4j.LoggerFactory;public class QuickStart {// 日志對象private static final transient Logger log = LoggerFactory.getLogger(QuickStart.class);public static void main(String[] args) {// 創建shiro環境Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");SecurityManager securityManager = factory.getInstance();SecurityUtils.setSecurityManager(securityManager);// 獲取當前的用戶對象Subject currentUser = SecurityUtils.getSubject();// 獲取當前sessionSession session = currentUser.getSession();// 設置keysession.setAttribute("someKey", "aValue");// 獲取valueString value = (String) session.getAttribute("someKey");if (value.equals("aValue")) {log.info("Retrieved the correct value! [" + value + "]");}// let's login the current user so we can check against roles and permissions:// 是否被認證if (!currentUser.isAuthenticated()) {// token 根據用戶密碼 拿到令牌UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");// 記住密碼token.setRememberMe(true);try {// 執行了登錄操作currentUser.login(token);} catch (UnknownAccountException uae) { // 賬號不存在log.info("There is no user with username of " + token.getPrincipal());} catch (IncorrectCredentialsException ice) { // 密碼錯誤log.info("Password for account " + token.getPrincipal() + " was incorrect!");} catch (LockedAccountException lae) { // 賬戶鎖定log.info("The account for username " + token.getPrincipal() + " is locked. " +"Please contact your administrator to unlock it.");}// ... catch more exceptions here (maybe custom ones specific to your application?catch (AuthenticationException ae) {// 最大異常//unexpected condition? error?}}// 拿到用戶信息//say who they are://print their identifying principal (in this case, a username):log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");// 用戶的角色//test a role:if (currentUser.hasRole("schwartz")) {log.info("May the Schwartz be with you!");} else {log.info("Hello, mere mortal.");}// 用戶的普通權限//test a typed permission (not instance-level)if (currentUser.isPermitted("lightsaber:wield")) {log.info("You may use a lightsaber ring. Use it wisely.");} else {log.info("Sorry, lightsaber rings are for schwartz masters only.");}// 用戶的更大的權限//a (very powerful) Instance Level permission:if (currentUser.isPermitted("winnebago:drive:eagle5")) {log.info("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'. " +"Here are the keys - have fun!");} else {log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");}// 注銷//all done - log out!currentUser.logout();System.exit(0);} }

    springboot 整合shiro

    核心目標

    • springboot 整合shiro shiro-spring

    • subject 用戶

    • SecurityManager 管理所有用戶

    • Realm 連接數據

    • 認證 數據庫匹配賬號密碼

    • 授權 用戶的角色匹配 [user:add], [user:update]用戶修改和新增的權限

    • shiro與thymeleaf的整合

    清爽pom

    • shiro-core
    <!-- shiro config.. --><dependencies><dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-core</artifactId><version>1.6.0</version></dependency><!-- configure logging --><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-log4j12</artifactId><version>1.7.30</version><scope>runtime</scope></dependency><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.12</version><scope>runtime</scope></dependency></dependencies>
    • spring 與shiro整合
    <!-- thymeleaf & shiro --><dependency><groupId>com.github.theborakompanioni</groupId><artifactId>thymeleaf-extras-shiro</artifactId><version>2.0.0</version></dependency><!-- shiro & springboot --><dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-spring</artifactId><version>1.6.0</version></dependency>

    用戶認證授權認證,與數據庫交互

    package cn.bitqian.config;import cn.bitqian.entity.Users; import cn.bitqian.mapper.UsersMapper; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.*; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.authz.SimpleAuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import org.apache.shiro.subject.Subject; import org.springframework.beans.factory.annotation.Autowired;/*** 用戶認證* @author echo lovely* @date 2020/10/27 15:58*/ public class UserRealm extends AuthorizingRealm {@Autowiredprivate UsersMapper usersMapper;// 授權@Overrideprotected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {System.out.println("授權認證=> PrincipalCollection");SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();// 對user:add授權// authorizationInfo.addStringPermission("user:add");// 獲取當前用戶Subject subject = SecurityUtils.getSubject();Users users = (Users) subject.getPrincipal();// 進行身份認證 設置當前用戶的權限authorizationInfo.addStringPermission(users.getPermission());return authorizationInfo;}// 認證@Overrideprotected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {System.out.println("登錄認證=> AuthenticationToken");// 用戶名 密碼認證UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;// 頁面用戶名String tokenUsername = userToken.getUsername();// 數據庫中是否存在該用戶Users users = usersMapper.findUsersByUsersName(tokenUsername);if (users == null) {return null;}SecurityUtils.getSubject().getSession().setAttribute("loginUser", users);// principal 用戶認證 用戶里面存在權限return new SimpleAuthenticationInfo(users, users.getUserPassword(), ""); // 密碼自動驗證} }

    shiro configuration

    package cn.bitqian.config;import at.pollux.thymeleaf.shiro.dialect.ShiroDialect; import org.apache.shiro.mgt.SecurityManager; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.spring.web.ShiroFilterFactoryBean; import org.apache.shiro.web.mgt.DefaultWebSecurityManager; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;import java.util.LinkedHashMap; import java.util.Map;/*** shiro的配置類* @author echo lovely* @date 2020/10/27 16:03*/ @Configuration public class ShiroConfig {// 1. 自定義realm對象@Bean(name = "authorizingRealm")public AuthorizingRealm authorizingRealm() {return new UserRealm();}// 2. DefaultWebSecurityManager@Bean(name = "securityManager")public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("authorizingRealm") AuthorizingRealm authorizingRealm) {DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();// 關聯UserRealmsecurityManager.setRealm(authorizingRealm);return securityManager;}// 3. ShiroFilterFactoryBean@Beanpublic ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") SecurityManager securityManager) {ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();// 設置安全管理器shiroFilterFactoryBean.setSecurityManager(securityManager);/*** anon 無需認證就可訪問* authc 必須認證了才能訪問* user 必須擁有 記住我 功能* perms 擁有對某個資源的權限* roles 角色權限*/Map<String, String> filterMap = new LinkedHashMap<>();shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);// filterMap.put("/*", "authc");// 必須認證 才可用filterMap.put("/update", "authc");filterMap.put("/add", "authc");// 必須有某個資源的權限 授權 正常的情況下,沒有授權會跳轉到未授權頁面// user:add 和 user:update 的權限filterMap.put("/add", "perms[user:add]");filterMap.put("/update", "perms[user:update]");// 設置登錄請求shiroFilterFactoryBean.setLoginUrl("login");// 沒有權限 跳轉到提示到頁面shiroFilterFactoryBean.setUnauthorizedUrl("/unauthorized");return shiroFilterFactoryBean;}@Bean // 用來整合thymeleafpublic ShiroDialect getShiroDialect() {return new ShiroDialect();}}

    核心controller 獲取shiro 中的token

    @PostMapping(value = "/login")public String login(String username, String password, Model model) {// 設置用戶名 跟 密碼UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);// 獲取當前用戶對象Subject subject = SecurityUtils.getSubject();try {// 執行了登錄操作subject.login(usernamePasswordToken);return "index";} catch (UnknownAccountException uae) { // 賬號不存在model.addAttribute("msg", "賬號錯誤");return "login";} catch (IncorrectCredentialsException ice) { // 密碼錯誤model.addAttribute("msg", "密碼錯誤");return "login";}}@RequestMapping(value = "/unauthorized")@ResponseBodypublic String toUnauthorized() {return "未經授權,不許訪問!";}

    頁面控制功能的隱藏和顯示

    <!DOCTYPE html> <html lang="en"xmlns:th="http://www.thymeleaf.org"xmlns:shiro="http://www.thymeleaf.org/thymeleaf-extras-shiro.com"> <head><meta charset="UTF-8"><title>index shiro</title> </head> <body><p th:text="${msg}"></p><hr/><div th:if="${session.loginUser==null}"><a href="/login">login</a></div><div shiro:hasPermission="user:add"><a th:href="@{/add}">add</a></div><div shiro:hasPermission="user:update"><a th:href="@{/update}">update</a></div></body> </html>

    更多代碼git clone

    總結

    以上是生活随笔為你收集整理的springboot 与shiro整合的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。