Shiro的Web项目配置

一 shiro的学习

二 shiro的java客户端配置

三 关于权限的一些问题

一 shiro的学习

官网和张开涛博客

二 shiro的java客户端配置

1.在web.xml中配置shiro的过滤器

  1. <!-- shiro 安全过滤器 -->
  2. <!-- The filter-name matches name of a 'shiroFilter' bean inside  -->
  3. <filter>
  4. <filter-name>shiroFilter</filter-name>
  5. <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
  6. <async-supported>true</async-supported>
  7. <init-param>
  8. <param-name>targetFilterLifecycle</param-name>
  9. <param-value>true</param-value>
  10. </init-param>
  11. </filter>
  12. <filter-mapping>
  13. <filter-name>shiroFilter</filter-name>
  14. <url-pattern>/*</url-pattern>
  15. </filter-mapping>
  1. <!-- shiro 安全过滤器 -->
  2. <!-- The filter-name matches name of a 'shiroFilter' bean inside -->
  3. <filter>
  4. <filter-name>shiroFilter</filter-name>
  5. <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
  6. <async-supported>true</async-supported>
  7. <init-param>
  8. <param-name>targetFilterLifecycle</param-name>
  9. <param-value>true</param-value>
  10. </init-param>
  11. </filter>
  12. <filter-mapping>
  13. <filter-name>shiroFilter</filter-name>
  14. <url-pattern>/*</url-pattern>
  15. </filter-mapping>

同时在web.xml读取shiro的配置文件

2.在spring-shiro-web.xml中配置:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:util="http://www.springframework.org/schema/util"
  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5. xmlns:context="http://www.springframework.org/schema/context"
  6. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  7. http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
  8. <!--     为了获取adminPath的值 -->
  9. <context:property-placeholder ignore-unresolvable="true" location="classpath*:/system.properties"/>
  10. <!-- 配置安全管理中心,Shiro的主要业务层对象基于web的应用程序 -->
  11. <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
  12. <property name="realm" ref="userRealm"/>
  13. </bean>
  14. <!--     自定义的过滤器,用来验证登陆 -->
  15. <bean id="formAuthenticationCaptchaFilter" class="com.huaxia.shiro.FormAuthenticationCaptchaFilter">
  16. <property name="usernameParam" value="username"/>
  17. <property name="passwordParam" value="password"/>
  18. <property name="captchaParam" value="captcha"/>
  19. <property name="loginUrl" value="${adminPath}/login"/>
  20. </bean>
  21. <!--     自定义的过滤器 -->
  22. <bean id="userFilter" class="com.huaxia.shiro.HuaXiaUserFilter">
  23. </bean>
  24. <!-- Shiro的Web过滤器,在web.xml中配置的shiroFilter即指向此 -->
  25. <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
  26. <!--         指定一个安全管理中心,用来验证用户能否登陆和相关权限 -->
  27. <property name="securityManager" ref="securityManager"/>
  28. <!--         所有地址被重定向到该地址 -->
  29. <property name="loginUrl" value="${adminPath}/login"/>
  30. <!--         用户登录成功后的页面地址 -->
  31. <property name="successUrl" value="${adminPath}"/>
  32. <!--         过滤器链,在shiroFilter之前即开始执行 -->
  33. <property name="filters">
  34. <util:map>
  35. <entry key="authc" value-ref="formAuthenticationCaptchaFilter"/>
  36. <entry key="user" value-ref="userFilter"/>
  37. </util:map>
  38. </property>
  39. <!--         配置地址对应的过滤器 -->
  40. <property name="filterChainDefinitions">
  41. <value>
  42. ${adminPath}/login = authc
  43. /** = user
  44. </value>
  45. </property>
  46. </bean>
  47. <!-- 保证实现了Shiro内部lifecycle函数的bean执行 -->
  48. <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
  49. <!-- 下面两个bean是shiro官网推荐的配置  -->
  50. <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor">
  51. <property name="proxyTargetClass" value="true" />
  52. </bean>
  53. <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
  54. <property name="securityManager" ref="securityManager"/>
  55. </bean>
  56. </beans>
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:util="http://www.springframework.org/schema/util"
  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5. xmlns:context="http://www.springframework.org/schema/context"
  6. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  7. http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
  8.  
  9. <!-- 为了获取adminPath的值 -->

  10. <context:property-placeholder ignore-unresolvable="true" location="classpath*:/system.properties"/>
  11. &lt;!-- 配置安全管理中心,Shiro的主要业务层对象基于web的应用程序 --&gt;
  12. &lt;bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"&gt;
  13. 	&lt;property name="realm" ref="userRealm"/&gt;
  14. &lt;/bean&gt;
  15.  
  16. <!-- 自定义的过滤器,用来验证登陆 -->

  17. <bean id="formAuthenticationCaptchaFilter" class="com.huaxia.shiro.FormAuthenticationCaptchaFilter">

  18. <property name="usernameParam" value="username"/>

  19. <property name="passwordParam" value="password"/>

  20. <property name="captchaParam" value="captcha"/>

  21. <property name="loginUrl" value="${adminPath}/login"/>

  22. </bean>

  23. <!-- 自定义的过滤器 -->

  24. <bean id="userFilter" class="com.huaxia.shiro.HuaXiaUserFilter">

  25. </bean>

  26. <!-- Shiro的Web过滤器,在web.xml中配置的shiroFilter即指向此 -->

  27. <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">

  28. <!-- 指定一个安全管理中心,用来验证用户能否登陆和相关权限 -->

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

  30. <!-- 所有地址被重定向到该地址 -->

  31. <property name="loginUrl" value="${adminPath}/login"/>

  32. <!-- 用户登录成功后的页面地址 -->

  33. <property name="successUrl" value="${adminPath}"/>

  34. <!-- 过滤器链,在shiroFilter之前即开始执行 -->

  35. <property name="filters">

  36. <util:map>

  37. <entry key="authc" value-ref="formAuthenticationCaptchaFilter"/>

  38. <entry key="user" value-ref="userFilter"/>

  39. </util:map>

  40. </property>

  41. <!-- 配置地址对应的过滤器 -->

  42. <property name="filterChainDefinitions">

  43. <value>

  44. ${adminPath}/login = authc

  45. /** = user

  46. </value>

  47. </property>

  48. </bean>

  49. &lt;!-- 保证实现了Shiro内部lifecycle函数的bean执行 --&gt;
  50. &lt;bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/&gt;
  51. &lt;!-- 下面两个bean是shiro官网推荐的配置  --&gt;
  52. &lt;bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor"&gt;
  53. 	&lt;property name="proxyTargetClass" value="true" /&gt;
  54. &lt;/bean&gt;
  55. &lt;bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor"&gt;
  56. 	&lt;property name="securityManager" ref="securityManager"/&gt;
  57. &lt;/bean&gt;
  58.  
  59. </beans>

其中UserRealm的实现如下:

  1. package com.huaxia.shiro;
  2. import javax.annotation.PostConstruct;
  3. import org.apache.shiro.SecurityUtils;
  4. import org.apache.shiro.authc.AuthenticationException;
  5. import org.apache.shiro.authc.AuthenticationInfo;
  6. import org.apache.shiro.authc.AuthenticationToken;
  7. import org.apache.shiro.authc.DisabledAccountException;
  8. import org.apache.shiro.authc.LockedAccountException;
  9. import org.apache.shiro.authc.SimpleAuthenticationInfo;
  10. import org.apache.shiro.authc.UnknownAccountException;
  11. import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
  12. import org.apache.shiro.authz.AuthorizationInfo;
  13. import org.apache.shiro.authz.SimpleAuthorizationInfo;
  14. import org.apache.shiro.realm.AuthorizingRealm;
  15. import org.apache.shiro.subject.PrincipalCollection;
  16. import org.apache.shiro.util.ByteSource;
  17. import org.slf4j.Logger;
  18. import org.slf4j.LoggerFactory;
  19. import org.springframework.beans.factory.annotation.Autowired;
  20. import org.springframework.stereotype.Service;
  21. import com.google.code.kaptcha.Constants;
  22. import com.huaxia.Constant;
  23. import com.huaxia.common.utils.security.Digests;
  24. import com.huaxia.common.utils.security.Encodes;
  25. import com.huaxia.user.entity.User;
  26. import com.huaxia.user.service.UserService;
  27. @Service
  28. public class UserRealm extends AuthorizingRealm {
  29. private Logger logger = LoggerFactory.getLogger(UserRealm.class);
  30. @Autowired
  31. private UserService userService;
  32. @Override
  33. protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
  34. String username = (String)principals.getPrimaryPrincipal();
  35. SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
  36. authorizationInfo.setRoles(userService.findRoles(username));
  37. authorizationInfo.setStringPermissions(userService.findPermissions(username));
  38. return authorizationInfo;
  39. }
  40. @Override
  41. protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
  42. UsernamePasswordCaptchaToken captchaToken = (UsernamePasswordCaptchaToken) token;
  43. String username = String.valueOf(token.getPrincipal());
  44. User user = userService.findByUsername(username,Constant.USER_DELFLAG);
  45. if(null != user && doCaptchValidate(captchaToken)) {
  46. if (Boolean.TRUE.equals(user.getLocked())) {
  47. throw new LockedAccountException(); //帐号锁定
  48. }
  49. if(Constant.LOGIN_STATUS_N.equals(user.getLoginStatus())){
  50. throw new DisabledAccountException();
  51. }
  52. byte[] salt = Encodes.decodeHex(user.getSalt());
  53. //交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配,可以自定义实现
  54. SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
  55. user.getUserName(),
  56. user.getPassword(), //密码
  57. ByteSource.Util.bytes(salt),
  58. getName()  //realm name
  59. );
  60. //SecurityUtils.getSubject().getSession().setAttribute("user", user);
  61. SecurityUtils.getSubject().getSession().setAttribute("userId", user.getUserId());
  62. userService.updateByLogin(user);
  63. return authenticationInfo;
  64. }else{
  65. throw new UnknownAccountException();
  66. }
  67. }
  68. protected boolean doCaptchValidate(UsernamePasswordCaptchaToken token){
  69. String captcha = (String) SecurityUtils.getSubject().getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
  70. if(captcha != null && !captcha.equalsIgnoreCase(token.getCaptcha())){
  71. throw new CaptchaException("Code error");
  72. }
  73. return true;
  74. }
  75. @PostConstruct
  76. public void initCredentialsMatcher() {
  77. HashedCredentialsMatcher matcher = new HashedCredentialsMatcher(Digests.SHA1);
  78. matcher.setHashIterations(Constant.HASH_INTERATIONS);
  79. setCredentialsMatcher(matcher);
  80. }
  81. @Override
  82. public void clearCachedAuthorizationInfo(PrincipalCollection principals) {
  83. super.clearCachedAuthorizationInfo(principals);
  84. }
  85. @Override
  86. public void clearCachedAuthenticationInfo(PrincipalCollection principals) {
  87. super.clearCachedAuthenticationInfo(principals);
  88. }
  89. @Override
  90. public void clearCache(PrincipalCollection principals) {
  91. super.clearCache(principals);
  92. }
  93. public void clearAllCachedAuthorizationInfo() {
  94. getAuthorizationCache().clear();
  95. }
  96. public void clearAllCachedAuthenticationInfo() {
  97. getAuthenticationCache().clear();
  98. }
  99. public void clearAllCache() {
  100. clearAllCachedAuthenticationInfo();
  101. clearAllCachedAuthorizationInfo();
  102. }
  103. }
  1. package com.huaxia.shiro;
  2.  
  3. import javax.annotation.PostConstruct;
  4.  
  5. import org.apache.shiro.SecurityUtils;

  6. import org.apache.shiro.authc.AuthenticationException;

  7. import org.apache.shiro.authc.AuthenticationInfo;

  8. import org.apache.shiro.authc.AuthenticationToken;

  9. import org.apache.shiro.authc.DisabledAccountException;

  10. import org.apache.shiro.authc.LockedAccountException;

  11. import org.apache.shiro.authc.SimpleAuthenticationInfo;

  12. import org.apache.shiro.authc.UnknownAccountException;

  13. import org.apache.shiro.authc.credential.HashedCredentialsMatcher;

  14. import org.apache.shiro.authz.AuthorizationInfo;

  15. import org.apache.shiro.authz.SimpleAuthorizationInfo;

  16. import org.apache.shiro.realm.AuthorizingRealm;

  17. import org.apache.shiro.subject.PrincipalCollection;

  18. import org.apache.shiro.util.ByteSource;

  19. import org.slf4j.Logger;

  20. import org.slf4j.LoggerFactory;

  21. import org.springframework.beans.factory.annotation.Autowired;

  22. import org.springframework.stereotype.Service;
  23.  
  24. import com.google.code.kaptcha.Constants;

  25. import com.huaxia.Constant;

  26. import com.huaxia.common.utils.security.Digests;

  27. import com.huaxia.common.utils.security.Encodes;

  28. import com.huaxia.user.entity.User;

  29. import com.huaxia.user.service.UserService;
  30.  
  31. @Service

  32. public class UserRealm extends AuthorizingRealm {

  33. private Logger logger = LoggerFactory.getLogger(UserRealm.class);
  34. @Autowired
  35. private UserService userService;
  36. @Override
  37. protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
  38.     String username = (String)principals.getPrimaryPrincipal();
  39.     SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
  40.     authorizationInfo.setRoles(userService.findRoles(username));
  41.     authorizationInfo.setStringPermissions(userService.findPermissions(username));
  42.     return authorizationInfo;
  43. }
  44. @Override
  45. protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
  46.     UsernamePasswordCaptchaToken captchaToken = (UsernamePasswordCaptchaToken) token;
  47.     String username = String.valueOf(token.getPrincipal());
  48.     User user = userService.findByUsername(username,Constant.USER_DELFLAG);
  49.     if(null != user &amp;&amp; doCaptchValidate(captchaToken)) {
  50.         if (Boolean.TRUE.equals(user.getLocked())) {
  51.             throw new LockedAccountException(); //帐号锁定
  52.         }
  53.         if(Constant.LOGIN_STATUS_N.equals(user.getLoginStatus())){
  54.         	throw new DisabledAccountException();
  55. 		}
  56.         byte[] salt = Encodes.decodeHex(user.getSalt());
  57.         //交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配,可以自定义实现
  58.         SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
  59.                 user.getUserName(),
  60.                 user.getPassword(), //密码
  61.                 ByteSource.Util.bytes(salt),
  62.                 getName()  //realm name
  63.         );
  64.         //SecurityUtils.getSubject().getSession().setAttribute("user", user);
  65.         SecurityUtils.getSubject().getSession().setAttribute("userId", user.getUserId());
  66.         userService.updateByLogin(user);
  67.         return authenticationInfo;
  68.     }else{
  69.         throw new UnknownAccountException();
  70.     }
  71. }
  72. protected boolean doCaptchValidate(UsernamePasswordCaptchaToken token){
  73.     String captcha = (String) SecurityUtils.getSubject().getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
  74.     if(captcha != null &amp;&amp; !captcha.equalsIgnoreCase(token.getCaptcha())){
  75.         throw new CaptchaException("Code error");
  76.     }
  77.     return true;
  78. }
  79. @PostConstruct
  80. public void initCredentialsMatcher() {
  81.     HashedCredentialsMatcher matcher = new HashedCredentialsMatcher(Digests.SHA1);
  82.     matcher.setHashIterations(Constant.HASH_INTERATIONS);
  83.     setCredentialsMatcher(matcher);
  84. }
  85. @Override
  86. public void clearCachedAuthorizationInfo(PrincipalCollection principals) {
  87.     super.clearCachedAuthorizationInfo(principals);
  88. }
  89. @Override
  90. public void clearCachedAuthenticationInfo(PrincipalCollection principals) {
  91.     super.clearCachedAuthenticationInfo(principals);
  92. }
  93. @Override
  94. public void clearCache(PrincipalCollection principals) {
  95.     super.clearCache(principals);
  96. }
  97. public void clearAllCachedAuthorizationInfo() {
  98.     getAuthorizationCache().clear();
  99. }
  100. public void clearAllCachedAuthenticationInfo() {
  101.     getAuthenticationCache().clear();
  102. }
  103. public void clearAllCache() {
  104.     clearAllCachedAuthenticationInfo();
  105.     clearAllCachedAuthorizationInfo();
  106. }
  107.  
  108. }

其中formAuthenticationCaptchaFilter的实现如下:

  1. package com.huaxia.shiro;
  2. import javax.servlet.ServletRequest;
  3. import javax.servlet.ServletResponse;
  4. import javax.servlet.http.HttpServletRequest;
  5. import javax.servlet.http.HttpServletResponse;
  6. import org.apache.shiro.authc.AuthenticationToken;
  7. import org.apache.shiro.subject.Subject;
  8. import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
  9. import org.apache.shiro.web.util.WebUtils;
  10. import org.slf4j.Logger;
  11. import org.slf4j.LoggerFactory;
  12. public class FormAuthenticationCaptchaFilter extends FormAuthenticationFilter {
  13. private Logger logger = LoggerFactory.getLogger(FormAuthenticationCaptchaFilter.class);
  14. public static final String DEFAULT_CAPTCHA_PARAM = "captcha";
  15. private String captchaParam = DEFAULT_CAPTCHA_PARAM;
  16. public String getCaptchaParam() {
  17. return captchaParam;
  18. }
  19. public void setCaptchaParam(String captchaParam){
  20. this.captchaParam = captchaParam;
  21. }
  22. protected String getCaptcha(ServletRequest request) {
  23. return WebUtils.getCleanParam(request, getCaptchaParam());
  24. }
  25. protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) {
  26. String username = getUsername(request) == null ? "" : getUsername(request);
  27. String password = getPassword(request) == null ? "" : getPassword(request);
  28. String captcha = getCaptcha(request) == null ? "" : getCaptcha(request);
  29. boolean rememberMe = isRememberMe(request);
  30. return new UsernamePasswordCaptchaToken(username,password.toCharArray(), rememberMe, captcha);
  31. }
  32. @Override
  33. protected boolean onLoginSuccess(AuthenticationToken token, Subject subject,
  34. ServletRequest request, ServletResponse response) throws Exception {
  35. //      issueSuccessRedirect(request, response);
  36. //      we handled the success redirect directly, prevent the chain from continuing:
  37. HttpServletRequest httpServletRequest = (HttpServletRequest)request;
  38. HttpServletResponse httpServletResponse = (HttpServletResponse)response;
  39. if (!"XMLHttpRequest".equalsIgnoreCase(httpServletRequest.getHeader("X-Requested-With"))
  40. || request.getParameter("ajax") == null) {// 不是ajax请求
  41. httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + this.getSuccessUrl());
  42. } else {
  43. httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + this.getSuccessUrl());
  44. }
  45. return false;
  46. }
  47. }
  1. package com.huaxia.shiro;
  2.  
  3. import javax.servlet.ServletRequest;

  4. import javax.servlet.ServletResponse;

  5. import javax.servlet.http.HttpServletRequest;

  6. import javax.servlet.http.HttpServletResponse;
  7.  
  8. import org.apache.shiro.authc.AuthenticationToken;

  9. import org.apache.shiro.subject.Subject;

  10. import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

  11. import org.apache.shiro.web.util.WebUtils;

  12. import org.slf4j.Logger;

  13. import org.slf4j.LoggerFactory;
  14.  
  15. public class FormAuthenticationCaptchaFilter extends FormAuthenticationFilter {
  16. private Logger logger = LoggerFactory.getLogger(FormAuthenticationCaptchaFilter.class);
  17. public static final String DEFAULT_CAPTCHA_PARAM = "captcha";
  18. private String captchaParam = DEFAULT_CAPTCHA_PARAM;
  19. public String getCaptchaParam() {
  20. 	return captchaParam;
  21. }
  22. public void setCaptchaParam(String captchaParam){
  23. 	this.captchaParam = captchaParam;
  24. }
  25. protected String getCaptcha(ServletRequest request) {
  26. 	return WebUtils.getCleanParam(request, getCaptchaParam());
  27. }
  28. protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) {
  29. 	String username = getUsername(request) == null ? "" : getUsername(request);
  30. 	String password = getPassword(request) == null ? "" : getPassword(request);
  31. 	String captcha = getCaptcha(request) == null ? "" : getCaptcha(request);
  32. 	boolean rememberMe = isRememberMe(request);
  33. 	return new UsernamePasswordCaptchaToken(username,password.toCharArray(), rememberMe, captcha);
  34. }
  35. @Override
  36. protected boolean onLoginSuccess(AuthenticationToken token, Subject subject,
  37. 								 ServletRequest request, ServletResponse response) throws Exception {
  38. 	//		issueSuccessRedirect(request, response);
  39. 	//      we handled the success redirect directly, prevent the chain from continuing:
  40. 	HttpServletRequest httpServletRequest = (HttpServletRequest)request;
  41. 	HttpServletResponse httpServletResponse = (HttpServletResponse)response;
  42. 	if (!"XMLHttpRequest".equalsIgnoreCase(httpServletRequest.getHeader("X-Requested-With"))
  43. 			|| request.getParameter("ajax") == null) {// 不是ajax请求
  44. 		httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + this.getSuccessUrl());
  45. 	} else {
  46. 		httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + this.getSuccessUrl());
  47. 	}
  48. 	return false;
  49. }
  50.  
  51. }

其中HuaXiaUserFilter的实现如下:

  1. package com.huaxia.shiro;
  2. import org.apache.shiro.web.filter.authc.UserFilter;
  3. import org.apache.shiro.web.filter.session.NoSessionCreationFilter;
  4. import org.apache.shiro.web.util.WebUtils;
  5. import javax.servlet.ServletRequest;
  6. import javax.servlet.ServletResponse;
  7. import javax.servlet.http.HttpServletResponse;
  8. public class HuaXiaUserFilter extends UserFilter {
  9. @Override
  10. protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
  11. /*if(!"XMLHttpRequest".equalsIgnoreCase(WebUtils.toHttp(response).getHeader("X-Requested-With"))
  12. || request.getParameter("ajax") == null ){
  13. this.saveRequestAndRedirectToLogin(request, response);
  14. }else{*/
  15. HttpServletResponse res = WebUtils.toHttp(response);
  16. res.setHeader("sessionstatus","timeout");
  17. //res.sendError(HttpServletResponse.SC_UNAUTHORIZED);
  18. /* }*/
  19. this.saveRequestAndRedirectToLogin(request, response);
  20. return false;
  21. }
  22. }
  1. package com.huaxia.shiro;
  2.  
  3. import org.apache.shiro.web.filter.authc.UserFilter;

  4. import org.apache.shiro.web.filter.session.NoSessionCreationFilter;

  5. import org.apache.shiro.web.util.WebUtils;
  6.  
  7. import javax.servlet.ServletRequest;

  8. import javax.servlet.ServletResponse;

  9. import javax.servlet.http.HttpServletResponse;
  10.  
  11. public class HuaXiaUserFilter extends UserFilter {
  12. @Override
  13. protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
  14.     /*if(!"XMLHttpRequest".equalsIgnoreCase(WebUtils.toHttp(response).getHeader("X-Requested-With"))
  15.             || request.getParameter("ajax") == null ){
  16.         this.saveRequestAndRedirectToLogin(request, response);
  17.     }else{*/
  18.         HttpServletResponse res = WebUtils.toHttp(response);
  19.         res.setHeader("sessionstatus","timeout");
  20.         //res.sendError(HttpServletResponse.SC_UNAUTHORIZED);
  21.    /* }*/
  22.     this.saveRequestAndRedirectToLogin(request, response);
  23.     return false;
  24. }
  25.  
  26. }

