Shiro授权-SSM

shiro与SSM整合之授权和注解式开发 文章目录1、shiro授权角色、权限权限表设计图:ShiroUserMapper:ShiroUserMapper.xml:MyRealm:2、Shiro的注解式开发常用注解介绍:ShiroUserController:在springmvc-servlet.xml添加:jsp中添加:测试: 1、shiro授权角色、权限 权限表设计图: ShiroUserMapper: Set<String&... 阅读详情

数据库的表的权限设计图设计
在这里插入图片描述

我们需要根据用户id获取他的角色id(role)和权限(pers),所以需要在ShiroUserMapper写两个查询的方法。

ShiroUserMapper

/**
     * 查询角色id
     * @param userid
     * @return
     */
    Set<String> getRolesByUserId(@Param("userid") Integer userid);

    /**
     * 查询权限id
     * @param userid
     * @return
     */
    Set<String> getPersByUserId(@Param("userid") Integer userid);


ShiroUserMapper.xml

<select id="getRolesByUserId" resultType="java.lang.String" parameterType="java.lang.Integer">
  select r.roleid from t_shiro_user u,t_shiro_user_role ur,t_shiro_role r
    where u.userid = ur.userid and ur.roleid = r.roleid
    and u.userid = #{userid}
</select>
<select id="getPersByUserId" resultType="java.lang.String" parameterType="java.lang.Integer">
  select p.permission from t_shiro_user u,t_shiro_user_role ur,t_shiro_role_permission rp,t_shiro_permission p
  where u.userid = ur.userid and ur.roleid = rp.roleid and rp.perid = p.perid
  and u.userid = #{userid}
</select>

ShiroUserService

package com.pyx.service;

import com.pyx.model.ShiroUser;
import org.apache.ibatis.annotations.Param;

import java.util.Set;

public interface ShiroUserService {
    ShiroUser queryByName( String uname);

    int insert(ShiroUser record);

    Set<String> getRolesByUserId(Integer userid);

    Set<String> getPersByUserId(Integer userid);
}

MyRealm

package com.pyx.shiro;

import com.pyx.model.ShiroUser;
import com.pyx.service.ShiroUserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
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.stereotype.Component;

import java.util.Set;

public class MyRealm extends AuthorizingRealm {
    private ShiroUserService shiroUserService;

    public ShiroUserService getShiroUserService() {
        return shiroUserService;
    }

    public void setShiroUserService(ShiroUserService shiroUserService) {
        this.shiroUserService = shiroUserService;
    }

