溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

springboot如何整合shiro實(shí)現(xiàn)登錄驗(yàn)證授權(quán)的過(guò)程解析

發(fā)布時(shí)間:2022-01-26 11:49:10 來(lái)源:億速云 閱讀:126 作者:柒染 欄目:開(kāi)發(fā)技術(shù)

本篇文章為大家展示了springboot如何整合shiro實(shí)現(xiàn)登錄驗(yàn)證授權(quán)的過(guò)程解析,內(nèi)容簡(jiǎn)明扼要并且容易理解,絕對(duì)能使你眼前一亮,通過(guò)這篇文章的詳細(xì)介紹希望你能有所收獲。

springboot整合shiro實(shí)現(xiàn)登錄驗(yàn)證授權(quán),內(nèi)容如下所示:

1.添加依賴:

<!-- shiro -->
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring</artifactId>
            <version>1.7.1</version>
        </dependency>

2.yml配置:

#配置服務(wù)端口
server:
  port: 8080
  servlet:
    encoding:
      charset: utf-8
      enabled: true
      force: true
    context-path: /cxh/
spring:
  #配置數(shù)據(jù)源
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/cxh_mall_service?characterEncoding=utf-8&useSSL=false
    username: root
    password: 123456
  #配置頁(yè)面
  mvc:
    view:
      prefix: /WEB-INF/page/
      suffix: .jsp
  #配置上傳文件大小
  servlet:
    multipart:
      max-file-size: 10MB
