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

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

 更新時(shí)間:2022年01月26日 09:33:18   作者:灰太狼_cxh  
這篇文章主要介紹了springboot整合shiro實(shí)現(xiàn)登錄驗(yàn)證授權(quán),本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

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;
}

到此這篇關(guān)于springboot整合shiro實(shí)現(xiàn)登錄驗(yàn)證授權(quán)的文章就介紹到這了,更多相關(guān)springboot整合shiro登錄驗(yàn)證內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Java synchronize線程安全測(cè)試

    Java synchronize線程安全測(cè)試

    這篇文章主要介紹了Java synchronize線程安全測(cè)試,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-04-04
  • spring boot中配置hikari連接池屬性方式

    spring boot中配置hikari連接池屬性方式

    這篇文章主要介紹了spring boot中配置hikari連接池屬性方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-10-10
  • Spring?Boot?集成Redisson實(shí)現(xiàn)分布式鎖詳細(xì)案例

    Spring?Boot?集成Redisson實(shí)現(xiàn)分布式鎖詳細(xì)案例

    這篇文章主要介紹了Spring?Boot?集成Redisson實(shí)現(xiàn)分布式鎖詳細(xì)案例,文章圍繞主題展開(kāi)詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的朋友可以參考一下
    2022-08-08
  • springmvc學(xué)習(xí)筆記-返回json的日期格式問(wèn)題的解決方法

    springmvc學(xué)習(xí)筆記-返回json的日期格式問(wèn)題的解決方法

    本篇文章主要介紹了springmvc學(xué)習(xí)筆記-返回json的日期格式問(wèn)題的解決方法,解決了日期格式的輸出,有興趣的可以了解一下。
    2017-01-01
  • Java中的日期和時(shí)間類以及Calendar類用法詳解

    Java中的日期和時(shí)間類以及Calendar類用法詳解

    這篇文章主要介紹了Java中的日期和時(shí)間類以及Calendar類用法詳解,是Java入門(mén)學(xué)習(xí)中的基礎(chǔ)知識(shí),需要的朋友可以參考下
    2015-09-09
  • 基于SpringMVC攔截器實(shí)現(xiàn)接口耗時(shí)監(jiān)控功能

    基于SpringMVC攔截器實(shí)現(xiàn)接口耗時(shí)監(jiān)控功能

    本文呢主要介紹了基于SpringMVC攔截器實(shí)現(xiàn)的接口耗時(shí)監(jiān)控功能,統(tǒng)計(jì)接口的耗時(shí)情況屬于一個(gè)可以復(fù)用的功能點(diǎn),因此這里直接使用 SpringMVC的HandlerInterceptor攔截器來(lái)實(shí)現(xiàn),需要的朋友可以參考下
    2024-02-02
  • Java中Maven Shade插件的具體使用

    Java中Maven Shade插件的具體使用

    Maven Shade插件它可以幫助你在構(gòu)建項(xiàng)目時(shí)打包所有依賴項(xiàng),并將其打包到一個(gè)單獨(dú)的JAR文件中,本文就介紹一下Maven Shade插件的具體使用,具有一定參考價(jià)值,感興趣的可以了解一下
    2023-08-08
  • Java的StringBuilder在高性能場(chǎng)景下的正確用法

    Java的StringBuilder在高性能場(chǎng)景下的正確用法

    StringBuilder?對(duì)字符串的操作是直接改變字符串對(duì)象本身,而不是生成新的對(duì)象,所以新能開(kāi)銷小.與StringBuffer相比StringBuilder的性能略高,StringBuilder則沒(méi)有保證線程的安全,從而性能略高于StringBuffer,需要的朋友可以參考下
    2023-05-05
  • Java日期時(shí)間調(diào)整的幾種方式匯總

    Java日期時(shí)間調(diào)整的幾種方式匯總

    Calendar類是一個(gè)抽象類,在實(shí)際使用時(shí)實(shí)現(xiàn)特定的子類的對(duì)象,創(chuàng)建對(duì)象的過(guò)程對(duì)程序員來(lái)說(shuō)是透明的,只需要使用getInstance方法創(chuàng)建即可,這篇文章主要介紹了Java日期時(shí)間調(diào)整的幾種方式,需要的朋友可以參考下
    2023-05-05
  • 在SpringBoot中無(wú)縫整合Dubbo的實(shí)現(xiàn)過(guò)程

    在SpringBoot中無(wú)縫整合Dubbo的實(shí)現(xiàn)過(guò)程

    微服務(wù)架構(gòu)已經(jīng)成為現(xiàn)代應(yīng)用開(kāi)發(fā)的熱門(mén)趨勢(shì),而Dubbo作為一款強(qiáng)大的分布式服務(wù)框架,與Spring?Boot的結(jié)合是構(gòu)建高性能微服務(wù)應(yīng)用的理想選擇,本文將詳細(xì)介紹如何在SpringBoot中無(wú)縫整合Dubbo,需要的朋友可以參考下
    2024-01-01

最新評(píng)論