    /**
     * 授权的方法
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String uname=principalCollection.getPrimaryPrincipal().toString();
        ShiroUser shiroUser = this.shiroUserService.queryByName(uname);
        Set<String> persByUserId = this.shiroUserService.getPersByUserId(shiroUser.getUserid());
        Set<String> rolesByUserId = this.shiroUserService.getRolesByUserId(shiroUser.getUserid());
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        info.setRoles(rolesByUserId);
        info.setStringPermissions(persByUserId);
        return info;
    }

    /**
     * 身份认证的方法
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String uname=authenticationToken.getPrincipal().toString();
        String pwd=authenticationToken.getCredentials().toString();
        ShiroUser shiroUser=shiroUserService.queryByName(uname);

        AuthenticationInfo info=new SimpleAuthenticationInfo(
            shiroUser.getUsername(),
                shiroUser.getPassword(),
                ByteSource.Util.bytes(shiroUser.getSalt()),
                this.getName()
        );
        return info;
    }
}


常用注解

@RequiresAuthenthentication:表示当前Subject已经通过login进行身份验证;即
Subject.isAuthenticated()返回 true
@RequiresUser:表示当前Subject已经身份验证或者通过记住我登录的
@RequiresGuest:表示当前Subject没有身份验证或者通过记住我登录过,即是游客身份
@RequiresRoles(value = {“admin”,“user”},logical =
Logical.AND):表示当前Subject需要角色admin和user @RequiresPermissions(value =
{“user:delete”,“user:b”},logical =
Logical.OR):表示当前Subject需要权限user:delete或者user:b

Springmvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
      http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
    <!-- 通过context:component-scan元素扫描指定包下的控制器-->
    <!--1) 扫描com.javaxl.zf及子子孙孙包下的控制器(扫描范围过大,耗时)-->
    <aop:aspectj-autoproxy/>
    <context:component-scan base-package="com.pyx"/>

    <!--2) 此标签默认注册DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapter -->
    <!--两个bean,这两个bean是spring MVC为@Controllers分发请求所必须的。并提供了数据绑定支持,-->
    <!--@NumberFormatannotation支持,@DateTimeFormat支持,@Valid支持,读写XML的支持(JAXB),读写JSON的支持(Jackson)-->
    <mvc:annotation-driven></mvc:annotation-driven>

    <!--3) ViewResolver -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- viewClass需要在pom中引入两个包:standard.jar and jstl.jar -->
        <property name="viewClass"
                  value="org.springframework.web.servlet.view.JstlView"></property>
        <property name="prefix" value="/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 必须和用户JSP 的pageEncoding属性一致,以便正确解析表单的内容 -->
        <property name="defaultEncoding" value="UTF-8"></property>
        <!-- 文件最大大小(字节) 1024*1024*50=50M-->
        <property name="maxUploadSize" value="52428800"></property>
        <!--resolveLazily属性启用是为了推迟文件解析,以便捕获文件大小异常-->
        <property name="resolveLazily" value="true"/>
    </bean>

    <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
          depends-on="lifecycleBeanPostProcessor">
        <property name="proxyTargetClass" value="true"></property>
    </bean>
    <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
        <property name="securityManager" ref="securityManager"/>
    </bean>

    <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="exceptionMappings">
            <props>
                <prop key="org.apache.shiro.authz.UnauthorizedException">
                    unauthorized
                </prop>
            </props>
        </property>
        <property name="defaultErrorView" value="unauthorized"/>
    </bean>

    <!--4) 单独处理图片、样式、js等资源 -->
    <!--<mvc:resources location="/css/" mapping="/css/**"/>-->
    <!--<mvc:resources location="/images/" mapping="/images/**"/>-->
    <!--<mvc:resources location="/js/" mapping="/js/**"/>-->
    <mvc:resources location="/static/" mapping="/static/**"/>
</beans>

ShiroUserController

package com.pyx.controller;

import com.pyx.model.ShiroUser;
import com.pyx.service.ShiroUserService;
import com.pyx.util.PasswordHelper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
public class ShiroUserController {
    @Autowired
    private ShiroUserService shiroUserService;

    @RequestMapping("login")
    public String login(HttpServletRequest req){
        Subject subject = SecurityUtils.getSubject();
        String uname = req.getParameter("username");
        String pwd = req.getParameter("password");
        UsernamePasswordToken token = new UsernamePasswordToken(uname,pwd);

        try {
//            这里会跳转到MyRealm中的认证方法
            subject.login(token);
            req.getSession().setAttribute("username",uname);
            return "main";
        }catch (Exception e){
            req.setAttribute("message","用户名密码错误");
            return "login";
        }
    }

    @RequestMapping("logout")
    public String logout(HttpServletRequest req){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:/login.jsp";
    }


    @RequestMapping("/register")
    public String register(HttpServletRequest req, HttpServletResponse resp){
        String uname = req.getParameter("username");
        String pwd = req.getParameter("password");
        String salt = PasswordHelper.createSalt();
        String credentials = PasswordHelper.createCredentials(pwd, salt);

        ShiroUser shiroUser=new ShiroUser();
        shiroUser.setUsername(uname);
        shiroUser.setPassword(credentials);
        shiroUser.setSalt(salt);
        int insert = shiroUserService.insert(shiroUser);
        if(insert>0){
            req.setAttribute("message","注册成功");
            return "login";
        }
        else{
            req.setAttribute("message","注册失败");
            return "register";
        }
    }

    @RequiresUser
    @ResponseBody
    @RequestMapping("passUser")
    public String passUser(){
        return "用户认证访问成功!!!";
    }
    @RequiresRoles(value = {"2"} ,logical = Logical.AND)
    @ResponseBody
    @RequestMapping("passRole")
    public String passRole(){
        return "角色访问成功!!!";
    }
    @RequiresPermissions(value = {"user:update","user:load"},logical = Logical.AND)
    @ResponseBody
    @RequestMapping("passPer")
    public String passPer(){
        return "权限访问成功!!!";
    }


}

Shiro教程7(整合SSM项目-授权) 授权原理分析 首先授权必须是在认证通过之后才会执行的操作 之前我们在Shiro教程4(授权操作)该教程中讲过,获取权限我们是通过如下方法实现的 那么在自定义Realm中授权是怎么实现的呢? 我们跟踪代码来看 首先从 hasRole()方法来看。 到此我们发现要对用户授权的话,我们只需要在定义Realm的doGetAuthorizationInfo方法中来授权。 授权具体实现 授权 /**... 阅读详情

相关推荐

【接口自动化测试】cookie绕过验证码自动登录?(保持登录状态)

在编写接口自动化测试用例或其他脚本的过程中,经常会遇到需要绕过用户名/密码或验证码登录,去请求接口的情况,一是因为有时验证码会比较复杂,比如有些图形验证码,难以通过接口的方式去处理;再者,每次请求接口前如果都需要先去登录一次,这样不仅效率低,还耗费资源。 有些网站是使用cookie辨别用户身份的,此时我们便可以先登录一次,拿到登录成功后的cookie,后续请求时在请求头中加入该cookie,便可保持登录状态直接请求。

weixin_67553250的博客 2069

Shiro授权

1、shiro授权角色、权限 2、Shiro的注解式开发 授权 <select id="getRolesByUserId" resultType="java.lang.String" parameterType="java.lang.Integer"> select r.roleid from t_shiro_user u,t_shiro_user_role ur,t_shir...

qq_44982547的博客 226

主流双目相机技术参数横向评测:从ZED到国产新锐

本文对主流双目相机技术参数进行了横向评测,涵盖ZED、Bumblebee等国际品牌及国产新锐产品。详细分析了分辨率、帧率、视场角等关键参数,并针对机器人导航、AR/VR交互、工业检测等场景提供选型建议。特别推荐ZED相机在科研领域的成熟应用,以及国产方案在长基线设计和主动双目技术上的创新突破。

weixin_33670786的博客 318

shiro 不完全学习笔记-----------1

一.shiro 简介                   shiro是apache的一个开源的安全框架,大体功能:认证,授权,企业会话管理,安全加密,缓存管理                   shiro和springScurity的比较                            简单                                               复杂 ...

小张同学的博客 305

ArcGIS Pro样式导入全攻略:从.style到.stylx的完整转换流程(附常见问题解决)

本文详细解析了ArcGIS Pro中从旧版.style文件导入并转换为新版.stylx格式的完整流程。针对用户在迁移过程中常见的样式库为空、符号匹配失败、显示异常等问题,提供了清晰的排查思路与解决方案,帮助用户高效完成样式库的升级与迁移,确保制图工作的连续性。

raspberrypi5的博客 515

全国大学生软件测试大赛Web应用测试(二)Selenium功能测试环境配置

全国大学生软件测试大赛Web应用测试(二)Selenium功能测试环境配置指南配置JAVA配置mooctest配置ChromeDriver配置SeleniumSelenium的使用 环境配置指南 配置JAVA 首先进入JDK8官方安装地址 然后找到Windows 64位 jdk8 点击下载(这里下载需要登录Orcale 账户) 下载后JDK的安装根据提示进行,还有安装JDK的时候也会安装JRE,一并安装就可以了。 安装JDK,安装过程中可以自定义安装目录等信息,例如我们选择安装目录为 D:\java\jav

Kennen0_0的博客 9606

SpringMVC+Shiro权限管理

博文目录 权限的简单描述实例表结构及内容及POJOShiro-pom.xmlShiro-web.xmlShiro-MyShiro-权限认证,登录认证层Shiro-applicationContext-shiro.xmlHomeController三个JSP文件  什么是权限呢?举个简单的例子: 我有一个论坛,注册的用户分为normal用户,manager用户。 对论坛的帖子的操

LzwGlory的专栏 2613

智能驾驶感知模块的测试评估方法(上)

对于智能驾驶系统而言,感知模块是开发难度最大、投入资源最多的核心部分。在智能驾驶开发团队内部,感知模块需要独立进行评测才能及早发现潜在缺陷或判断性能是否有改进。随着近几年BEV、OCC、E2E等新技术方案被越来越多企业应用,感知的评测变得越来越艰难,效率也变得越来越低下。本文作者基于在智驾测试行业多年经验,试图总结感知评测的基本规律和效率提升方法,以供读者一些启发。

vincent_321的博客 2559

实战-Shiro安全框架(二)权限控制

  上一篇讲解了shiro的认证流程以及实现。这一篇,笔者要详细讲解shiro的另一重要部分就是权限控制,简称授权。   授权流程跟认证流程很相似,大致过程为当前用户subject调用isPermitted*/hasRole* 接口时,将会委派给security manager,security manager委派给Authorizer(授权器)。比如调用的是isPermitted("user:...

啊杰的博客 824

Codex 100个真实案例 - 用AI自动生成API测试用例(接口测试全覆盖)

API 测试是保障后端质量的关键环节,但手写测试用例既枯燥又容易遗漏。本案例将展示如何用 Codex 从 Swagger/OpenAPI 规范文档自动生成 pytest 测试用例——包括正常流程测试、边界值测试、异常参数测试、性能压力测试,还能自动生成 Mock 数据和精美的 HTML 测试报告。全程自然语言驱动,让 API 测试覆盖率从 0 飙到 90%+!

yueyeguzhuo的专栏 270

【UG\NX二次开发】使用内部函数展开和折叠工序导航器

NX二次开发-群精选」专栏收录了那些曾散落在聊天对话框里的精彩的知识分享,这都是被遗落的宝贵财富。让我们一起向大佬学习,充满激情地进步,不断超越自己。底部联系方式,欢迎您加入一起交流。​下次一定。

王牌飞行员_里海的博客 819

权限管理:shiro

图一: shiro整体架构功能 图二: shiro架构API实现方式 @DependsOn(value="springUtils") @Configuration public class ShiroCoreConfig { @Autowired private RedisProperties redisParam; public static final String...

weixin_38289303的博客 258

2万字长文:海豚调度器(DolphinScheduler)面试题深入了解

DAG图(有向无环图)是海豚调度器中表示工作流任务依赖关系的一种方式。在DolphinScheduler中,每个任务是一个节点,任务之间的依赖关系通过有向边连接这些节点来表示。无环:保证了工作流的执行顺序是确定的,避免了无限循环的问题。有向:箭头指示了任务的执行方向,即上一个任务的输出可以作为下一个任务的输入。依赖表示:通过图形化界面,用户可以通过拖拽连接线来定义任务之间的先后顺序和依赖关系。并行处理:DAG图可以表示出任务的并行关系,允许多个任务在没有直接依赖关系的情况下同时执行。条件分支。

大模型大数据攻城狮的专栏 1329

Shiro授权之SSM

1.添加角色和权限的授权方法 //根据username查询该用户的所有角色,用于角色验证 Set<String> findRoles(String username); //根据username查询他所拥有的权限信息,用于权限判断 Set<String> findPermissions(String username); 编写方法 1.根据username获取用户对应的角色 2.根据username获取用户对应的角色权限 实现方法 ...

m0_67596612的博客 658

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

shiro授权SSM

shiro授权SSM 授权 1.添加角色和权限的授权方法 //根据username查询该用户的所有角色,用于角色验证 Set findRoles(String username); //根据username查询他所拥有的权限信息,用于权限判断 Set findPermissions(String username); 在ShiroUserMapper.xml中新增内容: <select id...

hao_dream_xi的博客 321

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

shiro授权-SSM

1.添加角色和权限的授权方法 //根据username查询该用户的所有角色,用于角色验证 Set<String> findRoles(String username); //根据username查询他所拥有的权限信息,用于权限判断 Set<String> findPermissions(String username); 2.自定义Realm配置Shiro授权认证 1) 获取验证身份(用户名) 2) 根据身份(用户名)获取角色和权限信息 3) ...

m0_67476502的博客 160

SIMATIC S7-1200, S7-1500 PID 控制[手册]

SIMATIC S7-1200, S7-1500 PID 控制[手册]

SSM整合Shiro-授权案例

SSM整合Shiro-授权案例 接着上一篇登录案例,今天写一篇授权案例,博客结尾有shiro和ssm整合的一整个小案例,完成了登录、授权、缓存和session管理以及RememberMe功能。有需要的小伙伴下载,谢谢。 下面上代码,代码接着上一篇中的修改,我这里主要是授权改动的代码,shiro进行授权是两种方式注解和拦截器,我这里方便起见,使用的是注解。 修改自定义Realm //授权 ...

java小白的博客 468

Shiro之 SSM 授权

一、简介 SSM 项目整合Shiro 访问需要相关角色、许可的操作可以使用Filter 配置,但是使用Filter 非常的不灵活,请繁琐;Shiro 也提供了使用注解配置相关角色、许可的访问控制。 该授权操作将基于笔者 ssm 整合Shiro实现用户认证 项目, 二、项目修改 1.pom.xml 添加如下依赖: <dependency> <groupId>org.a...

Zllvincent的博客 8401

Shiro+SSM整合,认证授权

   环境 :     Shiro+SSM整合基于你已经拥有一个可运行的ssm环境,jar包管理这里使用的Maven。   主体 :    1. 导入shiro相关jar包    2. web.xml配置shiro的代理过滤器,shiro的入口,相当于建立起servlet与shiro的联系    3. 配置shiro的xml文件    步骤 :    1. pom.xml导入相关jar包     ...

hans的博客 1万+

shiro+ssm授权方式之xml文件授权

shiro+ssm给请求地址授权的方式有两种: 一是通过xml文件授权 二是通过注解方式授权

灵魂和肉体总要有一个在路上 364

SSM集成Shiro并完成认证和授权

一、准备工作 在进行ssm集成Shiro之前,需要准备相关的数据库表结构。如:用户表,角色表,权限表,用户与角色关系表,角色与权限关系表。 并且准备好相关的实体类,以及Mapper和Mapper的映射xml文件,还有进行认证的自定义Realm。 二、application-Shrio.xml文件的相关配置 在此,将shiro的配置内容与Spring的配置内容分开进行配置。 <beans xm...

qq_44193036的博客 361

Shiro与SSM集成实现用户认证和授权

Shiro实现用户认证 在 shiro 中,用户需要提供principals (身份)和credentials(凭证)给shiro,从而应用能验证用户身份。身份即帐号/凭证即密码

weixin_64987028的博客 376

shiro-----Shiro与SSM集成实现用户认证和授权

Shiro实现用户认证 在 shiro 中,用户需要提供principals (身份)和credentials(凭证)给shiro,从而应用能验证用户身份。身份即帐号/凭证即密码 认证流程 Shrio实现登录(盐加密)认证 导入Shrio与Spring及springMVC相关依赖 <!-- shiro核心包 --> <dependency> <groupId>org.apache.shiro</groupId...

鑫709的博客 1030

SSM+Shiro+用户登录授权

SSM与整合Shiro进行整合实现用户登录验证及权限分配 在前面的学习过程中,已经学习了 Shiro的一些基本组件以及如何利用Shiro进行权限控制。下面学习用目前比较主流的SSM框架来整合Shiro框架,将我们前面学习的一些基本知识运用到实际项目之中。由于本人初学,内容可能比较粗浅,后期进行深入理解后会细化,SSM项目的搭建过程这里不再叙述,可查阅其他人教程学习,可能有时间也会进行回顾记录。 为方便对下述内容进行理解,先画了一个流程图进行辅助 第一步项目配置文件(项目常规操作) 1.spring-con

qq_46416934的博客 375
上一篇: shiro入门
下一篇: git
P_YUX
博客等级 码龄7年 3粉丝 66原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值