欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

springboot整合shiro的過程詳解

 更新時間:2021年10月26日 09:34:49   作者:桐花思雨  
Shiro 是一個強大的簡單易用的 Java 安全框架,主要用來更便捷的 認證,授權(quán),加密,會話管理,這篇文章給大家詳細介紹Shiro 工作原理及架構(gòu)圖,通過實例圖文相結(jié)合給大家介紹的非常詳細,需要的朋友參考下吧

什么是 Shiro

Shiro 是一個強大的簡單易用的 Java 安全框架,主要用來更便捷的 認證,授權(quán),加密,會話管理Shiro 首要的和最重要的目標就是容易使用并且容易理解,通過 Shiro 易于理解的API,您可以快速、輕松地獲得任何應用程序——從最小的移動應用程序最大的網(wǎng)絡和企業(yè)應用程序

Shiro 架構(gòu)

Shiro 架構(gòu)圖

在這里插入圖片描述

  • Authentication:身份認證/登錄
  • Authorization:驗證權(quán)限,即,驗證某個人是否有做某件事的權(quán)限
  • Session Management:會話管理。管理用戶特定的會話,支持 web 與非 web
  • Cryptography: 加密,保證數(shù)據(jù)安全
  • Caching:緩存
  • Remember Me:記住我,即記住登錄狀態(tài),一次登錄后,下次再來的話不用登錄了

Shiro 工作原理

Shiro 的架構(gòu)有三個主要概念:Subject,SecurityManagerRealms

在這里插入圖片描述

  • Subject:當前參與應用安全部分的主角??梢允怯脩?,可以試第三方服務,可以是 cron 任務,或者任何東西。主要指一個正在與當前軟件交互的東西。所有 Subject 都需要 SecurityManager,當你與 Subject 進行交互,這些交互行為實際上被轉(zhuǎn)換為與 SecurityManager 的交互
  • SecurityManager:安全管理器,Shiro 架構(gòu)的核心,它就像 Shiro 內(nèi)部所有原件的保護傘。然而一旦配置了 SecurityManager,SecurityManager 就用到的比較少,開發(fā)者大部分時間都花在 Subject 上面。當你與 Subject 進行交互的時候,實際上是 SecurityManager在 背后幫你舉起 Subject 來做一些安全操作
  • RealmsRealms 作為 Shiro 和你的應用的連接橋,當需要與安全數(shù)據(jù)交互的時候,像用戶賬戶,或者訪問控制,Shiro 就從一個或多個 Realms 中查找。Shiro 提供了一些可以直接使用的 Realms,如果默認的 Realms不能滿足你的需求,你也可以定制自己的 Realms

Shiro 詳細架構(gòu)圖

在這里插入圖片描述

  • Subject:與應用交互的主體,例如用戶,第三方應用等
  • SecurityManagershiro 的核心,負責整合所有的組件,使他們能夠方便快捷完成某項功能。例如:身份驗證,權(quán)限驗證等
  • Authenticator:認證器,負責主體認證的,這是一個擴展點,如果用戶覺得 Shiro 默認的不好,可以自定義實現(xiàn);其需要認證策略(Authentication Strategy),即什么情況下算用戶認證通過了。
  • Authorizer:決定主體是否有權(quán)限進行相應的操作;即控制著用戶能訪問應用中的哪些功能
  • SessionManager:會話管理。CacheManager:緩存管理器。創(chuàng)建和管理緩存,為 authentication, authorizationsession management 提供緩存數(shù)據(jù),避免直接訪問數(shù)據(jù)庫,提高效率
  • Cryptography;密碼模塊,提供加密組件
  • Realms:可以有 1 個或多個 Realm,可以認為是安全實體數(shù)據(jù)源,即用于獲取安全實體的;可以是 JDBC 實現(xiàn),也可以是 LDAP 實現(xiàn),或者內(nèi)存實現(xiàn)等等;由用戶提供;注意:Shiro 不知道你的用戶/權(quán)限存儲在哪及以何種格式存儲;所以我們一般在應用中都需要實現(xiàn)自己的 Realm

springboot 整合 shiro

springboot 整合 shiro 思路

在這里插入圖片描述

項目搭建

主要依賴

