• shiro的ssm集成和简单的开发尝试


     配置web.xml

    <!-- 配置shiro的集成开始 -->
        <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>
            <init-param>
                <!-- 这里面的shiroFilter必须和application-shiro.xml里面的
                <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean" >id 一样 -->
                <param-name>targetBeanName</param-name>
                <param-value>shiroFilter</param-value>
            </init-param>
        </filter>
        <filter-mapping>
            <filter-name>shiroFilter</filter-name>
            <servlet-name>springmvc</servlet-name>
        </filter-mapping>
    
        <!-- 配置shiro的集成结束 -->

    创建application-shiro.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"
        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.xsd">
    
        <!-- 声明凭证匹配器 -->
        <bean id="credentialsMatcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
            <property name="hashAlgorithmName" value="md5"></property>
            <property name="hashIterations" value="2"></property>
        </bean>
    
        <!-- 声明userRealm -->
        <bean id="userRealm" class="com.sxt.realm.UserRealm">
            <!-- 注入凭证匹配器 -->
            <property name="credentialsMatcher" ref="credentialsMatcher"></property>
        </bean>
    
        <!-- 配置SecurityManager -->
        <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
            <!-- 注入realm -->
            <property name="realm" ref="userRealm"></property>    
        </bean>
        
        <!-- 配置shiro的过滤器  这里面的id必须和web.xml里面的配置一样 -->
        <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean" >
            <!-- 注入安全管理器 -->
            <property name="securityManager" ref="securityManager"></property>
            <!-- 注入未登陆的跳转页面 默认的是webapp/login.jsp-->
            <property name="loginUrl" value="/index.jsp"></property>
            <!-- 注入未授权的访问页面 -->
            <property name="unauthorizedUrl" value="/unauthorized.jsp"></property>
            <!-- 配置过滤器链 -->
            <property name="filterChainDefinitions">
                <value>
                    <!-- 放行index.jsp -->
                    /index.jsp*=anon  
                    <!-- 放行跳转到登陆页面的路径 -->
                    /login/toLogin*=anon
                    <!-- 放行登陆的请求 -->
                    /login/login*=anon
                    <!-- 设置登出的路径 -->
                    /login/logout*=logout
                    <!-- 设置其它路径全部拦截 -->   
                    /**=authc 
                </value>
            </property>
            
        </bean>
    
    </beans>
    com.sxt.realm.UserRealm 类
    public class UserRealm extends AuthorizingRealm {
    
        @Autowired
        private UserService userService;
        @Autowired
        private RoleService roleService;
        @Autowired
        private PermissionService permissionService;
        
        
        @Override
        public String getName() {
            return this.getClass().getSimpleName();
        }
    
        /**
         * 认证
         */
        @Override
        protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
            String username = token.getPrincipal().toString();
            // 根据用户名查询用户
            User user = this.userService.queryUserByUserName(username);
            if (null != user) {
                //查询角色
                List<String> roles = this.roleService.queryRolesByUserId(user.getUserid());
                //查询权限
                List<String> permissions = this.permissionService.queryPermissionByUserId(user.getUserid());
                //构造ActiverUser
                ActivierUser activierUser=new ActivierUser(user, roles, permissions);
                //创建盐
                ByteSource credentialsSalt=ByteSource.Util.bytes(user.getUsername()+user.getAddress());
                SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(activierUser, user.getUserpwd(), credentialsSalt, this.getName());
                return info;
            } else {
                return null;
            }
        }
    
        /**
         * 授权
         */
        @Override
        protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
            ActivierUser activierUser = (ActivierUser) principals.getPrimaryPrincipal();
            SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
            
            List<String> roles = activierUser.getRoles();
            List<String> permissions = activierUser.getPermissions();
            if(null!=roles&&roles.size()>0) {
                info.addRoles(roles);
            }
            if(null!=permissions&&permissions.size()>0) {
                info.addStringPermissions(permissions);
            }
            return info;
        }
    
    }
    User权限和角色类集合
    public class ActivierUser {
    
        private User user;
        private List<String> roles;
    
        private List<String> permissions;
        
        public ActivierUser() {
            // TODO Auto-generated constructor stub
        }
    
        public ActivierUser(User user, List<String> roles, List<String> permissions) {
            super();
            this.user = user;
            this.roles = roles;
            this.permissions = permissions;
        }

    UserRealm 类的使用

    public class UserRealm extends AuthorizingRealm {
    
        @Autowired
        private UserService userService;
        @Autowired
        private RoleService roleService;
        @Autowired
        private PermissionService permissionService;
        
        
        @Override
        public String getName() {
            return this.getClass().getSimpleName();
        }
    
        /**
         * 认证
         */
        @Override
        protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
            String username = token.getPrincipal().toString();
            System.out.println(token.getPrincipal()+"---账号名");
            System.out.println(token.getCredentials()+"--密码");
            // 根据用户名查询用户
            User user = this.userService.queryUserByUserName(username);
            if (null != user) {
                //查询角色
                List<String> roles = this.roleService.queryRolesByUserId(user.getUserid());
                //查询权限
                List<String> permissions = this.permissionService.queryPermissionByUserId(user.getUserid());
                //构造ActiverUser
                ActivierUser activierUser=new ActivierUser(user, roles, permissions);
                //创建盐
                ByteSource credentialsSalt=ByteSource.Util.bytes(user.getUsername()+user.getAddress());
                SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(activierUser, user.getUserpwd(), credentialsSalt, this.getName());
                return info;
            } else {
                return null;
            }
        }
    
        /**
         * 授权
         */
        @Override
        protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
            ActivierUser activierUser = (ActivierUser) principals.getPrimaryPrincipal();
            SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
            
            List<String> roles = activierUser.getRoles();
            List<String> permissions = activierUser.getPermissions();
            if(null!=roles&&roles.size()>0) {
                info.addRoles(roles);
            }
            if(null!=permissions&&permissions.size()>0) {
                info.addStringPermissions(permissions);
            }
            return info;
        }
    
    }

    登录请求

    @RequestMapping("login")
    @Controller
    public class LoginController {
        
        /**
         * 跳转到登陆页面
         */
        @RequestMapping("toLogin")
        public String toLogin() {
            return "login";
        }
        
        
        /**
         * 做登陆
         */
        @RequestMapping("login")
        public String login(String username,String pwd,HttpSession session) {
            //得到主体
            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken token=new UsernamePasswordToken(username, pwd);
            try {
                subject.login(token);
                System.out.println("登陆成功");
                ActivierUser activierUser = (ActivierUser) subject.getPrincipal();
                System.out.println(subject.getPrincipal().toString()+"222");
                session.setAttribute("user", activierUser.getUser());
                return "redirect:/user/toUserManager.action";
            } catch (AuthenticationException e) {
                e.printStackTrace();
                return "redirect:/index.jsp";
            }
        }
    
    }

    页面调用

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <%@taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
        <shiro:hasPermission name="user:query">
            <h1><a href="user/query.action">查询用户</a></h1>
        </shiro:hasPermission>
        <shiro:hasPermission name="user:add">
        <h1><a href="user/add.action">添加用户</a></h1>
        </shiro:hasPermission>
        <shiro:hasPermission name="user:update">
        <h1><a href="user/update.action">修改用户</a></h1>
        </shiro:hasPermission>
        <shiro:hasPermission name="user:delete">
        <h1><a href="user/delete.action">删除用户</a></h1>
        </shiro:hasPermission>
        <shiro:hasPermission name="user:export">
        <h1><a href="user/export.action">导出用户</a></h1>
        </shiro:hasPermission>
    </body>
    </html>

    详细请看git

  • 相关阅读:
    Mysql字符串字段判断是否包含某个字符串的方法
    mysql中用group_concat把selct中的数据列表转换成逗号分隔的字符串
    iview中对列标题头进行格式渲染render
    iview中父组件的数据通过props属性传值给子组件
    iview分页问题
    iview实现国际化
    MySQL查询优化:GROUP BY
    使用@ContextConfiguration替换@SpringBootTest
    WebAppConfiguration in Spring Tests
    使用@ContextConfiguration或者@ContextWebConfiguration注解调用resource文件夹下面的yml文件
  • 原文地址:https://www.cnblogs.com/xiaozhang666/p/12058341.html
Copyright © 2020-2023  润新知