亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

springboot整合shiro實現(xiàn)登錄驗證授權的過程解析

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

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

1.添加依賴:

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

2.yml配置:

#配置服務端口
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
  #配置頁面
  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;
    }
    //憑證匹配器, 密碼校驗交給Shiro的SimpleAuthenticationInfo進行處理
    public HashedCredentialsMatcher hashedCredentialsMatcher() {
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        hashedCredentialsMatcher.setHashAlgorithmName("MD5");//散列算法:這里使用MD5算法;
        hashedCredentialsMatcher.setHashIterations(2);//散列的次數(shù);
        return hashedCredentialsMatcher;
    //將自己的驗證方式加入容器
    public LoginRealm myShiroRealm() {
        LoginRealm loginRealm = new LoginRealm();
        //加入密碼管理
        loginRealm.setCredentialsMatcher(hashedCredentialsMatcher());
        return loginRealm;
    //權限管理,配置主要是Realm的管理認證
    public SecurityManager securityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(myShiroRealm());
        return securityManager;
    //Filter工廠,設置對應的過濾條件和跳轉條件
    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");
        //對所有用戶認證
        map.put("/**", "authc");
        shiroFilterFactoryBean.setLoginUrl("/login");
        //首頁
        shiroFilterFactoryBean.setSuccessUrl("/index");
        //錯誤頁面,認證不通過跳轉
        shiroFilterFactoryBean.setUnauthorizedUrl("/error");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
        return shiroFilterFactoryBean;
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
}

4.shiro登錄驗證授權:

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;
    /**
     * 授權
     */
    @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認證對象
        info.setRoles(roles);
        // 權限加入AuthorizationInfo認證對象
        info.setStringPermissions(menus);
        return info;
    }
     * 登錄認證
    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(); //未知賬號
        //判斷賬號是否被鎖定,狀態(tài)(0:禁用;1:鎖定;2:啟用)
        if(user.getStatus() == 0)
            throw new DisabledAccountException(); //帳號禁用
        if (user.getStatus() == 1)
            throw new LockedAccountException(); //帳號鎖定
        //鹽
        String salt = "123456";
        //驗證
        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 {
    /**
     * 登錄頁面
     */
    @GetMapping(value={"/", "/login"})
    public String login(){
        return "admin/loginPage";
    }
     * 登錄操作
    @RequestMapping("/loginSubmit")
    public String login(String username, String password, ModelMap modelMap)
    {
        //參數(shù)驗證
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password))
        {
            modelMap.addAttribute("message", "賬號密碼必填!");
            return "admin/loginPage";
        }
        //賬號密碼令牌
        AuthenticationToken token = new UsernamePasswordToken(username, password);
        //獲得當前用戶到登錄對象,現(xiàn)在狀態(tài)為未認證
        Subject subject = SecurityUtils.getSubject();
        try
            //將令牌傳到shiro提供的login方法驗證,需要自定義realm
            subject.login(token);
            //沒有異常表示驗證成功,進入首頁
            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", "用戶名或密碼錯誤次數(shù)太多!");
        catch (AuthenticationException ae)
            modelMap.addAttribute("message", "驗證未通過!");
        catch (Exception e)
        //返回登錄頁
     * 登出操作
    @RequestMapping("/logout")
    public String logout()
        //登出清除緩存
        subject.logout();
        return "redirect:/login";
}

6.前端登錄頁面:

<div>
        <div><p>cxh電商平臺管理后臺</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("請輸入用戶姓名!");
        loginForm.username.focus();
        return false;
    }

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

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

相關文章

  • Java synchronize線程安全測試

    Java synchronize線程安全測試

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

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

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

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

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

    springmvc學習筆記-返回json的日期格式問題的解決方法

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

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

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

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

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

    Java中Maven Shade插件的具體使用

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

    Java的StringBuilder在高性能場景下的正確用法

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

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

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

    在SpringBoot中無縫整合Dubbo的實現(xiàn)過程

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

最新評論