shiro安全框架学习

shiro安全框架——初步学习

使用步骤:

导包

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

配置web.xml

<filter>
    <filter-name>shiroFilter</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    <init-param>
      <param-name>targetFilterLifecycle</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>shiroFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

创建一个Realm类

package com.qf.shiro.realm;

import com.qf.shiro.bean.TbUser;
import com.qf.shiro.mapper.UserMapper;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.Permission;
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 java.util.Collection;
import java.util.List;

/**
 * @author smj
 * @date 2020/1/13 - 19:13
 */
// Shiro中用来查询数据的类
public class MyRealm  extends AuthorizingRealm {
    @Autowired
    private UserMapper userMapper;

    /**
     * 授权:角色权限
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        // 此方法获取到的值取决于下面的方法doGetAuthenticationInfo返回的值
        // new SimpleAuthenticationInfo()中的第一个参数
        Object primaryPrincipal = principalCollection.getPrimaryPrincipal();
        String username = primaryPrincipal.toString();

        // 查询此用户的角色有哪些
        List<String> roleList = userMapper.queryRoleByName(username);

        // 查询此用户的权限有哪些
        List<String> permissionList = userMapper.queryPermissionByName(username);

        // AuthorizationInfo的具体实现类
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addRoles(roleList);
        simpleAuthorizationInfo.addStringPermissions(permissionList);

        // 将角色和权限的数据返回(交给SecurityManager来处理)
        return simpleAuthorizationInfo;
    }

    /**
     * 认证:登录
     * @param authenticationToken :用户传入的用户名和密码
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // UsernamePasswordToken 是AuthenticationToken的子类
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;

        // 获得用户传入的用户名
        String username = usernamePasswordToken.getUsername();

        TbUser tbUser = userMapper.queryUserInfoByName(username);

        // 查出来的user为空 说明没有这个用户名
        if (tbUser == null){
            throw new UnknownAccountException("username error");
        }

        // 用来加密的盐
        ByteSource byteSource = ByteSource.Util.bytes(tbUser.getUserSalt());

        // 返回 从数据库查出的用户的 用户名、密码、用来加密的盐、一个名称
        SimpleAuthenticationInfo myRealm = new SimpleAuthenticationInfo(tbUser.getUserName(), tbUser.getUserPassword(), byteSource, "myRealm");

        return myRealm;
    }
}

在spring.xml中配置shiro(新建了一个spring-shiro.xml,然后在spring.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--shiro结合spring管理java对象生命周期的一个类-->
    <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>

    <!--myRealm是用来访问数据库获得用户名和密码的-->
    <bean id="myRealm" class="com.qf.shiro.realm.MyRealm">
        <!--配置加密方式-->
        <property name="credentialsMatcher" ref="hashMatcher"/>
    </bean>

    <!--配置加密方式-->
    <bean id="hashMatcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
        <property name="hashAlgorithmName" value="MD5"/>
    </bean>

    <!--securityManager是匹配数据的类  DefaultSecurityManager是SecurityManager接口的具体实现类-->
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <property name="realm" ref="myRealm"/>
    </bean>

    <!--ShiroFilterFactoryBean是真正处理拦截的类-->
    <!--这里的id要和web.xml中的委派过滤器名称一致-->
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <property name="securityManager" ref="securityManager"/>
        <!--如果没有登录就跳转到denglu.jsp页面-->
        <property name="loginUrl" value="/denglu.jsp"/>
        <!--如果没有访问权限就跳转到unAuthorized.jsp页面-->
        <property name="unauthorizedUrl" value="/unAuthorized.jsp"/>

        <!--配置拦截规则-->
        <property name="filterChainDefinitions">
            <!--放行denglu.jsp和/shiro/login接口 其他的没有登录就拦截-->
            <value>
                /denglu.jsp=anon
                /shiro/login=anon
                /loginSuccess.jsp=anon
                /shiro/addUser=authc,roles[超级管理员]
                /addUser.jsp=authc,roles[超级管理员]
                /**=authc
            </value>
        </property>
    </bean>

</beans>

    <!--允许shiro的配置生效-->
    <!-- Enable Shiro Annotations for Spring-configured beans.  Only run after -->
    <!-- the lifecycleBeanProcessor has run: -->
    <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor"/>
    <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
        <property name="securityManager" ref="securityManager"/>
    </bean>

controller层传入用户名和密码

package com.qf.shiro.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;


/**
 * @author smj
 * @date 2020/1/13 - 19:32
 */
@Controller
@RequestMapping("shiro")
public class ShiroController {

