shiro的使用入门

2024-09-02 14:48
文章标签 使用 入门 shiro

本文主要是介绍shiro的使用入门,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

    shiro是一个权限控制框架,因为项目需要自己看了看,在这里把所有学到的分享一下。shiro主要由AuthorizationInfo、AuthenticationInfo、Subject构成一个权限环境,doGetAuthenticationInfo方法是用户登录的使用调用的( subject.login(token);),doGetAuthorizationInfo方法是在用户进行权限验证的时候调用的(   boolean isOk=subject.isPermitted(url);)。

下面我们来看看一个真正的项目中使用shiro需要做哪些操作。

    1、配置web.xml文件

<!-- shiro 安全过滤器 -->

      <filter>  
        <filter-name>shiroFilter</filter-name>  
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>  
         <async-supported>true</async-supported>  
        <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> 

2、配置shiro.xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:util="http://www.springframework.org/schema/util"  
       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  
       http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">  
 
    <description>apache shiro配置</description>  
 
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">  
        <property name="securityManager" ref="securityManager"/>  
        <property name="loginUrl" value="/"/>  
        <property name="successUrl" value="/jsp/main"/>  
        <property name="unauthorizedUrl" value="/rest/page/401"/>  
        <property name="filterChainDefinitions">  
            <value>  
                <!-- 静态资源允许访问 -->  
                /app/** = anon  
                /login = anon  
                <!-- 登录页允许访问 -->  
                /rest/user/login = anon  
                /=anon
                <!-- 其他资源需要认证 -->  
                /** = authc  
            </value>  
        </property>  
    </bean>  
 
    <!-- 缓存管理器 使用Ehcache实现 -->  
   <bean id="shiroEhcacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">  
        <property name="cacheManagerConfigFile" value="classpath:ehcache-shiro.xml"/>  
    </bean>
 
    <!-- 会话DAO -->  
    <bean id="sessionDAO" class="org.apache.shiro.session.mgt.eis.MemorySessionDAO"/>  
 
    <!-- 会话管理器 -->  
    <bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">  
        <property name="sessionDAO" ref="sessionDAO"/>  
    </bean>  
 
    <!-- 安全管理器 -->  
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">  
        <property name="realms">  
            <list>  
                <ref bean="myRealms"/>  
            </list>  
        </property>  
        <!-- cacheManager,集合spring缓存工厂 -->  
        <!-- <property name="cacheManager" ref="shiroEhcacheManager" /> -->  
        <!-- <property name="sessionManager" ref="sessionManager" /> -->  
    </bean>  
      <bean id="myRealms" class="com.lintian.util.MyRealms"></bean>
    <!-- Shiro生命周期处理器 -->  
    <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>  
</beans> 
3、安全管理器MyRealms.java

package com.lintian.util;

import java.util.ArrayList;
import java.util.List;

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.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.lintian.entity.Permission;
import com.lintian.entity.Role;
import com.lintian.entity.User;
import com.lintian.service.UserService;
@Service
public class MyRealms extends AuthorizingRealm {
    @Autowired
    private UserService userService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //获取当前登录的用户名
                String account = (String) super.getAvailablePrincipal(principals);
                
                List<String> roles = new ArrayList<String>();  
                List<String> permissions = new ArrayList<String>();
                User user = userService.getByAccount(account);//获取用户
                if(user != null){
                    if (user.getRoles() != null && user.getRoles().size() > 0) {
                        for (Role role : user.getRoles()) {
                            roles.add(role.getRoleName());
                            if (role.getPermissions() != null && role.getPermissions().size() > 0) {
                                for (Permission pmss : role.getPermissions()) {
                                    if(!StringUtils.isEmpty(pmss.getPermission())){
                                        permissions.add(pmss.getPermission());
                                    }
                                }
                            }
                        }
                    }
                }else{
                    throw new AuthorizationException();
                }
                //给当前用户设置角色
                info.addRoles(roles);
                //给当前用户设置权限
                info.addStringPermissions(permissions);
                return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(
            AuthenticationToken authcToken) throws AuthenticationException {
        // TODO Auto-generated method stub
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
        User user = userService.getByAccount(token.getUsername());
        if (user != null) {
            return new SimpleAuthenticationInfo(user.getUserName(), user
                    .getUserPass(), getName());
        } else {
            return null;
        }
    }

}
4、测试控制器

package com.lintian.action;

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

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.mybatis.generator.ant.GeneratorAntTask;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.lintian.entity.User;
import com.lintian.service.UserService;

@Controller
public class TestAction {
    @Autowired
    private UserService userService;
    @RequestMapping("/login.do")
    public String login(){
        System.out.println("system is login...");
        return "test";
    }
    @RequestMapping("/login")
    public String login2(String userName,HttpServletRequest request){
        System.out.println("system is login2...");
         userName=request.getParameter("userName");
        User user=userService.getByAccount(userName);
        System.out.println(user.getUserName()+"========"+user.getUserPass());
        Subject subject = SecurityUtils.getSubject();     
        UsernamePasswordToken token=new UsernamePasswordToken(user.getUserName(),user.getUserPass());
        token.setRememberMe(true);
        subject.login(token);
        token.clear();
        
        request.setAttribute("user", user);
        return "main";
    }
    @RequestMapping(value="/user/insert")
    public String insert(String userName,String userPass,HttpServletRequest request,HttpServletResponse response){
        System.out.println("do insert method....");
        String url=request.getContextPath();
        String path=request.getServletPath();
        boolean isOk=checkPermission(path, request, response);
        if(isOk){
            return "user/list";
        }else{
            return "/permissionError";
        }
        
    }
    
    @RequestMapping(value="/logout")
    public String logout(HttpServletRequest request){
        Subject subject=SecurityUtils.getSubject();
        subject.logout();
        return "login";
    }
    @RequestMapping(value="/checkPerm")
    public boolean checkPermission(String url,HttpServletRequest request,HttpServletResponse response){
        Subject subject=SecurityUtils.getSubject();
        boolean isOk=subject.isPermitted(url);
        
        System.out.println(url+" is have premission: "+isOk);
        return isOk;
    }
    
  
    
}

以上代码是经过测试可用的。


这篇关于shiro的使用入门的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1130259

相关文章

JavaScript中的reduce方法执行过程、使用场景及进阶用法

《JavaScript中的reduce方法执行过程、使用场景及进阶用法》:本文主要介绍JavaScript中的reduce方法执行过程、使用场景及进阶用法的相关资料,reduce是JavaScri... 目录1. 什么是reduce2. reduce语法2.1 语法2.2 参数说明3. reduce执行过程

如何使用Java实现请求deepseek

《如何使用Java实现请求deepseek》这篇文章主要为大家详细介绍了如何使用Java实现请求deepseek功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1.deepseek的api创建2.Java实现请求deepseek2.1 pom文件2.2 json转化文件2.2

python使用fastapi实现多语言国际化的操作指南

《python使用fastapi实现多语言国际化的操作指南》本文介绍了使用Python和FastAPI实现多语言国际化的操作指南,包括多语言架构技术栈、翻译管理、前端本地化、语言切换机制以及常见陷阱和... 目录多语言国际化实现指南项目多语言架构技术栈目录结构翻译工作流1. 翻译数据存储2. 翻译生成脚本

C++ Primer 多维数组的使用

《C++Primer多维数组的使用》本文主要介绍了多维数组在C++语言中的定义、初始化、下标引用以及使用范围for语句处理多维数组的方法,具有一定的参考价值,感兴趣的可以了解一下... 目录多维数组多维数组的初始化多维数组的下标引用使用范围for语句处理多维数组指针和多维数组多维数组严格来说,C++语言没

在 Spring Boot 中使用 @Autowired和 @Bean注解的示例详解

《在SpringBoot中使用@Autowired和@Bean注解的示例详解》本文通过一个示例演示了如何在SpringBoot中使用@Autowired和@Bean注解进行依赖注入和Bean... 目录在 Spring Boot 中使用 @Autowired 和 @Bean 注解示例背景1. 定义 Stud

使用 sql-research-assistant进行 SQL 数据库研究的实战指南(代码实现演示)

《使用sql-research-assistant进行SQL数据库研究的实战指南(代码实现演示)》本文介绍了sql-research-assistant工具,该工具基于LangChain框架,集... 目录技术背景介绍核心原理解析代码实现演示安装和配置项目集成LangSmith 配置(可选)启动服务应用场景

使用Python快速实现链接转word文档

《使用Python快速实现链接转word文档》这篇文章主要为大家详细介绍了如何使用Python快速实现链接转word文档功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 演示代码展示from newspaper import Articlefrom docx import

oracle DBMS_SQL.PARSE的使用方法和示例

《oracleDBMS_SQL.PARSE的使用方法和示例》DBMS_SQL是Oracle数据库中的一个强大包,用于动态构建和执行SQL语句,DBMS_SQL.PARSE过程解析SQL语句或PL/S... 目录语法示例注意事项DBMS_SQL 是 oracle 数据库中的一个强大包,它允许动态地构建和执行

SpringBoot中使用 ThreadLocal 进行多线程上下文管理及注意事项小结

《SpringBoot中使用ThreadLocal进行多线程上下文管理及注意事项小结》本文详细介绍了ThreadLocal的原理、使用场景和示例代码,并在SpringBoot中使用ThreadLo... 目录前言技术积累1.什么是 ThreadLocal2. ThreadLocal 的原理2.1 线程隔离2

Python itertools中accumulate函数用法及使用运用详细讲解

《Pythonitertools中accumulate函数用法及使用运用详细讲解》:本文主要介绍Python的itertools库中的accumulate函数,该函数可以计算累积和或通过指定函数... 目录1.1前言:1.2定义:1.3衍生用法:1.3Leetcode的实际运用:总结 1.1前言:本文将详