Maven+SSM+Shiro整合配置

效果图:

 

简介

1.shiro是用于权限控制还有对密码加密的框架,同时可以控制尝试登入次数,超出将对用户锁定

2.shiro的运行轨迹是用户登入以后,shiro会自动查询用户的角色以及权限,并将用户信息保存到session里,当用户在进行访问资源时候,会根据之前对资源权限的定义,检查用户是否具有这个权限,比如访问/allUser,访问需要admin的角色,shiro会根据登入用户的信息,检查用户是否具有admin的角色

3.shiro1.2提供了passwordService,对密码加密更加方便

4.shiro的shiroFilter配置,如果是访问其他已存在的页面被拦截到登录页面,登录后就会跳转到之前的页面;如果是直接访问登录页面或者是通过退出登录到登录页面,再次登录就会跳转到“/”

5.Spring MVC的json传输,可以自动的根据属性名称,将json和对象自动转换

6.实例环境的搭建 http://blog.csdn.net/zzhao114/article/details/54958339

7.实例用到的mybatis多表联立 http://blog.csdn.net/zzhao114/article/details/55106270

8.实例  http://download.csdn.net/download/zzhao114/9757441

(http://download.csdn.net/download/zzhao114/9936992  这个加入了数据库还有简单的文档)

 

遇到的问题及解决

1.shiro定义的权限控制无效的问题

在web.xml中需要将shiro的配置放在是Spring MVC的配置之前,shiro的过滤集为<url-pattern>/*</url-pattern>,Spring MVC的过滤集为<url-pattern>/</url-pattern>

2.使用shiro加密,用户登入密码匹配一直不成功问题

自定义的userRealm,不能通过注释的方式自动注册bean,不然不能讲使用passwordService的加密方式对密码正确的匹配,需要在配置文件里配置

<!-- 注册自定义的Realm,并把密码匹配器注入,使用注解的方式自动注解会无法正确匹配密码 -->

<bean id="userRealm" class="com.shiro.UserRealm">

<property name="credentialsMatcher" ref="passwordMatcher"/>

<property name="cachingEnabled" value="false"/>

</bean>

3.shiro的注解无效问题

 

需要在Spring MVC的配置文件中启动shiro注解

<!--启用shiro注解 -->

<bean

class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"

depends-on="lifecycleBeanPostProcessor">

<property name="proxyTargetClass" value="true" />

</bean>

<bean

class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">

<property name="securityManager" ref="securityManager" />

</bean>

4.使用注解后,无权限异常的问题

 

如果没有对资源的访问权限,并不是跳转到在shiro配置文件中的<property name="unauthorizedUrl" value="/unauthorized" />设置的url,而是抛出无权限的异常,需要在Spring MVC的配置文件中加入即可解决

<!-- shiro为集成springMvc 拦截异常,使用注解时无权限的跳转 -->

<bean

class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">

<property name="exceptionMappings">

<props>

<!-- 这里你可以根据需要定义N多个错误异常转发 -->

<prop key="org.apache.shiro.authz.UnauthorizedException">redirect:/unauthorized</prop>

<prop key="org.apache.shiro.authz.UnauthenticatedException">redirect:/unauthorized</prop>

<prop key="java.lang.IllegalArgumentException">/error</prop> <!-- 参数错误(bizError.jsp) -->

<prop key="java.lang.Exception">/error</prop> <!-- 其他错误为'未定义错误'(unknowError.jsp) -->

</props>

</property>

</bean>

5.对静态资源设置不须任何权限的问题

需要同时在Spring MVC和shiro的配置文件中配置。

Spring MVC:

<!-- 静态资源访问(不拦截此目录下的东西的访问) -->

<mvc:resources location="/js/" mapping="/js/**" />

<mvc:resources location="/icon/" mapping="/icon/**" />

Shiro:

/icon/**=anon

/js/**=anon

6.shiro中的successUrl不生效的问题

 

successUrl配置只是做为一种附加配置,只有session中没有用户请求地址时才会使用successUrl。系统默认的是认证成功后跳转到上一次请求的路径,如果是首次请求,那shiro就会跳转到默认虚拟路径“/”,也就是跳转到index.jsp。

7.使用json问题

需要在Spring MVC加入json转换器

<!-- 启动SpringMVC的注解功能,完成请求和注解POJO的映射 -->、

<bean

class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">

<property name="messageConverters">

<list>

<ref bean="jsonMapping" /> <!-- JSON转换器 -->

</list>

</property>

</bean>


<!--避免IE执行AJAX时,返回JSON出现下载文件 -->

<bean id="jsonMapping"

class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">

<property name="supportedMediaTypes">

<list>

<value>text/html;charset=gbk</value>

</list>

</property>

</bean>

需要的jar包:

<!-- 映入JSON -->

<dependency>

  <groupId>org.codehaus.jackson</groupId>

  <artifactId>jackson-mapper-asl</artifactId>

  <version>1.9.13</version>

</dependency>

拓展

 

1.登入的几种异常

try {

subject.login(token);

} catch (UnknownAccountException uae) {

logger.info("用户名为【" + token.getPrincipal() + "】不存在");

} catch (IncorrectCredentialsException ice) {

logger.info("用户名为【 " + token.getPrincipal() + " 】密码错误!");

} catch (LockedAccountException lae) {

logger.info("用户名为【" + token.getPrincipal() + " 】的账户锁定,请联系管理员。");

} catch (DisabledAccountException dax) {

logger.info("用户名为:【" + token.getHost() + "】用户已经被禁用.");

} catch (ExcessiveAttemptsException eae) {

logger.info("用户名为:【" + token.getHost() + "】的用户登录次数过多,有暴力破解的嫌疑.");

} catch (ExpiredCredentialsException eca) {

logger.info("用户名为:【" + token.getHost() + "】用户凭证过期.");

} catch (AuthenticationException ae) {

logger.info("用户名为:【" + token.getHost() + "】用户验证失败.");

} catch (Exception e) {

logger.info("别的异常信息。。。。具体查看继承关系");

}

2.filterChainDefinitions的解释

<property name="filterChainDefinitions">

<value>

<!-- anon表示此地址不需要任何权限即可访问 -->

/static/**=anon

<!-- perms[user:query]表示访问此连接需要权限为user:query的用户 -->

/user=perms[user:query]

<!-- roles[manager]表示访问此连接需要用户的角色为manager -->

/user/add=roles[manager]

/user/del/**=roles[admin]

/user/edit/**=roles[manager]

<!--所有的请求(除去配置的静态资源请求或请求地址为anon的请求)都要通过登录验证,如果未登录则跳到/login-->

/** = authc

</value>

</property>

3.shiro在jsp页面的用法

 

配置:

<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>

用法:

<shiro:authenticated>用户已经登录显示此内容</shiro:authenticated>

<shiro:hasRole name="manager">manager角色登录显示此内容</shiro:hasRole>

<shiro:hasRole name="admin">admin角色登录显示此内容</shiro:hasRole>

<shiro:hasRole name="normal">normal角色登录显示此内容</shiro:hasRole>

<shiro:hasAnyRoles name="manager,admin">** manager or admin 角色用户登录显示此内容**</shiro:hasAnyRoles>

<shiro:principal/>显示当前登录用户名

<shiro:hasPermission name="add">add权限用户显示此内容</shiro:hasPermission>

<shiro:hasPermission name="user:query">query权限用户显示此内容<shiro:principal/></shiro:hasPermission>

<shiro:lacksPermission name="user:del"> 不具有user:del权限的用户显示此内容 </shiro:lacksPermission>

具体的配置:

 

数据库:

user:id、username、password

mapping_UR:userid(FK:user.id)、roleid(FK:role.id)

role:id、name
mapping_RP:roleid(FK:role.id)、permissionid(FK:permission.id)

permission:id、pname

spring-shiro

<?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"

xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"

xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc"

xmlns:aop="http://www.springframework.org/schema/aop"

xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/tx

http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc

http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/aop

http://www.springframework.org/schema/aop/spring-aop-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.jsp" />

<!-- 配置我们在登录页登录成功后的跳转地址,如果你访问的是非/login地址,则跳到您访问的地址 -->

<property name="successUrl" value="/Adduser.jsp" />

<!-- 如果您请求的资源不再您的权限范围,则跳转到/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表示此地址不需要任何权限即可访问 -->

/login=anon

/icon/**=anon

/js/**=anon

/logout=logout

<!--所有的请求(除去配置的静态资源请求或请求地址为anon的请求)都要通过登录验证,如果未登录则跳到/login -->

/** = authc

</value>

</property>

</bean>

<bean id="logoutFilter" class="org.apache.shiro.web.filter.authc.LogoutFilter">

<property name="redirectUrl" value="/login.jsp" />

</bean>


<!-- 凭证匹配器 -->

<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>


<!-- 会话ID生成器 -->

<bean id="sessionIdGenerator"

class="org.apache.shiro.session.mgt.eis.JavaUuidSessionIdGenerator" />

<!-- 会话Cookie模板 关闭浏览器立即失效 -->

<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>

<!-- 会话DAO -->

<bean id="sessionDAO"

class="org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO">

<property name="sessionIdGenerator" ref="sessionIdGenerator" />

</bean>

<!-- 会话验证调度器,每30分钟执行一次验证 ,设定会话超时及保存 -->

<bean name="sessionValidationScheduler"

class="org.apache.shiro.session.mgt.ExecutorServiceSessionValidationScheduler">

<property name="interval" value="1800000" />

<property name="sessionManager" ref="sessionManager" />

</bean>

<!-- 会话管理器 -->

<bean id="sessionManager"

class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">

<!-- 全局会话超时时间(单位毫秒),默认30分钟 -->

<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>


<!-- 安全管理器 -->

<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">

<property name="realm" ref="userRealm" />

<!-- 使用下面配置的缓存管理器 -->

<property name="cacheManager" ref="cacheManager" />

<property name="sessionManager" ref="sessionManager" />

</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>


<!-- 注册自定义的Realm,并把密码匹配器注入,使用注解的方式自动注解会无法正确匹配密码 -->

<bean id="userRealm" class="com.shiro.UserRealm">

<property name="credentialsMatcher" ref="passwordMatcher"/>

<property name="cachingEnabled" value="false"/>

</bean>


<bean id="cacheManager" class="org.apache.shiro.cache.MemoryConstrainedCacheManager" />

<!-- 保证实现了Shiro内部lifecycle函数的bean执行 -->

<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />

</beans>

spring-mvc

<?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"

xmlns:mvc="http://www.springframework.org/schema/mvc"

xsi:schemaLocation="

http://www.springframework.org/schema/mvc

http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd

http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context-3.0.xsd">


<!-- 扫描所有的 controller -->

<context:component-scan base-package="com.Controllers" />


<!-- 启动注解驱动 SpringMVC 功能 -->

<mvc:annotation-driven />


<!-- 启动SpringMVC的注解功能,完成请求和注解POJO的映射 -->

<bean

class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">

<property name="messageConverters">

<list>

<ref bean="jsonMapping" /> <!-- JSON转换器 -->

</list>

</property>

</bean>


<!--避免IE执行AJAX时,返回JSON出现下载文件 -->

<bean id="jsonMapping"

class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">

<property name="supportedMediaTypes">

<list>

<value>text/html;charset=gbk</value>

</list>

</property>

</bean>


<!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 -->

<bean id="multipartResolver"

class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

<!-- 默认编码 -->

<property name="defaultEncoding" value="gbk" />

<!-- 文件大小最大值 -->

<property name="maxUploadSize" value="10485760000" />

<!-- 内存中的最大值 -->

<property name="maxInMemorySize" value="40960" />

</bean>


<!-- 定义跳转的文件的前后缀,视图模式配置 -->

<bean

class="org.springframework.web.servlet.view.InternalResourceViewResolver">

<property name="prefix" value="" />

<property name="suffix" value=".jsp" />

</bean>


<!--启用shiro注解 -->

<bean

class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"

depends-on="lifecycleBeanPostProcessor">

<property name="proxyTargetClass" value="true" />

</bean>

<bean

class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">

<property name="securityManager" ref="securityManager" />

</bean>

<!-- shiro为集成springMvc 拦截异常,使用注解时无权限的跳转 -->

<bean

class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">

<property name="exceptionMappings">

<props>

<!-- 这里你可以根据需要定义N多个错误异常转发 -->

<prop key="org.apache.shiro.authz.UnauthorizedException">redirect:/unauthorized</prop>

<prop key="org.apache.shiro.authz.UnauthenticatedException">redirect:/unauthorized</prop>

<prop key="java.lang.IllegalArgumentException">/error</prop> <!-- 参数错误(bizError.jsp) -->

<prop key="java.lang.Exception">/error</prop> <!-- 其他错误为'未定义错误'(unknowError.jsp) -->

</props>

</property>

</bean>


<!-- 静态资源访问(不拦截此目录下的东西的访问) -->

<mvc:resources location="/js/" mapping="/js/**" />

<mvc:resources location="/icon/" mapping="/icon/**" />


</beans>

web.xm

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns="http://xmlns.jcp.org/xml/ns/javaee"

xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"

id="WebApp_ID" version="3.1">


<display-name>M-Shiro</display-name>


<welcome-file-list>

<welcome-file>index.jsp</welcome-file>

</welcome-file-list>


<!-- 读取Spring配置文件 -->

<context-param>

<param-name>contextConfigLocation</param-name>

<param-value>

classpath:config/spring-mybatis.xml

classpath:config/spring-shiro.xml

</param-value>

</context-param>

<listener>

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

</listener>


<!-- 日志记录 -->

<context-param>

<!-- 日志配置文件路径 -->

<param-name>log4jConfigLocation</param-name>

<param-value>classpath:properties/log4j.properties</param-value>

</context-param>

<context-param>

<!-- 日志页面的刷新间隔 -->

<param-name>log4jRefreshInterval</param-name>

<param-value>6000</param-value>

</context-param>

<listener>

<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>

</listener>


<!-- 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>


<!-- Spring MVC配置 -->

<servlet>

<servlet-name>SpringMVC</servlet-name>

<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

<init-param>

<param-name>contextConfigLocation</param-name>

<param-value>classpath:config/spring-mvc.xml</param-value>

</init-param>

<load-on-startup>1</load-on-startup>

</servlet>

<servlet-mapping>

<servlet-name>SpringMVC</servlet-name>

<url-pattern>/</url-pattern>

</servlet-mapping>


</web-app>

UserRealm

package com.shiro;


import javax.annotation.Resource;

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.UnknownAccountException;

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 com.pojo.*;

import com.service.IUserService;


public class UserRealm extends AuthorizingRealm {


@Resource

private IUserService userService;


@Override

protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {


String username = (String)principals.getPrimaryPrincipal();

SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();

authorizationInfo.setRoles(userService.findRoles(username));

authorizationInfo.setStringPermissions(userService.findPermissions(username));


return authorizationInfo;

}


@Override

protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {


String username = (String)token.getPrincipal();

User user = userService.findByUsername(username);


if(user == null) {

throw new UnknownAccountException();//没找到帐号

}


//交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配,如果觉得人家的不好可以自定义实现

SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(

user.getUsername(), //用户名

user.getPassword(),

getName() //realm name

);


return authenticationInfo;

}

}

登入

@RequestMapping(value = "/login", method = RequestMethod.POST)

@ResponseBody

public Message login(@RequestBody UserValidate userValidate) {


UsernamePasswordToken token = new UsernamePasswordToken(userValidate.getUsername(), userValidate.getPassword());

token.setRememberMe(userValidate.getRememberme());

try {

SecurityUtils.getSubject().login(token);

return new Message("login success");

} catch (UnknownAccountException uae) {

return new Message("error username");

} catch (IncorrectCredentialsException ice) {

return new Message("error password");

}

}

注册添加

@RequestMapping(value = "/addUser", method = RequestMethod.POST)

@ResponseBody

public User adduser(@RequestBody User u) {

String pwd = u.getPassword();

String newpwd = passwordService.encryptPassword(pwd);

u.setPassword(newpwd);

User user = userService.createUser(u);

int uid = user.getUserid();

List<Mapping_UR> urlist = u.getMapping_UR();

if (urlist != null) {

for (Mapping_UR ur : urlist) {

if (ur != null) {

int roleid = ur.getRole().getRoleid();

userService.correlationRoles(uid, roleid);

}

}

}


return user;

}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值