3.另外在Mvc的配置文件spring-mvc.xml中加入如下拦截器内容:

  1. <aop:config proxy-target-class="true"></aop:config>  
  2. <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">  
  3.     <property name="securityManager" ref="securityManager"/>  
  4. </bean>  
  1. <aop:config proxy-target-class="true"></aop:config>

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

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

  4. </bean>
  1.   
  1.  

三 关于权限的一些问题

1.shiro如何实现验证码?

关于shiro的验证码,使用的是google的kaptcha , 在web.xml中配置sevlet如下:

  1. <servlet>  
  2.     <servlet-name>ImageServlet</servlet-name>  
  3.     <servlet-class>com.google.code.kaptcha.servlet.KaptchaServlet</servlet-class>  
  4. </servlet>  
  5.   
  6. <servlet-mapping>  
  7.     <servlet-name>ImageServlet</servlet-name>  
  8.     <url-pattern>/ImageServlet</url-pattern>  
  9. </servlet-mapping>  
  1. <servlet>

  2. <servlet-name>ImageServlet</servlet-name>

  3. <servlet-class>com.google.code.kaptcha.servlet.KaptchaServlet</servlet-class>

  4. </servlet>
  5. &lt;servlet-mapping&gt;
  6. 	&lt;servlet-name&gt;ImageServlet&lt;/servlet-name&gt;
  7. 	&lt;url-pattern&gt;/ImageServlet&lt;/url-pattern&gt;
  8. &lt;/servlet-mapping&gt;</pre>
  9.  
  10. 2.用户名密码通常保存为什么要加盐值?

  11. 由于通常密码保存使用的是md5加密,同样的密码在md5后会产生相同的加密后字符串,如果有数据库的查看权限,那么看到相同的加密后字符串,很容易猜到是相同的密码。同时根据md5对照表(或者一些网站),能够找到密码。 如果密码在加上随机盐后再进行md5,那么同样的密码在md5后的字符串是不同的,就能够避免上面两个问题。总的来说增加了破解的难度。

  12. 3.通常情况下用户-角色-权限(资源)之间的关系

  13. 用户与角色多对多:一个用户可以拥有多个角色,一个角色可以被多个用户具有

  14. 角色与权限(资源,主要指菜单,按钮等)多对多:一个角色可以拥有多个权限,一个权限可以被多个角色拥有

  15. 3.1 在首页,通常根据用户查找角色,然后根据角色列出相关的菜单栏和相关按钮

  16. 3.2 在系统配置中:

  17. 用户配置:可以增删用户,也可以配置用户的多个角色

  18. 角色配置:可以配置一个角色的多个权限

  19. 权限配置:可以增删相关的资源(菜单或者按钮)

  20. 4.shiro授权的几种方式:

  21. 4.1 在代码体中:

    1. if (currentUser.hasRole("admin"))
  22.  
  23. if (currentUser.hasRole("admin"))
  24. 4.2 在方法上:

    1. @RequiresPermissions(“account:create”)‏
    1. public void openAccount( Account acct )
  25.  
  26. @RequiresPermissions(“account:create”)‏
  27. public void openAccount( Account acct )
  28. 4.3 在jsp页面上:

    1. <shiro:hasPermission name=“users:manage”>
    1. <a href=“manageUsers.jsp”> </a>
    1. </shiro:hasPermission>
  29.  
  30.    <shiro:hasPermission name=“users:manage”>
  31.         <a href=“manageUsers.jsp”> </a>
  32.    </shiro:hasPermission>
  33. Shiro的官方文档整理的感觉差强人意,非常不明朗,需要结合张开涛的博客来看。有很多的地方需要学习,后续更新。

