ssm集成shiro进行权限管理,shiro退出(三)

第一步在maven中添加

 <!--shiro   shiro-all  shiro-web spring-shiro-->
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-all</artifactId>
            <version>1.2.5</version>
        </dependency>
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-web</artifactId>
            <version>1.2.5</version>
        </dependency>
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring</artifactId>
            <version>1.2.5</version>
        </dependency>

第二步,找到web.xml配置spring的动态代理filter

	<filter>
		<filter-name>ShiroFilter</filter-name>
		<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>ShiroFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

第三步,配置spring-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:aop="http://www.springframework.org/schema/aop"
	   xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util"
	   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/tx http://www.springframework.org/schema/tx/spring-tx.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
       http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">


	<!-- 1:spring和shiro整合的配置文件当中,需要定义bean shirofilter -->
	<bean id="ShiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
		<property name="securityManager" ref="securityManager" />
		<!-- 如果没有认证将要跳转的登陆地址,http可访问的url,如果不在表单认证过虑器FormAuthenticationFilter中指定此地址就为身份认证地址 -->
		<property name="loginUrl" value="/login/toLogin" />
		<!-- 没有权限跳转的地址 -->
		<property name="unauthorizedUrl" value="/login/noauth" />
		<!-- shiro拦截器配置 -->
		<!-- 定义权限拦截的规则  
		authc 权限认证通过才可以访问
		anon  不需要登录认证 也不需要权限认证
		user  登录认证通过才可以访问
		logout  退出登录  不需要自己定义退出登录功能
		
		 -->
		<!-- 过滤器链定义   shirofilter可以拦截静态子资源的,所以静态资源一定得在这里配置 -->
		<property name="filterChainDefinitions">
			<value>
				/login/**= anon
				/css/**=anon
				/html/**=anon
				/images/**=anon
				/js/**=anon
				/company/**=roles[admin]
				/logout = logout
				<!-- user表示身份认证通过或通过记住我认证通过的可以访问 -->
				/** = user
				<!-- /**放在最下边,如果一个url有多个过虑器则多个过虑器中间用逗号分隔,如:/** = user,roles[admin] -->
			</value>
		</property>
	</bean>

	<!-- 安全管理器  把reaml注入给安全管理器 -->
	<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
		<property name="realm" ref="userRealm" />

	</bean>

	<!-- 自定义 realm -->
	<bean id="userRealm" class="com.xiupeilian.carpart.session.UserRealm">
	</bean>

	<!-- Shiro生命周期处理器-->
	<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />

</beans>


第四步,配置web.xml

  <!-- springmvc的核心控制器dispatcherServlet -->
    <servlet>
        <servlet-name>dispactherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath*:spring/springmvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

在处理登录的conllter中

Subject subject= SecurityUtils.getSubject();
			UsernamePasswordToken token=new UsernamePasswordToken(vo.getLoginName(),vo.getPassword());
			subject.login(token);

这个时候到哪里了?到我们的UserRealm 创建一个 UserRealm 实现 AuthorizingRealm接口,重写两个方法 ,这边我们在登录认证这里写下,登录认证的逻辑

@Description: 登录认证的方法
 * @Author:      sunflower
 * @Param:       [authenticationToken]
 * @Return       org.apache.shiro.authc.AuthenticationInfo
  **/
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token=(UsernamePasswordToken)authenticationToken;
        //查询数据库,判断用户名密码是否存在
        LoginVo vo=new LoginVo();
        vo.setPassword(SHA1Util.encode(new String(token.getPassword())));
        vo.setLoginName(token.getUsername());
        SysUser user=userService.findUserByLoginNameAndPassword(vo);
        if (user==null){
            //认证失败,,新建一个异常
            throw new AccountException("2");
        }else {
            //返回用户的认证成功之后的身份信息给
            AuthenticationInfo info = new SimpleAuthenticationInfo(user, token.getPassword(), getName());
            return info;

        }
    }

登陆成功返回了authenticationInfo对象,登录失败抛出一个异常,那我们在登录的controllter进行一个捕获

try {
				subject.login(token);
			}catch (Exception e){
				//用户名密码错误
				response.getWriter().write(e.getMessage());
			}
			//获取存入的用户信息
			SysUser user=(SysUser)SecurityUtils.getSubject().getPrincipal();
			//存spring-session
			request.getSession().setAttribute("user",user);
			response.getWriter().write(3);

这样的话,我们的登录认证就写完了,下面来写授权的逻辑。

    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SysUser user=(SysUser)principalCollection.getPrimaryPrincipal();
        ///查询出该用户所有的权限信息和角色信息。
        //查角色
        Role role=userService.findRoleByRoleId(user.getRoleId());
        List<String> roleList=new ArrayList<>();
        roleList.add(role.getRoleEnglishName());
        //查权限信息(菜单)
        List<Menu> menuList=userService.findMenusById(user.getId());
        List<String> permisstionList=new ArrayList<>();
        for (Menu menu:menuList){
            //存入权限的关键字
            permisstionList.add(menu.getMenuKey());
        }
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        info.addRoles(roleList);
        info.addStringPermissions(permisstionList);
        //封装了该用户的权限信息
        return info;
    }

启动项目,大功告成。

接下来,说一下shiro的退出,不需要自己开发,只需要定义退出的路径就可以了。在spring-shiro加上一行/logout = logout

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值