#配置Mybatis
mybatis:
  config-location: classpath:mybatis/mybatis-config.xml
  mapper-locations: classpath:mybatis/mapper/*.xml
  type-aliases-package: com.cxh.mall.entity

3.shiro配置:

import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;
@Configuration
public class ShiroConfig {
    @Bean
    @ConditionalOnMissingBean
    public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
        DefaultAdvisorAutoProxyCreator defaultAAP = new DefaultAdvisorAutoProxyCreator();
        defaultAAP.setProxyTargetClass(true);
        return defaultAAP;
    }
    //憑證匹配器, 密碼校驗(yàn)交給Shiro的SimpleAuthenticationInfo進(jìn)行處理
    public HashedCredentialsMatcher hashedCredentialsMatcher() {
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        hashedCredentialsMatcher.setHashAlgorithmName("MD5");//散列算法:這里使用MD5算法;
        hashedCredentialsMatcher.setHashIterations(2);//散列的次數(shù);
        return hashedCredentialsMatcher;
    //將自己的驗(yàn)證方式加入容器
    public LoginRealm myShiroRealm() {
        LoginRealm loginRealm = new LoginRealm();
        //加入密碼管理
        loginRealm.setCredentialsMatcher(hashedCredentialsMatcher());
        return loginRealm;
    //權(quán)限管理,配置主要是Realm的管理認(rèn)證
    public SecurityManager securityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(myShiroRealm());
        return securityManager;
    //Filter工廠,設(shè)置對(duì)應(yīng)的過(guò)濾條件和跳轉(zhuǎn)條件
    public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        Map<String, String> map = new HashMap<>();
        //登出
        map.put("/logout", "logout");
        //登錄
        map.put("/loginSubmit", "anon");
        //靜態(tài)文件包
        map.put("/res/**", "anon");
        //對(duì)所有用戶認(rèn)證
        map.put("/**", "authc");
        shiroFilterFactoryBean.setLoginUrl("/login");
        //首頁(yè)
        shiroFilterFactoryBean.setSuccessUrl("/index");
        //錯(cuò)誤頁(yè)面,認(rèn)證不通過(guò)跳轉(zhuǎn)
        shiroFilterFactoryBean.setUnauthorizedUrl("/error");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
        return shiroFilterFactoryBean;
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
}

4.shiro登錄驗(yàn)證授權(quán):

import com.cxh.mall.entity.SysUser;
import com.cxh.mall.service.SysMenuService;
import com.cxh.mall.service.SysRoleService;
import com.cxh.mall.service.SysUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.util.StringUtils;

import java.util.HashSet;
import java.util.Set;
public class LoginRealm extends AuthorizingRealm {
    @Autowired
    @Lazy
    private SysUserService sysUserService;
    private SysRoleService sysRoleService;
    private SysMenuService sysMenuService;
    /**
     * 授權(quán)
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
        String username = (String) arg0.getPrimaryPrincipal();
        SysUser sysUser = sysUserService.getUserByName(username);
        // 角色列表
        Set<String> roles = new HashSet<String>();
        // 功能列表
        Set<String> menus = new HashSet<String>();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        roles = sysRoleService.listByUser(sysUser.getId());
        menus = sysMenuService.listByUser(sysUser.getId());
        // 角色加入AuthorizationInfo認(rèn)證對(duì)象
        info.setRoles(roles);
        // 權(quán)限加入AuthorizationInfo認(rèn)證對(duì)象
        info.setStringPermissions(menus);
        return info;
    }
     * 登錄認(rèn)證
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        if (StringUtils.isEmpty(authenticationToken.getPrincipal())) {
            return null;
        }
        //獲取用戶信息
        String username = authenticationToken.getPrincipal().toString();
        if (username == null || username.length() == 0)
        {
        SysUser user = sysUserService.getUserByName(username);
        if (user == null)
            throw new UnknownAccountException(); //未知賬號(hào)
        //判斷賬號(hào)是否被鎖定,狀態(tài)(0:禁用;1:鎖定;2:?jiǎn)⒂茫?
        if(user.getStatus() == 0)
            throw new DisabledAccountException(); //帳號(hào)禁用
        if (user.getStatus() == 1)
            throw new LockedAccountException(); //帳號(hào)鎖定
        //鹽
        String salt = "123456";
        //驗(yàn)證
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                username, //用戶名
                user.getPassword(), //密碼
                ByteSource.Util.bytes(salt), //鹽
                getName() //realm name
        );
        return authenticationInfo;
    public static void main(String[] args) {
        String originalPassword = "123456"; //原始密碼
        String hashAlgorithmName = "MD5"; //加密方式
        int hashIterations = 2; //加密的次數(shù)
        //加密
        SimpleHash simpleHash = new SimpleHash(hashAlgorithmName, originalPassword, salt, hashIterations);
        String encryptionPassword = simpleHash.toString();
        //輸出加密密碼
        System.out.println(encryptionPassword);
}

5.登錄控制器:

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

@Controller
@Slf4j
public class LoginController {
    /**
     * 登錄頁(yè)面
     */
    @GetMapping(value={"/", "/login"})
    public String login(){
        return "admin/loginPage";
    }
     * 登錄操作
    @RequestMapping("/loginSubmit")
    public String login(String username, String password, ModelMap modelMap)
    {
        //參數(shù)驗(yàn)證
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password))
        {
            modelMap.addAttribute("message", "賬號(hào)密碼必填!");
            return "admin/loginPage";
        }
        //賬號(hào)密碼令牌
        AuthenticationToken token = new UsernamePasswordToken(username, password);
        //獲得當(dāng)前用戶到登錄對(duì)象,現(xiàn)在狀態(tài)為未認(rèn)證
        Subject subject = SecurityUtils.getSubject();
        try
            //將令牌傳到shiro提供的login方法驗(yàn)證,需要自定義realm
            subject.login(token);
            //沒(méi)有異常表示驗(yàn)證成功,進(jìn)入首頁(yè)
            return "admin/homePage";
        catch (IncorrectCredentialsException ice)
            modelMap.addAttribute("message", "用戶名或密碼不正確!");
        catch (UnknownAccountException uae)
            modelMap.addAttribute("message", "未知賬戶!");
        catch (LockedAccountException lae)
            modelMap.addAttribute("message", "賬戶被鎖定!");
        catch (DisabledAccountException dae)
            modelMap.addAttribute("message", "賬戶被禁用!");
        catch (ExcessiveAttemptsException eae)
            modelMap.addAttribute("message", "用戶名或密碼錯(cuò)誤次數(shù)太多!");
        catch (AuthenticationException ae)
            modelMap.addAttribute("message", "驗(yàn)證未通過(guò)!");
        catch (Exception e)
        //返回登錄頁(yè)
     * 登出操作
    @RequestMapping("/logout")
    public String logout()
        //登出清除緩存
        subject.logout();
        return "redirect:/login";
}

6.前端登錄頁(yè)面:

<div>
        <div><p>cxh電商平臺(tái)管理后臺(tái)</p></div>
        <div>
            <form name="loginForm" method="post" action="/cxh/loginSubmit" onsubmit="return SubmitLogin()" autocomplete="off">
                <input type="text" name="username" placeholder="用戶名"/>
                <input type="password" name="password" placeholder="密碼" autocomplete="on">
                <span>${message}</span>
                <input type="submit" value="登錄"/>
            </form>
        </div>
    </div>
//提交登錄
function SubmitLogin() {
    //判斷用戶名是否為空
    if (!loginForm.username.value) {
        alert("請(qǐng)輸入用戶姓名!");
        loginForm.username.focus();
        return false;
    }

    //判斷密碼是否為空
    if (!loginForm.password.value) {
        alert("請(qǐng)輸入登錄密碼!");
        loginForm.password.focus();
        return false;
    }
    return true;
}

上述內(nèi)容就是springboot如何整合shiro實(shí)現(xiàn)登錄驗(yàn)證授權(quán)的過(guò)程解析,你們學(xué)到知識(shí)或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識(shí)儲(chǔ)備,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI