欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

【Java】Shiro权限框架在项目中的应用

程序员文章站 2022-06-08 10:46:10
...

同样,忙于校招,忙于提升自己,忙于项目。直接把项目中的代码拿来分享给大家。

一、配置ShiroFilter

  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
      classpath:spring/spring-*.xml,
      classpath:spring/spring-shiro.xml
    </param-value>
  </context-param>

  <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>
    <filter-name>characterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>

  <filter-mapping>
    <filter-name>shiroFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <filter-mapping>
    <filter-name>characterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>


  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring/spring-*.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

二、配置spring-shiro.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns="http://www.springframework.org/schema/beans"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
	   http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
	   http://www.springframework.org/schema/util
	   http://www.springframework.org/schema/util/spring-util.xsd">

    <!-- 配置shiro的过滤器工厂类,id- shiroFilter要和我们在web.xml中配置的过滤器一致 -->
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <!-- 调用我们配置的权限管理器 -->
        <property name="securityManager" ref="securityManager" />
        <!-- 配置我们的登录请求地址 -->
        <property name="loginUrl" value="/login" />
        <!-- 配置我们在登录页登录成功后的跳转地址,如果你访问的是非/login地址,则跳到您访问的地址,html已经有解析器 -->
        <property name="successUrl" value="/index" />

        <!-- TODO 需要403页面地址才可配置: 如果您请求的资源不再您的权限范围,则跳转到/403请求地址 -->
        <property name="unauthorizedUrl" value="/unauthorized" />
        <property name="filters">
            <util:map>
                <entry key="logout" value-ref="logoutFilter" />
            </util:map>
        </property>

        <!-- 权限配置 -->
        <property name="filterChainDefinitions">
            <value>
                <!-- anon表示此地址不需要任何权限即可访问 -->
                /**/**=anon
                /index=anon
                /login=anon
                /vcode=anon
                /icon/**=anon
                /js/**=anon
                /static/** = anon
                /lg=anon
                <!--所有的请求(除去配置的静态资源请求或请求地址为anon的请求)都要通过登录验证,如果未登录则跳到/login -->
                /** = authc
            </value>
        </property>
    </bean>

    <!-- TODO 需要403页面地址才可配置 -->
    <bean id="logoutFilter" class="org.apache.shiro.web.filter.authc.LogoutFilter">
        <property name="redirectUrl" value="/login" />
    </bean>

<!--    &lt;!&ndash; 凭证匹配器 &ndash;&gt;-->
<!--    <bean id="passwordMatcher" class="org.apache.shiro.authc.credential.PasswordMatcher">-->
<!--        <property name="passwordService" ref="passwordService" />-->
<!--    </bean>-->
<!--    <bean id="passwordService"-->
<!--          class="org.apache.shiro.authc.credential.DefaultPasswordService">-->
<!--        <property name="hashService" ref="hashService"></property>-->
<!--        <property name="hashFormat" ref="hashFormat"></property>-->
<!--        <property name="hashFormatFactory" ref="hashFormatFactory"></property>-->
<!--    </bean>-->
<!--    <bean id="hashService" class="org.apache.shiro.crypto.hash.DefaultHashService"></bean>-->
<!--    <bean id="hashFormat" class="org.apache.shiro.crypto.hash.format.Shiro1CryptFormat"></bean>-->
<!--    <bean id="hashFormatFactory"-->
<!--          class="org.apache.shiro.crypto.hash.format.DefaultHashFormatFactory">-->
<!--    </bean>-->

<!--    &lt;!&ndash; 会话ID生成器 &ndash;&gt;-->
<!--    <bean id="sessionIdGenerator"-->
<!--          class="org.apache.shiro.session.mgt.eis.JavaUuidSessionIdGenerator" />-->
<!--    &lt;!&ndash; 会话Cookie模板 maxAge=-1表示:关闭浏览器立即失效 &ndash;&gt;-->
<!--    <bean id="sessionIdCookie" class="org.apache.shiro.web.servlet.SimpleCookie">-->
<!--        <constructor-arg value="sid" />-->
<!--        <property name="httpOnly" value="true" />-->
<!--        <property name="maxAge" value="-1" />-->
<!--    </bean>-->
<!--    &lt;!&ndash; 会话DAO &ndash;&gt;-->
<!--    <bean id="sessionDAO"-->
<!--          class="org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO">-->
<!--        <property name="sessionIdGenerator" ref="sessionIdGenerator" />-->
<!--    </bean>-->
<!--    &lt;!&ndash; 会话验证调度器,每30分钟执行一次验证 ,设定会话超时及保存 &ndash;&gt;-->
<!--    <bean name="sessionValidationScheduler"-->
<!--          class="org.apache.shiro.session.mgt.ExecutorServiceSessionValidationScheduler">-->
<!--        <property name="interval" value="1800000" />-->
<!--        <property name="sessionManager" ref="sessionManager" />-->
<!--    </bean>-->
<!--    &lt;!&ndash; 会话管理器 &ndash;&gt;-->
<!--    <bean id="sessionManager"-->
<!--          class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">-->
<!--        &lt;!&ndash; 全局会话超时时间(单位毫秒),默认30分钟 &ndash;&gt;-->
<!--        <property name="globalSessionTimeout" value="1800000" />-->
<!--        <property name="deleteInvalidSessions" value="true" />-->
<!--        <property name="sessionValidationSchedulerEnabled" value="true" />-->
<!--        <property name="sessionValidationScheduler" ref="sessionValidationScheduler" />-->
<!--        <property name="sessionDAO" ref="sessionDAO" />-->
<!--        <property name="sessionIdCookieEnabled" value="true" />-->
<!--        <property name="sessionIdCookie" ref="sessionIdCookie" />-->
<!--    </bean>-->

    <!-- TODO  已解决 需要注册自定义的Realm,并把密码匹配器注入,使用注解的方式自动注解会无法正确匹配密码 已解决-->
    <bean id="userRealm" class="com.lanou.web.controller.shiro.UserRealm">
<!--        <property name="credentialsMatcher" ref="passwordMatcher"/>-->
        <property name="cachingEnabled" value="false"/>
    </bean>

    <!-- 安全管理器 作为filter的成员变量而出现-->
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <property name="realm" ref="userRealm" />
    </bean>
    <!-- 相当于调用SecurityUtils.setSecurityManager(securityManager) -->
    <bean
    class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
        <property name="staticMethod"
        value="org.apache.shiro.SecurityUtils.setSecurityManager" />
        <property name="arguments" ref="securityManager" />
    </bean>


    <bean id="cacheManager" class="org.apache.shiro.cache.MemoryConstrainedCacheManager" />
    <!-- 保证实现了Shiro内部lifecycle函数的bean执行 -->
    <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />
</beans>
  1. 编写Realm完成角色权限分配
import org.apache.shiro.SecurityUtils;
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.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;

public class UserRealm extends AuthorizingRealm {

    // 用户对应的角色信息与权限信息都保存在数据库中,通过UserService获取数据

    @Autowired
    public IUserService userService;

    /*
    * 这个方法是通过用户名查询到当前用户的角色与权限,然后将这些信息放在simpleAuthorizationInfo中
    *   即:提供用户信息返回权限信息
    * 登陆后来走这里,拿出该用户的权限和角色,放在info中。
    * */
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String username = (String)principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        // 根据用户名查询当前用户拥有的角色
        Set<TbRole> roles = userService.findRolesByUsername(username);
        Set<String> rolesName = new HashSet<String>();
        for (TbRole role:roles) {
            rolesName.add(role.getName());
        }

        // 根据用户名查询当前用户权限
        Set<TbPermission> permissions = userService.findPermissionByUsername(username);
        Set<String> permissionNames = new HashSet<String>();
        for (TbPermission permission : permissions) {
            permissionNames.add(String.valueOf(permission.getPermission()));
        }

        // 将权限名称提供给info
        simpleAuthorizationInfo.setStringPermissions(permissionNames);
        // 将角色名称提供给info
        simpleAuthorizationInfo.setRoles(rolesName);

        return simpleAuthorizationInfo;
    }


    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //鉴权
        String username = (String)authenticationToken.getPrincipal();
        TbUser user = null;
        SimpleAuthenticationInfo simpleAuthenticationInfo = null;
        try{
            user = userService.findByUsername(username);
        }catch(Exception e) {
            return null;
        }
        Subject subject = SecurityUtils.getSubject();
        subject.getSession().setAttribute("user",user);
        //第一个参数是传入的用户名(其实是一个principal参数,这个参数以为着用户所有认证信息的几个),第二个是密码,
        //TODO 此处的对象创建没有盐值加密过程,可以再构造里面看得到
        simpleAuthenticationInfo = new SimpleAuthenticationInfo(user.getUsername(),user.getPassword(),getName());
        return simpleAuthenticationInfo;
    }
}

四、使用注解完成角色权限控制

    //用户登录后同时获取用户的个人信息
    @RequestMapping(value = "/findInfo",method = RequestMethod.POST)
    @ResponseBody
    @RequiresRoles(value = {"student", "teacher"}, logical = Logical.OR)  //允许具有老师或学生身份的访问该接口
    public Result findMyInfo(String identifier){
        Subject subject = SecurityUtils.getSubject();
        TbUser user = (TbUser) subject.getSession().getAttribute("user");
        if (user != null) {
            if (identifier.equals("student")) {
                TbStudentInfo studentInfo = studentInfoService.findStudentInfo(user);
                return ResultGenerator.genSuccessResult(studentInfo);
            } else {
                TbTeacherInfo teacherInfo = teacherInfoService.findTeacherInfoById(user.getId());
                System.out.println(teacherInfo.toString());
                return ResultGenerator.genSuccessResult(teacherInfo);
            }
        } else {
            return ResultGenerator.genFailResult("未得到该用户信息,可能原因:未鉴权");
        }

    }