springboot整合shiro实现登录验证授权的过程解析

springboot整合shiro实现登录验证授权,内容如下所示:

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:
  #配置数据源
  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);//散列的次数;
        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");
        //静态文件包
        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(); //未知账号
        //判断账号是否被锁定,状态(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; //加密的次数
        //加密
        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)
    {
        //参数验证
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password))
        {
            modelMap.addAttribute("message", "账号密码必填!");
            return "admin/loginPage";
        }
        //账号密码令牌
        AuthenticationToken token = new UsernamePasswordToken(username, password);
        //获得当前用户到登录对象,现在状态为未认证
        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", "用户名或密码错误次数太多!");
        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实现登录验证授权的文章就介绍到这了,更多相关springboot整合shiro登录验证内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • springboot整合shiro的过程详解

    目录 什么是 Shiro Shiro 架构 Shiro 架构图 Shiro 工作原理 Shiro 详细架构图 springboot 整合 shiro springboot 整合 shiro 思路 项目搭建 主要依赖 数据库表设计 实体类 自定义 Realm shiro 的配置类 ShiroFilterFactoryBean 过滤器链配置中的 url 匹配规则 ShiroFilterFactoryBean 过滤器 ShiroFilterFactoryBean 过滤器分类 前端页面 登录页面 log

  • springboot整合shiro多验证登录功能的实现(账号密码登录和使用手机验证码登录)

    1. 首先新建一个shiroConfig shiro的配置类,代码如下: @Configuration public class SpringShiroConfig { /** * @param realms 这儿使用接口集合是为了实现多验证登录时使用的 * @return */ @Bean public SecurityManager securityManager(Collection<Realm> realms) { DefaultWebSecurityManager sManager

  • SpringBoot整合Shiro框架,实现用户权限管理

    一.Shiro简介 核心角色 1)Subject:认证主体 代表当前系统的使用者,就是用户,在Shiro的认证中,认证主体通常就是userName和passWord,或者其他用户相关的唯一标识. 2)SecurityManager:安全管理器 Shiro架构中最核心的组件,通过它可以协调其他组件完成用户认证和授权.实际上,SecurityManager就是Shiro框架的控制器. 3)Realm:域对象 定义了访问数据的方式,用来连接不同的数据源,如:关系数据库,配置文件等等. 核心理念 Shi

  • springboot整合Shiro

    目录 什么是Shiro Shiro的三大核心概念 Shiro功能介绍 Springboot整合Shiro 导入依赖 javaConfig Realm Controller Shiro整合thymeleaf 导入依赖 HTML页面命名空间 使用举例 总结 什么是Shiro Apache Shiro是一个功能强大且易于使用的Java安全框架,它执行身份验证.授权.加密和会话管理.借助Shiro易于理解的API,您可以快速轻松地保护任何应用程序-从最小的移动应用程序到最大的web和企业应用程序. Sh

  • SpringBoot 整合 Shiro 密码登录与邮件验证码登录功能(多 Realm 认证)

    导入依赖(pom.xml) <!--整合Shiro安全框架--> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>1.4.0</version> </dependency> <!--集成jwt实现token认证--> <dependency

  • springboot整合shiro实现登录验证授权的过程解析

    springboot整合shiro实现登录验证授权,内容如下所示: 1.添加依赖: <!-- shiro --> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>1.7.1</version> </dependency> 2.yml配置: #配置服务端口 s

  • SpringBoot 整合 Shiro 密码登录的实现代码

    导入依赖(pom.xml) <!--整合Shiro安全框架--> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>1.4.0</version> </dependency> <!--集成jwt实现token认证--> <dependency

  • Springboot整合Shiro实现登录与权限校验详细解读

    目录 Springboot-cli 开发脚手架系列 简介 前言 1. 环境 2. 简介 3. Realm配置 4. 核心配置 5. 接口编写 6. 网页资源 7. 效果演示 8. 源码分享 Springboot-cli 开发脚手架系列 Springboot优雅的整合Shiro进行登录校验,权限认证(附源码下载) 简介 Springboo配置Shiro进行登录校验,权限认证,附demo演示. 前言 我们致力于让开发者快速搭建基础环境并让应用跑起来,提供使用示例供使用者参考,让初学者快速上手. 本博

  • SpringBoot整合Shiro实现登录认证的方法

    安全无处不在,趁着放假读了一下 Shiro 文档,并记录一下 Shiro 整合 Spring Boot 在数据库中根据角色控制访问权限 简介 Apache Shiro是一个功能强大.灵活的,开源的安全框架.它可以干净利落地处理身份验证.授权.企业会话管理和加密. 上图是 Shiro 的基本架构 Authentication(认证) 有时被称为"登录",用来证明用户是用户他们自己本人 Authorization(授权) 访问控制的过程,即确定"谁"访问"什么

  • 基于springboot实现整合shiro实现登录认证以及授权过程解析

    这篇文章主要介绍了基于springboot实现整合shiro实现登录认证以及授权过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 1.添加shiro的依赖 <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring-boot-web- starter</artifactId> <version&g

  • SpringBoot整合Shiro的代码详解

    shiro是一个权限框架,具体的使用可以查看其官网 http://shiro.apache.org/  它提供了很方便的权限认证和登录的功能. 而springboot作为一个开源框架,必然提供了和shiro整合的功能!接下来就用springboot结合springmvc,mybatis,整合shiro完成对于用户登录的判定和权限的验证. 1.准备数据库表结构 这里主要涉及到五张表:用户表,角色表(用户所拥有的角色),权限表(角色所涉及到的权限),用户-角色表(用户和角色是多对多的),角色-权限表

  • Springboot整合Shiro的代码实例

    这篇文章主要介绍了Springboot整合Shiro的代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 1.导入依赖 <!--shiro--> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>1.4.0</versio

  • Springboot 整合shiro实现权限控制的方法

    Author:jeffrey Date:2019-04-08 一.开发环境: 1.mysql - 5.7 2.navicat(mysql客户端管理工具) 3.idea 2017.2 4.jdk8 5.tomcat 8.5 6.springboot2.1.3 7.mybatis 3 8.shiro1.4 9.maven3.3.9 二.数据库设计 [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-CB46ByC1-1604249108144)(img/shiro01.pn

随机推荐