    @RequestMapping("login")
    public String login(String username,String password){
        // 用来搜集用户名和密码交给SecurityManager的工具类
        Subject subject = SecurityUtils.getSubject();
        try {
            // 登录  如果没有出错就是登陆成功
            subject.login(new UsernamePasswordToken(username,password));
            return "/loginSuccess.jsp";
        }catch (Exception e){
            e.printStackTrace();
        }
        return "/loginError.jsp";

    }


   /**
    * @RequiresRoles(value = {"超级管理员","财务总监"},logical = Logical.OR)
    * 表示只要拥有“超级管理员”、“财务总监”两个角色中的一个就能访问此接口
    **/
    /**
     * @RequiresRoles({"超级管理员","财务总监"})
     * 表示必须同时拥有“超级管理员”和“财务总监”两个角色才能访问此接口
     */
    @RequestMapping("addUser")
    @RequiresRoles("超级管理员")
    public String addUser(){
        System.out.println("添加用户");
        return "/addUser.jsp";
    }

    /*给密码加盐*/
    @RequestMapping("salt")
    public void getSalt(){
        Md5Hash md5Hash = new Md5Hash("123456", "smj");
        String hex = md5Hash.toHex();
        System.out.println(hex);
    }
}


spring中的统一异常管理

只需要创建如下类 不需要其他配置

package com.qf.shiro.exception;

import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

/**
 * @author smj
 * @date 2020/1/14 - 19:58
 */
//统一异常管理
@ControllerAdvice
public class ExceptionHandlerController {

    /**
     * 所有出现UnauthorizedException异常的controller接口都执行以下异常处理机制
     * @return
     */
    @ExceptionHandler(UnauthorizedException.class)
    public String exception1(){
        return "unAuthorized.jsp";
    }
}

shiro的部分页面标签使用

<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2020/1/14
  Time: 19:14
  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>
<%--如果没有登录就会显示游客模式--%>
<shiro:guest>游客模式</shiro:guest>
<%--如果登录了就会显示欢迎您--%>
<shiro:authenticated>
    <h1>登录成功</h1>
    <shiro:principal/>,欢迎您回来!
</shiro:authenticated>
<%--如果拥有某权限 就会显示某权限的按钮--%>
<shiro:hasPermission name="增加用户">
    <button value="增加用户"/>
</shiro:hasPermission>
<shiro:hasPermission name="删除用户">
    <button value="删除用户"/>
</shiro:hasPermission>
<shiro:hasPermission name="修改用户">
    <button value="修改用户"/>
</shiro:hasPermission>
<shiro:hasPermission name="增加财务报表">
    <button value="增加财务报表"/>
</shiro:hasPermission>
<shiro:hasPermission name="修改财务报表">
    <button value="修改财务报表"/>
</shiro:hasPermission>
</body>
</html>

注意

角色权限管理如果使用注解方式:
首先要在spring-shiro.xml中配置让shiro的注解生效

<!--允许shiro的配置生效-->
    <!-- Enable Shiro Annotations for Spring-configured beans.  Only run after -->
    <!-- the lifecycleBeanProcessor has run: -->
    <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor"/>
    <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
        <property name="securityManager" ref="securityManager"/>
    </bean>

在要进行权限管理的方法上加如下注解:

@RequiresRoles("超级管理员")

以上注解表示只有"超级管理员"这个角色才可访问这个接口

@RequiresRoles( {"超级管理员","财务总监"})

以上注解表示必须同时拥有“超级管理员”和“财务总监”两个角色的用户才可以访问此接口

@RequiresRoles(value = {"超级管理员","财务总监"},logical = Logical.OR)

以上注解表示只要拥有“超级管理员”、“财务总监”两个角色中的一个就能访问此接口

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值