<!--thymeleaf 模板引擎-->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!--shiro-->
<dependency>
	<groupId>org.apache.shiro</groupId>
	<artifactId>shiro-spring-boot-starter</artifactId>
	<version>1.4.0</version>
</dependency>
<!-- thymeleaf 集成 shiro -->
<dependency>
	<groupId>com.github.theborakompanioni</groupId>
    <artifactId>thymeleaf-extras-shiro</artifactId>
	<version>2.0.0</version>
</dependency>

數(shù)據(jù)庫表設計

CREATE TABLE `shiro_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL,
  `nickname` varchar(255) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `index_username` (`username`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4;

INSERT INTO `shiro_user` VALUES (1, 'lisi', '110110', '李四');
INSERT INTO `shiro_user` VALUES (2, 'zs', '123456', '逆風飛翔');
INSERT INTO `shiro_user` VALUES (3, 'jack', '111111', '砥礪奮進');
INSERT INTO `shiro_user` VALUES (4, 'Tom', '123123', '靜夜思');
INSERT INTO `shiro_user` VALUES (5, 'nike', '222222', '殺傷力巨大');

CREATE TABLE `shiro_user_role` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL,
  `role_id` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4;

INSERT INTO `shiro_user_role` VALUES (1, 1, 1);
INSERT INTO `shiro_user_role` VALUES (2, 2, 3);
INSERT INTO `shiro_user_role` VALUES (3, 3, 3);
INSERT INTO `shiro_user_role` VALUES (4, 4, 2);

CREATE TABLE `shiro_role` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `role_code` varchar(255) NOT NULL,
  `role_name` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4;

INSERT INTO `shiro_role` VALUES (1, '1', '管理員');
INSERT INTO `shiro_role` VALUES (2, '2', '普通一級用戶');
INSERT INTO `shiro_role` VALUES (3, '3', '普通二級用戶');
INSERT INTO `shiro_role` VALUES (4, '4', '普通三級用戶');

CREATE TABLE `shiro_auth_role` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `auth_id` int(11) NOT NULL,
  `role_id` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8mb4;

INSERT INTO `shiro_auth_role` VALUES (1, 1, 1);
INSERT INTO `shiro_auth_role` VALUES (2, 2, 1);
INSERT INTO `shiro_auth_role` VALUES (3, 3, 1);
INSERT INTO `shiro_auth_role` VALUES (4, 4, 1);
INSERT INTO `shiro_auth_role` VALUES (5, 3, 2);
INSERT INTO `shiro_auth_role` VALUES (6, 4, 2);
INSERT INTO `shiro_auth_role` VALUES (7, 4, 3);
INSERT INTO `shiro_auth_role` VALUES (8, 4, 4);
INSERT INTO `shiro_auth_role` VALUES (9, 1, 3);

CREATE TABLE `shiro_auth` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `auth_code` varchar(255) NOT NULL,
  `auth_name` varchar(255) NOT NULL,
  `parent_id` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4;

INSERT INTO `shiro_auth` VALUES (1, 'user:add', '添加', 1);
INSERT INTO `shiro_auth` VALUES (2, 'user:delete', '刪除', 2);
INSERT INTO `shiro_auth` VALUES (3, 'user:update', '更新', 3);
INSERT INTO `shiro_auth` VALUES (4, 'user:list', '查看', 4);

在這里插入圖片描述

實體類

public class User implements Serializable {
    private Integer id;

    @NotBlank(message = "賬號不能為空")
    private String username;

    @NotEmpty(message = "密碼不能為空")
    private String password;

    private String nickname;

	// set/get方法省略
}

public class Role {
    private Integer id;

    private String roleCode;

    private String roleName;
    
	// set/get方法省略
}

public class Auth {
    private Integer id;

    private String authCode;

    private String authName;

    private Integer parentId;

	// set/get方法省略
}

自定義 Realm

realmshiro 進行登錄認證,權(quán)限,角色校驗的關(guān)鍵,我們需要重寫里面的方法

@Component
@Slf4j
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    // 授權(quán),權(quán)限操作
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(@NotNull PrincipalCollection principals) {
        log.info("------進入授權(quán)操作了------");
        User user = (User) principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        // 通過賬號來查詢相應的角色,權(quán)限數(shù)據(jù)
        List<AuthAndRoleVO> authAndRoleVOS = userService.selectAuthAndRole(user.getUsername());
        authAndRoleVOS.forEach(item -> {
            log.info("查詢到的權(quán)限,角色:" + item.toString());
            String roleName = item.getRoleName();
            String authCode = item.getAuthCode();
            info.addStringPermission(authCode);
            info.addRole(roleName);
        });
        return info;
    }

    // 認證操作
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        log.info("------進入認證操作了------");
        // 拿到UsernamePasswordToken,它里面有用戶名,密碼數(shù)據(jù)
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        // 查詢數(shù)據(jù)庫
        User user = userService.selectOne(usernamePasswordToken.getUsername(), String.valueOf(usernamePasswordToken.getPassword()));
        if (user == null) {
            return null;
        }
        return new SimpleAuthenticationInfo(user, token.getCredentials(), getName());
    }
}
  • 這里 ORM 持久層不再贅述,用 mybatisjpa 等都可以
  • doGetAuthorizationInfo(): 權(quán)限認證。即登錄過后,每個用戶的身份不一樣,對應的所能看的頁面也不一樣,也就是擁有的權(quán)限也不一樣
  • doGetAuthenticationInfo():身份認證。即登錄通過賬號和密碼驗證登陸人的身份信息

shiro 的配置類

@Configuration
public class ShiroConfig {

    /**
     * 安全管理器
     */
    @Bean
    public DefaultWebSecurityManager getDefaultWebSecurityManager(UserRealm userRealm) {
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        defaultWebSecurityManager.setRealm(userRealm);     
        return defaultWebSecurityManager;
    }

    /**
     * thymeleaf模板引擎中使用shiro標簽時,要用到
     */
    @Bean
    public ShiroDialect getShiroDialect() {
        return new ShiroDialect();
    }

    @Bean
    public ShiroFilterFactoryBean shiroFilter(DefaultWebSecurityManager defaultWebSecurityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
        // 設置登錄頁面url
        shiroFilterFactoryBean.setLoginUrl("/user/login");
        shiroFilterFactoryBean.setSuccessUrl("/user/index");
        shiroFilterFactoryBean.setUnauthorizedUrl("/user/unauthorized");

        // 注意此處使用的是LinkedHashMap是有順序的,shiro會按從上到下的順序匹配驗證,匹配了就不再繼續(xù)驗證
        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
		// 靜態(tài)資源放行
        filterChainDefinitionMap.put("/layer/**", "anon");
        filterChainDefinitionMap.put("/img/**", "anon");
        filterChainDefinitionMap.put("/jquery/**", "anon");
        // add.html頁面放行
        filterChainDefinitionMap.put("/user/add", "anon");
        // update.html必須認證
        filterChainDefinitionMap.put("/user/update", "authc");
        // index.html必須認證
        filterChainDefinitionMap.put("/user/index", "authc");
        // 設置授權(quán),只有user:add權(quán)限的才能請求/user/add這個url
        filterChainDefinitionMap.put("/user/add", "perms[user:add]");
        filterChainDefinitionMap.put("/user/update", "perms[user:update]");     

        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
        return shiroFilterFactoryBean;
    }
}

ShiroFilterFactoryBean 過濾器鏈配置中的 url 匹配規(guī)則

  •  ?:匹配一個字符,如 /admin?,將匹配 /admin1、/admin2,但不匹配 /admin
  • *:匹配零個或多個字符串,如 /admin* ,將匹配 /admin、/admin123,但不匹配 /admin/1
  • **:匹配路徑中的零個或多個路徑,如 /admin/**,將匹配 /admin/a、/admin/a/b

ShiroFilterFactoryBean 過濾器

  • anon:匿名過濾器,無需認證就可以訪問。例:/statics/**= anon 表示 statics 目錄下所有資源都能訪問
  • authc:必須認證了才能訪問,否則跳轉(zhuǎn)到登錄頁面。例:/unauthor.jsp= authc 如果用戶沒有登錄就訪問 unauthor.jsp,則直接跳轉(zhuǎn)到登錄頁面
  • user:必須通過記住我功能通過或認證通過才能訪問
  • perms:擁有對某個資源的權(quán)限才能訪問。例:/statics/** = perms["user:add:*,user:modify:*"] 表示訪問 statics 目錄下的資源時只有新增和修改的權(quán)限
  • roles:擁有某個角色權(quán)限才能訪問。例:/welcom.jsp = roles[admin] 表示訪問 welcom.jsp 頁面時會檢查是否擁有 admin 角色

ShiroFilterFactoryBean 過濾器分類

  • 認證過濾器:anon、authcBasic、auchc、user、logout
  • 授權(quán)過濾器:perms、roles、ssl、rest、port

前端頁面

登錄頁面 login.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>登錄</title>
    <link rel="shortcut icon" type="image/x-icon" th:href="@{/img/favicon.ico}" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" />
</head>
<body>
<form action="" method="post">
    <p>
        賬號:
        <label><input type="text" class="username" name="username"></label>
    </p>
    <p>
        密碼:
        <label><input type="text" class="password" name="password"></label>
    </p>
    <p>
        <label><input id="checkbox1" type="checkbox" name="rememberMe"></label>記住我
    </p>
    <p><button type="button" class="loginBtn">登錄</button></p>
</form>
</body>
<script type="text/javascript" th:src="@{/jquery/jquery-3.3.1.min.js}"></script>
<script type="text/javascript" th:src="@{/layer/layer.js}"></script><!--layui的彈出層-->
<script type="text/javascript">
    $(document).ready(function () {
        $('.loginBtn').on('click', function () { // 登錄按鈕
            const username = $('.username').val();
            const password = $('.password').val();
            $.ajax({// 用戶登錄
                type: 'post',
                url: '/user/doLogin',
                dataType: 'json',
                data: ({
                    'username': username,
                    'password': password
                }),
                success: function (resp) {
                    console.log(resp);
                    if (resp.code !== 200) {
                        layer.msg(resp.message, function () {// layui的彈窗
                        });
                    } else if (resp.code === 200) {
                        window.location.+ resp.action;
                    }
                },
                error: function () {// 此處添加錯誤處理
                    layer.open({
                        title: '提示信息',
                        content: '后臺訪問錯誤,請聯(lián)系管理員',
                        skin: 'layui-layer-molv',
                        icon: 0
                    });
                }
            });
        });
    });
</script>
</html>

首頁頁面 index.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>首頁</title>
    <link rel="shortcut icon" type="image/x-icon" th:href="@{/img/favicon.ico}" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" />
</head>
<body>
    <h1>首頁</h1>

    <a th:href="@{/user/add}" rel="external nofollow" >add</a> | <a th:href="@{/user/update}" rel="external nofollow" >update</a><br>

    <a th:href="@{/user/logout}" rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >退出登錄</a>
</body>
</html>

添加頁面 add.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>add</title>
    <link rel="shortcut icon" type="image/x-icon" th:href="@{/img/favicon.ico}" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" />
</head>
<body>
    <h1>add</h1><br>

    <a th:href="@{/user/logout}" rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >退出登錄</a>
</body>
</html>

更新頁面 update.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>update</title>
    <link rel="shortcut icon" type="image/x-icon" th:href="@{/img/favicon.ico}" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" />
</head>
<body>
    <h1>update</h1><br>

    <a th:href="@{/user/logout}" rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >退出登錄</a>
</body>
</html>

未授權(quán)頁面 unauthorized.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns="http://www.w3.org/1999/html">
<head>
    <meta charset="UTF-8">
    <title>未授權(quán)</title>
    <link rel="shortcut icon" type="image/x-icon" th:href="@{/img/favicon.ico}" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" />
</head>
<body>
    <p1>未授權(quán),無法訪問此頁面</p1></br>
    <a th:href="@{/user/index}" rel="external nofollow" >回到上一頁</a>
</body>
</html>

controller 控制器

鑒于文章篇幅,這里只展示主要的邏輯代碼

@Controller
@RequestMapping(path = "/user")
@Slf4j
public class UserController {

	@GetMapping(path = "/login")
    public String login() {
        return "login";
    }

    @GetMapping(path = "/index")
    public String index() {
        return "index";
    }

    @GetMapping(path = "/add")
    public String add() {
        return "add";
    }

    @GetMapping(path = "/update")
    public String update() {
        return "update";
    }
	
	// 未授權(quán)頁面
    @GetMapping(path = "/unauthorized")
    public String unauthorized() {
        return "unauthorized";
    }

    // 用戶登錄
    @PostMapping(path = "/doLogin")
    @ResponseBody
    public ResultMap doLogin(@NotNull @Valid User user, @NotNull BindingResult bindingResult) {
        // ------參數(shù)校驗------
        if (bindingResult.hasErrors()) {
            String message = Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage();
            log.info("校驗的message信息為:" + message);
            return new ResultMap().fail().message(message);
        }
        // 將用戶名,密碼交給shiro
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
        String msg;
        try {
            // shiro幫我們匹配密碼什么的,我們只需要把東西傳給它,它會根據(jù)我們在UserRealm里認證方法設置的來驗證
            Subject subject = SecurityUtils.getSubject();
            subject.login(token);
            return new ResultMap().success().action("/user/index");
        } catch (AuthenticationException e) {
            if (e instanceof IncorrectCredentialsException) {
                msg = "密碼錯誤";
            } else if (e instanceof LockedAccountException) {
                msg = "用戶被禁用";
            } else if (e instanceof UnknownAccountException) {
                msg = "用戶不存在";
            } else {
                msg = "用戶認證失敗";
            }
        }
        return new ResultMap().error().message(msg);
    }

    // 用戶退出登錄
    @GetMapping(path = "/logout")
    public String logout() {
        SecurityUtils.getSubject().logout();
        return "login";
    }
}

shiro 注解

在 contrller 的這些方法中,也可以使用 shiro 提供的一些注解來校驗用戶,認證用戶。不過個人認為使用這些注解有點麻煩(因為有些注解會拋出異常,然后再 controller 層還要捕獲異常),所以我在 ShiroConfig 配置類中進行了配置

  • @RequiresAuthentication:表示當前 Subject 已經(jīng)通過 login 進行了身份驗證;即 Subject.isAuthenticated() 返回 true
  • @RequiresUser:表示當前 Subject 已經(jīng)通過身份驗證或者通過記住我進行登錄的
  • @RequiresGuest:表示當前 Subject 沒有身份驗證或通過記住我登錄過,即是游客身份
  • @RequiresRoles(value={“admin”, “user”}, logical= Logical.AND):表示當前 Subject 需要角色 admin 和 user。如果當前 Subject 不同時 擁有所有指定角色,則方法不會執(zhí)行還會拋出 AuthorizationException 異常
  • @RequiresPermissions(value={“user:a”, “user:b”}, logical= Logical.OR):表示當前 Subject 需要權(quán)限 user:a 或 user:b。如果當前 Subject 不具有這樣的權(quán)限,則方法不會被執(zhí)行

測試

啟動項目,首先進入登錄頁面 login.html,如下

在這里插入圖片描述

我們分別以數(shù)據(jù)庫中的 {jack,111111} 和 {Tom,123123} 賬號與密碼進行測試

在這里插入圖片描述

測試一

首先使用 {jack,111111} 來進行登錄,如下

在這里插入圖片描述

進入首頁頁面,如下

在這里插入圖片描述

我們在接著查看控制臺日志,如下

在這里插入圖片描述

我們看到首頁頁面有兩個超鏈接頁面,以用戶 jack 的身份分別進入兩個頁面。首先進入 add.html 頁面,如下

在這里插入圖片描述

說明用戶 jack 擁有訪問 add.html 的權(quán)限,此時在查看控制臺日志,如下

在這里插入圖片描述

注意查看用戶 jack 的數(shù)據(jù),他的權(quán)限只有 user/add 和 user/list,是沒有 user/update 權(quán)限的,也就是沒有權(quán)限訪問 update.html 頁面的??梢则炞C,我們再以用戶 jack 的身份進入 update.html 頁面,如下

在這里插入圖片描述

關(guān)于測試,到此為止。當然,依然可以使用其他的數(shù)據(jù)在進行測試

小結(jié)

shiro 最為關(guān)鍵的就是 realm 了,繼承 AuthorizingRealm,然后重寫兩個方法

  • doGetAuthorizationInfo(): 權(quán)限認證。即登錄過后,每個用戶的身份不一樣,對應的所能看的頁面也不一樣,也就是擁有的權(quán)限也不一樣
  • doGetAuthenticationInfo():身份認證。即登錄通過賬號和密碼驗證登陸人的身份信息

在 controller 中的核心登錄操作,就是將前端頁面用戶的登錄數(shù)據(jù)(如賬號,密碼)交給 UsernamePasswordToken,然后使用當前的 Subject 對象調(diào)用 login(token) 方法即可,如下

// 將用戶名,密碼交給shiro
UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());

// shiro幫我們匹配密碼什么的,我們只需要把東西傳給它,它會根據(jù)我們在UserRealm里認證方法設置的來驗證
Subject subject = SecurityUtils.getSubject();
subject.login(token);

源碼:springboot-shiro

到此這篇關(guān)于springboot整合shiro的文章就介紹到這了,更多相關(guān)springboot整合shiro內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • java根據(jù)本地IP獲取mac地址的方法

    java根據(jù)本地IP獲取mac地址的方法

    這篇文章主要為大家詳細介紹了java根據(jù)本地IP獲取mac地址的方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-06-06
  • SpringBoot訪問HTML過程詳解

    SpringBoot訪問HTML過程詳解

    這篇文章主要詳細介紹了SpringBoot訪問HTML的全過程,文章中有詳細的代碼和圖片講解,感興趣的同學可以參考一下
    2023-04-04
  • java項目實現(xiàn)猜拳小游戲

    java項目實現(xiàn)猜拳小游戲

    這篇文章主要為大家詳細介紹了java項目實現(xiàn)猜拳小游戲,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2020-05-05
  • 關(guān)于ZooKeeper的會話機制Session解讀

    關(guān)于ZooKeeper的會話機制Session解讀

    這篇文章主要介紹了關(guān)于ZooKeeper的會話機制Session解讀,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-02-02
  • 自主配置數(shù)據(jù)源,mybatis/plus不打印sql日志問題

    自主配置數(shù)據(jù)源,mybatis/plus不打印sql日志問題

    這篇文章主要介紹了自主配置數(shù)據(jù)源,mybatis/plus不打印sql日志問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-12-12
  • Java中典型的內(nèi)存泄露問題和解決方法

    Java中典型的內(nèi)存泄露問題和解決方法

    這篇文章主要介紹了Java中典型的內(nèi)存泄露問題和解決方法,典型的內(nèi)存泄露例子是一個沒有實現(xiàn)hasCode和 equals方法的Key類在HashMap中保存的情況,可以通過實現(xiàn)Key類的equals和hasCode方法解決這種內(nèi)存泄漏問題,需要的朋友可以參考下
    2014-04-04
  • Java利用讀寫的方式實現(xiàn)音頻播放代碼實例

    Java利用讀寫的方式實現(xiàn)音頻播放代碼實例

    這篇文章主要介紹了Java利用讀寫的方式實現(xiàn)音頻播放代碼實例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2019-11-11
  • Struts2的輸入校驗實例代碼

    Struts2的輸入校驗實例代碼

    這篇文章主要介紹了Struts2的輸入校驗實例代碼,非常不錯,具有參考借鑒價值, 需要的朋友可以參考下
    2017-03-03
  • SpringBoot?將配置文件掛到?jar?包外面的操作方法

    SpringBoot?將配置文件掛到?jar?包外面的操作方法

    在 SpringBoot 中,可以將配置文件放在 jar 包外面,這樣可以方便地修改配置而不需要重新打包和部署,這篇文章主要介紹了SpringBoot?如何將配置文件掛到?jar?包外面,需要的朋友可以參考下
    2023-03-03
  • Spring Cloud根據(jù)服務名獲取服務的ip端口問題

    Spring Cloud根據(jù)服務名獲取服務的ip端口問題

    這篇文章主要介紹了Spring Cloud根據(jù)服務名獲取服務的ip端口,本篇示例我就以Nacos注冊中心為例了,下面是我注冊的兩個服務,需要的朋友可以參考下
    2022-09-09

最新評論