Shiro的Web项目配置(转)的更多相关文章

  1. Intellij IDEA创建的Web项目配置Tomcat并启动Maven项目

    本篇博客讲解IDEA如何配置Tomcat. 大部分是直接上图哦. 点击如图所示的地方,进行添加Tomcat配置页面 弹出页面后,按照如图顺序找到,点击+号 tomcat Service -> L ...

  2. Tomcat 中如何给 web 项目配置虚拟目录的方法

    为什么要给 web 项目配置虚拟目录? 初学 JavaWeb 时,会发现只要我们把 web 项目放到 Tomcat 的 webapps 目录下,再通过 http://localhost:8080/项目 ...

  3. 给本地web项目配置域名

    给本地的web项目配置一个域名 通常访问本地问项目时,使用localhost:port/projectname或者127.0.0.1:port/projectname来实现.我们可以通过配置tomca ...

  4. Java Web项目 配置 ueditor心得

    近期的JAVA项目,由于客户要求需要引入富文本编辑器. 参考了两款插件,一款是ckeditor,一款是ueditor. ckeditor在上传文件的时候必须配合ckfinder使用,而ckfinder ...

  5. web项目配置webAppRootKey 获得根目录 .

    log4j和web.xml配置webAppRootKey 的问题 1 在web.xml配置 <context-param>  <param-name>webAppRootKey ...

  6. 【IDEA】Intellij IDEA创建的Web项目配置Tomcat并启动Maven项目

    转载请注明出处:http://blog.csdn.net/qq_26525215本文源自[大学之旅_谙忆的博客] 本篇博客讲解IDEA如何配置Tomcat. 大部分是直接上图哦. 点击如图所示的地方, ...

  7. idea 普通 web项目配置启动【我】

    首先说这是一个普通的java web项目,没有用到maven.  检出项目: 项目是先用 乌龟svn 在 编辑器外部检出到一个目录下,然后再用 idea的 open 打开这个目录生成的.[因为直接用i ...

  8. shiro与Web项目整合-Spring+SpringMVC+Mybatis+Shiro(八)

    Jar包

  9. IDEA创建的Web项目配置Tomcat并启动Maven项目

    点击如图所示的地方,进行添加Tomcat配置页面   弹出页面后,按照如图顺序找到,点击+号     tomcat Service -> Local   注意,这里不要选错了哦,还有一个TomE ...

随机推荐

  1. Linq案例

    1.牛刀小试 using System; using System.Collections.Generic; using System.Linq; using System.Text; using S ...

  2. xshell --- 查看和关闭 进程

    netstat -apn | grep 80 kill -l PID  关闭进程

  3. ipcalcIP地址计算

    ipcalc命令是一个简单的ip地址计算器,可以完成简单的IP地址计算任务. 语法 ipcalc(选项) 选项 -b:由给定的IP地址和网络掩码计算出广播地址: -h:显示给定UP地址所对应的主机名: ...

  4. 移动GPU全解读(二)

    [编者按]:本文作者为爱搞机特约作者.技术达人"炮神"@ioncannon. 在上一篇移动GPU解读中,对移动GPU的架构.相关參数进行了介绍,本部分介绍的则是移动GPU的Shad ...

  5. android 自己定义状态栏和导航栏分析与实现

    效果 android 4.4之后,系统是支持自己定义状态栏和导航栏的.举个最典型的样例就是bilibiliclient了(iOS版本号和android版本号能用两套全然不一样符合各自系统的设计ui,良 ...

  6. POJ--2516--Minimum Cost【最小费用最大流】

    链接:http://poj.org/problem?id=2516 题意:有k种货物,n个客户对每种货物有一定需求量,有m个仓库.每一个仓库里有一定数量的k种货物.然后k个n*m的矩阵,告诉从各个仓库 ...

  7. javascript创建对象的方法--构造函数模式

    javascript创建对象的方法--构造函数模式 一.总结 构造函数模式作用和不足 1.作用:解决工厂模式不是用new关键字来创建对象的弊端 2.作用:解决工厂模式创建的实例和模型没有内在联系的问题 ...

  8. 阅读笔记——Web应用程序

    Web应用程序与DD文件 Web应用程序 web应用程序是一种可以通过Web访问的应用程序.Web应用程序最大的好处是永和很容易访问应用程序.用户只需要有浏览器即可,不需要安装其他任何软件.一个Web ...

  9. Linux在应用层读写寄存器的方法

    可以通过操作/dev/mem设备文件,以及mmap函数,将寄存器的地址映射到用户空间,直接在应用层对寄存器进行操作,示例如下: #include <stdio.h> #include &l ...

  10. 2.lombok系列2:lombok注解详解

    转自:https://www.imooc.com/article/18157 开篇 看到第一篇<初识lombok>你可能意犹未尽,本文我们按照场景来介绍一下常用的注解. 未特别说明,均标注 ...