ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

shiro授权

2021-12-25 16:00:55  阅读:142  来源: 互联网

标签:return String userId user 授权 public shiro


目录

一:shiro授权角色、权限

第一步:在ShiroUserMapper.xml中新增内容

第二步:编写service层

第三步:重写自定义Realm中的授权方法

二:Shiro的注解式开发

一:常用注解介绍

二:注解的使用


 

所需的大概表设计:

一:shiro授权角色、权限

第一步:在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>
ShiroUserMapper
    public ShiroUser queryByName(@Param("userName") String userName);

    public Set<String> getRolesByUserId(Integer userId);

    public Set<String> getPersByUserId(Integer userId);

第二步:编写service层

ShiroUserService
    public ShiroUser queryByName(String userName);

    public Set<String> getRolesByUserId(Integer userId);

    public Set<String> getPersByUserId(Integer userId);
ShiroUserServiceImpl
    @Override
    public ShiroUser queryByName(String userName) {
        return shiroUserMapper.queryByName(userName);
    }

    @Override
    public Set<String> getRolesByUserId(Integer userId) {
        return shiroUserMapper.getRolesByUserId(userId);
    }

    @Override
    public Set<String> getPersByUserId(Integer userId) {
        return shiroUserMapper.getPersByUserId(userId);
    }

第三步:重写自定义Realm中的授权方法

MyRealm
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //重写认证操作
        System.out.println("身份认证...");
        //token就是controller中login请求,subject。login(token)
        String username = token.getPrincipal().toString();
        String password = token.getCredentials().toString();
        ShiroUser user = shiroUserService.queryByName(username);
//        拿到数据库中的用户信息,放入token凭证中,用于controler进行对比
        AuthenticationInfo info = new SimpleAuthenticationInfo(
                user.getUsername(),
                user.getPassword(),
                ByteSource.Util.bytes(user.getSalt()),
                this.getName()
        );
        return info;
    }

二:Shiro的注解式开发

一:常用注解介绍

  @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

二:注解的使用

第一步:编写Controller层

package com.sg.controller;

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.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;

@Controller
public class AnnotationController {
    @RequiresUser
    @RequestMapping("/passUser")
    public String passUser(HttpServletRequest request){
        //必须登录才能访问
        return "admin/addUser";
    }

    @RequiresRoles(value = {"1","4"},logical = Logical.AND)
    @RequestMapping("/passRole")
    public String passRole(HttpServletRequest request){
        //拥有xx角色才能访问
        return "admin/listUser";
    }

    @RequiresPermissions(value = {"user:update","user:view"},logical = Logical.OR)
    @RequestMapping("/passPer")
    public String passPer(HttpServletRequest request){
        //xx权限才能访问
        return "admin/resetPwd";
    }

    @RequestMapping("/unauthorized")
    public String unauthorized(){
        return "unauthorized";
    }
}

第二步:在Springmvc.xml中追加

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

第三步:编写测试代码

<%--
  Created by IntelliJ IDEA.
  User: T440s
  Date: 2021/12/19
  Time: 15:51
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<ul>
    shiro注解
    <li>
        <a href="${pageContext.request.contextPath}/passUser">用户认证</a>
    </li>
    <li>
        <a href="${pageContext.request.contextPath}/passRole">角色</a>
    </li>
    <li>
        <a href="${pageContext.request.contextPath}/passPer">权限认证</a>
    </li>
</ul>
</body>
</html>

今天就到这了,拜拜了各位!!!

标签:return,String,userId,user,授权,public,shiro
来源: https://blog.csdn.net/A2895922320/article/details/122113515

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有