【Spring实战】----Security4.1.3实现根据请求跳转不同登录页以及登录后根据权限跳转到不同页配置

一、背景介绍

上一篇最后总结说了:

1)被认证请求被FilterSecurityInterceptor拦截看有没有对应权限,如果没有抛异常给ExceptionTranslationFilter
2)ExceptionTranslationFilter缓存原请求,利用LoginUrlAuthenticationEntryPoint入口跳转到登录界面
3)用户在登录界面填写登录信息后,提交,经过UsernamePasswordAuthenticationFilter对填写的信息和从数据源中获取的信息进行对比,成功则授权权限,并通过登录成功后入口SavedRequestAwareAuthenticationSuccessHandler跳转回原请求页面(跳转时有从缓存中对请求信息的恢复)
4)登录完成后返回原请求,由FilterSecurityInterceptor进行权限的验证(大部分工作有AbstractSecurityInterceptor来做),根据登录成功后生成的Authentication(Authentication authentication = SecurityContextHolder.getContext().getAuthentication();由SecurityContextHolder持有,而其中的SecurityContext由 SecurityContextPersistentFilter保存到session中从而实现request共享 )中的权限和请求所需的权限对比,如果一致则成功执行,如果权限不正确则返回403错误码
5)以上均是默认情况下,没有经过配置的执行过程,当然可以自定义LoginUrlAuthenticationEntryPoint和SavedRequestAwareAuthenticationSuccessHandler实现根据不同的请求所需权限跳转到不同登录页面及授权成功后根据权限跳转到不同页面,以及返回403错误码时跳转到对应的页面(AccessDeniedHandlerImpl)在下一篇中会对其进行实现


那么这里要实现题目中说的(登录后根据权限跳转到不同页是指直接点击登录的情况,如果是有原请求跳转过来的,登录成功并且认证成功后跳转到原请求页),需要如下操作

1)自定义LoginUrlAuthenticationEntryPoint实现跳转到不同登录页,如用户订单请求跳转到用户登录页,管理中心请求跳转到管理员登录页

2)自定义SavedRequestAwareAuthenticationSuccessHandler实现直接点击登录成功后跳转到指定的页,如用户登录后跳转到首页,管理员登陆后跳转到管理中心

3)此问题涉及了两种权限的用户登录,ROLE_USER及ROLE_MANAGER,还需要配置AccessDeniedHandlerImpl来处理虽然登录成功了确没有权限访问的情况。

4)还需要自定义SimpleUrlAuthenticationFailureHandler来实现登录失败的情况,主要是用户不存在或密码错误问题。这种情况下能够实现从哪个登录页面过来的还是返回原登录页,并携带错误信息

5)还需要配置login-processing-url属性,能够拦截/manager/login和/login提交,从而经过UsernamePasswordAuthenticationFilter时对其进行登录验证(requiresAuthentication(request, response)判断)

下面对其一一说明

二、全部配置如下:

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2.   
  3. <beans:beans xmlns="http://www.springframework.org/schema/security"  
  4.     xmlns:beans="http://www.springframework.org/schema/beans"  
  5.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  6.     xsi:schemaLocation="http://www.springframework.org/schema/beans  
  7.         http://www.springframework.org/schema/beans/spring-beans.xsd  
  8.         http://www.springframework.org/schema/security  
  9.         http://www.springframework.org/schema/security/spring-security.xsd">  
  10.           
  11.     <http auto-config="true" use-expressions="true" entry-point-ref="myAuthenticationEntryPoint" >  
  12.         <form-login   
  13.             login-page="/login"  
  14.             login-processing-url="/**/login"  
  15.             authentication-failure-handler-ref="myAuthenticationFailureHandler"  
  16.             authentication-success-handler-ref="myAuthenticationSuccessHandler" />     
  17.          <!-- 认证成功用自定义类myAuthenticationSuccessHandler处理 -->  
  18.            
  19.          <logout logout-url="/logout"   
  20.                 logout-success-url="/"   
  21.                 invalidate-session="true"  
  22.                 delete-cookies="JSESSIONID"/>  
  23.           
  24.         <!-- 登录成功后拒绝访问跳转的页面 -->         
  25.         <access-denied-handler error-page="/security/deny" />  
  26.           
  27.         <csrf disabled="true" />  
  28.         <intercept-url pattern="/order/*" access="hasRole('ROLE_USER')"/>  
  29.         <intercept-url pattern="/manager" access="hasRole('ROLE_MANAGER')"/>  
  30.     </http>  
  31.       
  32.     <!-- 使用自定义类myUserDetailsService从数据库获取用户信息 -->  
  33.     <authentication-manager>    
  34.         <authentication-provider user-service-ref="myUserDetailsService">    
  35.             <!-- 加密 -->  
  36.             <password-encoder hash="md5">  
  37.             </password-encoder>  
  38.         </authentication-provider>  
  39.     </authentication-manager>  
  40.       
  41.     <!-- 被认证请求根据所需权限跳转到不同的登录界面 -->  
  42.     <beans:bean id="myAuthenticationEntryPoint"   
  43.         class="com.mango.jtt.springSecurity.MyAuthenticationEntryPoint">  
  44.         <beans:property name="authEntryPointMap" ref="loginFormsMap"></beans:property>  
  45.         <beans:constructor-arg name="loginFormUrl" value="/login"></beans:constructor-arg>  
  46.     </beans:bean>  
  47.       
  48.     <!-- 根据不同请求所需权限跳转到不同的登录界面 -->  
  49.     <beans:bean id="loginFormsMap" class="java.util.HashMap">  
  50.         <beans:constructor-arg>  
  51.             <beans:map>  
  52.                 <beans:entry key="/user/**" value="/login" />  
  53.                 <beans:entry key="/manager/**" value="/manager/login" />  
  54.                 <beans:entry key="/**" value="/login" />  
  55.             </beans:map>  
  56.         </beans:constructor-arg>  
  57.     </beans:bean>  
  58.       
  59.     <!-- 登录且授权成功后控制 -->  
  60.     <beans:bean id="myAuthenticationSuccessHandler"   
  61.         class="com.mango.jtt.springSecurity.MyAuthenticationSuccessHandler">  
  62.         <beans:property name="authDispatcherMap" ref="dispatcherMap"></beans:property>  
  63.     </beans:bean>  
  64.       
  65.     <!-- 根据不同的权限,跳转到不同的页面(直接点击登录页面用) -->  
  66.     <beans:bean id="dispatcherMap" class="java.util.HashMap">  
  67.         <beans:constructor-arg>  
  68.             <beans:map>  
  69.                 <beans:entry key="ROLE_USER" value="/"/>  
  70.                 <beans:entry key="ROLE_MANAGER" value="/manager"/>  
  71.             </beans:map>  
  72.         </beans:constructor-arg>  
  73.     </beans:bean>  
  74.       
  75.     <!-- 登录失败后控制 -->  
  76.     <beans:bean id="myAuthenticationFailureHandler"   
  77.         class="com.mango.jtt.springSecurity.MyAuthenticationFailureHandler">  
  78.         <beans:property name="loginEntry" ref="myAuthenticationEntryPoint"></beans:property>  
  79.     </beans:bean>  
  80. </beans:beans>  

三、MyAuthenticationEntryPoint配置

  1. <!-- 被认证请求根据所需权限跳转到不同的登录界面 -->  
  2.    <beans:bean id="myAuthenticationEntryPoint"   
  3.     class="com.mango.jtt.springSecurity.MyAuthenticationEntryPoint">  
  4.     <beans:property name="authEntryPointMap" ref="loginFormsMap"></beans:property>  
  5.     <beans:constructor-arg name="loginFormUrl" value="/login"></beans:constructor-arg>  
  6.    </beans:bean>  
  7.      
  8.    <!-- 根据不同请求所需权限跳转到不同的登录界面 -->  
  9. <beans:bean id="loginFormsMap" class="java.util.HashMap">  
  10.     <beans:constructor-arg>  
  11.         <beans:map>  
  12.             <beans:entry key="/user/**" value="/login" />  
  13.             <beans:entry key="/manager/**" value="/manager/login" />  
  14.             <beans:entry key="/**" value="/login" />  
  15.         </beans:map>  
  16.     </beans:constructor-arg>  
  17. </beans:bean>  


根据请求路径跳转到不同的登录页面(其他实现方式也可),其中key是匹配的路径,value是要跳转的登录页,关键代码如下:

  1. /** 
  2.  * 被认证请求向登录页面跳转的控制 根据被请求所需权限向不同登录页面跳转 
  3.  *  
  4.  * @author HHL 
  5.  *  
  6.  * @date 2016年12月20日 
  7.  */  
  8. public class MyAuthenticationEntryPoint extends  
  9.         LoginUrlAuthenticationEntryPoint {  
  10.   
  11.     public MyAuthenticationEntryPoint(String loginFormUrl) {  
  12.         super(loginFormUrl);  
  13.     }  
  14.   
  15.     private Map<String, String> authEntryPointMap;  
  16.     private PathMatcher pathMatcher = new AntPathMatcher();  
  17.   
  18.     @Override  
  19.     protected String determineUrlToUseForThisRequest(  
  20.             HttpServletRequest request, HttpServletResponse response,  
  21.             AuthenticationException exception) {  
  22.         String requestURI = request.getRequestURI().replace(  
  23.                 request.getContextPath(), "");  
  24.         for (String url : this.authEntryPointMap.keySet()) {  
  25.             if (this.pathMatcher.match(url, requestURI)) {  
  26.                 return this.authEntryPointMap.get(url);  
  27.             }  
  28.         }  
  29.         return super.determineUrlToUseForThisRequest(request, response,  
  30.                 exception);  
  31.     }  
  32.   
  33.   
  34.     public PathMatcher getPathMatcher() {  
  35.         return pathMatcher;  
  36.     }  
  37.   
  38.     public void setPathMatcher(PathMatcher pathMatcher) {  
  39.         this.pathMatcher = pathMatcher;  
  40.     }  
  41.   
  42.   
  43.     public Map<String, String> getAuthEntryPointMap() {  
  44.         return authEntryPointMap;  
  45.     }  
  46.   
  47.     public void setAuthEntryPointMap(Map<String, String> authEntryPointMap) {  
  48.         this.authEntryPointMap = authEntryPointMap;  
  49.     }  
  50.   
  51. }  

该类重写了父类的determineUrlToUseForThisRequest,实现了根据请求路径返回不同的登录页路径,从而在父类的commence方法中跳转到根据请求路径返回的登录页。其中spring的AntPathMatcher类及AntPathRequestMatcher可以实现路径的匹配工作。

这里实现了"/user/**"相关的路径跳转到用户登录页面"/login","/manager/**"相关的页面跳转到管理员登录页面"/manager/login",上面两者没有匹配的"/**",均跳转到用户登录页面"/login"。当然上述的前提条件是请求路径需要权限,也就是有如下配置:

  1. <intercept-url pattern="/order/**" access="hasRole('ROLE_USER')"/>  
  2.         <intercept-url pattern="/manager" access="hasRole('ROLE_MANAGER')"/>  
否则,不需要权限的请求,也不需要跳转到登录页


四、myAuthenticationSuccessHandler配置

主要配置

  1. <!-- 授权成功后控制 -->  
  2.     <beans:bean id="myAuthenticationSuccessHandler"   
  3.         class="com.mango.jtt.springSecurity.MyAuthenticationSuccessHandler">  
  4.         <beans:property name="authDispatcherMap" ref="dispatcherMap"></beans:property>  
  5.     </beans:bean>  
  6.       
  7.     <!-- 根据不同的权限,跳转到不同的页面(直接点击登录页面用) -->  
  8.     <beans:bean id="dispatcherMap" class="java.util.HashMap">  
  9.         <beans:constructor-arg>  
  10.             <beans:map>  
  11.                 <beans:entry key="ROLE_USER" value="/"/>  
  12.                 <beans:entry key="ROLE_MANAGER" value="/manager"/>  
  13.             </beans:map>  
  14.         </beans:constructor-arg>  
  15.     </beans:bean>  

其中map中的key为登录后的用户权限,value代表要直接点击登录的情况下登录成功后要跳转的页面,关键代码处理

  1. /** 
  2.  * 登录授权成功后操作控制,如果是直接点击登录的情况下,根据授权权限跳转不同页面; 否则跳转到原请求页面 
  3.  *  
  4.  * @author HHL 
  5.  * @date 
  6.  *  
  7.  */  
  8. public class MyAuthenticationSuccessHandler extends  
  9.         SavedRequestAwareAuthenticationSuccessHandler {  
  10.     private Map<String, String> authDispatcherMap;  
  11.     private RequestCache requestCache = new HttpSessionRequestCache();  
  12.   
  13.     @Autowired  
  14.     private IUserService userService;  
  15.   
  16.     @Override  
  17.     public void onAuthenticationSuccess(HttpServletRequest request,  
  18.             HttpServletResponse response, Authentication authentication)  
  19.             throws IOException, ServletException {  
  20.         // 获取用户权限  
  21.         Collection<? extends GrantedAuthority> authCollection = authentication  
  22.                 .getAuthorities();  
  23.         if (authCollection.isEmpty()) {  
  24.             return;  
  25.         }  
  26.   
  27.         // 认证成功后,获取用户信息并添加到session中  
  28.         UserDetails userDetails = (UserDetails) authentication.getPrincipal();  
  29.         MangoUser user = userService.getUserByName(userDetails.getUsername());  
  30.         request.getSession().setAttribute("user", user);  
  31.           
  32.         String url = null;  
  33.         // 从别的请求页面跳转过来的情况,savedRequest不为空  
  34.         SavedRequest savedRequest = requestCache.getRequest(request, response);  
  35.         if (savedRequest != null) {  
  36.             url = savedRequest.getRedirectUrl();  
  37.         }  
  38.   
  39.         // 直接点击登录页面,根据登录用户的权限跳转到不同的页面  
  40.         if (url == null) {  
  41.             for (GrantedAuthority auth : authCollection) {  
  42.                 url = authDispatcherMap.get(auth.getAuthority());  
  43.             }  
  44.             getRedirectStrategy().sendRedirect(request, response, url);  
  45.         }  
  46.   
  47.         super.onAuthenticationSuccess(request, response, authentication);  
  48.       
  49.     }  
  50.   
  51.   
  52.     public RequestCache getRequestCache() {  
  53.         return requestCache;  
  54.     }  
  55.   
  56.     public void setRequestCache(RequestCache requestCache) {  
  57.         this.requestCache = requestCache;  
  58.     }  
  59.   
  60.   
  61.     public Map<String, String> getAuthDispatcherMap() {  
  62.         return authDispatcherMap;  
  63.     }  
  64.   
  65.     public void setAuthDispatcherMap(Map<String, String> authDispatcherMap) {  
  66.         this.authDispatcherMap = authDispatcherMap;  
  67.     }  
  68.   
  69. }  

其中用从requestCache中获取到的savedRequest来判断是否是直接点击登录还是从其他页面跳转过来的,上一篇也说过从savedRequest获取实质上是从session中获取,因此这里的requestCache实例可以为任一实例。

这里就实现了如果是直接点击登录的成功后,用户登录的跳转到首页"/",管理员登录的就跳转到管理中心“/manager”;如果是从其他请求页过来的还是返回原请求页面。

五、myAuthenticationFailureHandler

登录失败后,没有用户或者密码错误的情况下,主要配置

  1. <!-- 登录失败后控制 -->  
  2.     <beans:bean id="myAuthenticationFailureHandler"   
  3.         class="com.mango.jtt.springSecurity.MyAuthenticationFailureHandler">  
  4.         <beans:property name="loginEntry" ref="myAuthenticationEntryPoint"></beans:property>  
  5.     </beans:bean>  


其中依赖了myAuthenticationEntryPoint,就是要根据登录路径,返回到原登录页面,并携带错误信息,这里就需要管理登录的form action设置不同

  1. <%@ page language="java" pageEncoding="UTF-8" contentType="text/html;charset=UTF-8"%>  
  2. <%@ include file="../../includes/taglibs.jsp"%>  
  3. <!DOCTYPE html>  
  4. <html>  
  5. <head>  
  6.     <title>Mango-managerLogin</title>  
  7.     <meta name="menu" content="home" />      
  8. </head>  
  9.   
  10. <body>  
  11.   
  12. <h1>请管理员登录!</h1>  
  13.   
  14. <div style="text-align:center">  
  15.     <form action="<c:url value='/manager/login' />" method="post">  
  16.         <c:if test="${not empty error}">  
  17.             <p style="color:red">${error}</p>  
  18.         </c:if>  
  19.       <table>  
  20.          <tr>  
  21.             <td>用户名:</td>  
  22.             <td><input type="text" name="username"/></td>  
  23.          </tr>  
  24.          <tr>  
  25.             <td>密码:</td>  
  26.             <td><input type="password" name="password"/></td>  
  27.          </tr>  
  28.          <tr>  
  29.             <td colspan="2" align="center">  
  30.                 <input type="submit" value="登录"/>  
  31.                 <input type="reset" value="重置"/>  
  32.             </td>  
  33.          </tr>  
  34.       </table>  
  35.    </form>  
  36. </div>  
  37.   
  38. </body>  
  39. </html>  


其中action是/manager/login,和用户登录页中的/login是区分开的,这样利用myAuthenticationEntryPoint就可以根据路径返回到对应的登录界面,关键代码:

  1. /** 
  2.  * 登录失败控制 
  3.  *  
  4.  * @author HHL 
  5.  *  
  6.  * @date 2016年12月20日 
  7.  */  
  8. public class MyAuthenticationFailureHandler extends  
  9.         SimpleUrlAuthenticationFailureHandler {  
  10.     private MyAuthenticationEntryPoint loginEntry;  
  11.   
  12.     public MyAuthenticationEntryPoint getLoginEntry() {  
  13.         return loginEntry;  
  14.     }  
  15.   
  16.     public void setLoginEntry(MyAuthenticationEntryPoint loginEntry) {  
  17.         this.loginEntry = loginEntry;  
  18.     }  
  19.   
  20.     @Override  
  21.     public void onAuthenticationFailure(HttpServletRequest request,  
  22.             HttpServletResponse response, AuthenticationException exception)  
  23.             throws IOException, ServletException {  
  24.         // 从loginEntry中获取登录失败要跳转的url,并加上错误信息error  
  25.         String authenfailureUrl = this.loginEntry  
  26.                 .determineUrlToUseForThisRequest(request, response, exception);  
  27.         authenfailureUrl = authenfailureUrl + "?error";  
  28.         super.setDefaultFailureUrl(authenfailureUrl);  
  29.         super.onAuthenticationFailure(request, response, exception);  
  30.   
  31.     }  
  32.   
  33. }  

该类覆盖了父类的onAuthenticationFailure,根据请求路径,如果是“/manager/login”就和MyAuthenticationEntryPoint中的“/manager/**”相匹配,返回路径为“/manager/login”‘;“/login”的情况也类似,返回到“/login”;然后添加上?error,并设置到父类的setDefaultFailureUrl,由父类的onAuthenticationFailure执行跳转。

当然contoller中要如下配置:

  1. /** 
  2.  * @author HHL 
  3.  *  
  4.  *  
  5.  *         管理员控制类 
  6.  */  
  7. @Controller  
  8. public class ManagerController {  
  9.   
  10.     /** 
  11.      * 管理中心首页 
  12.      *  
  13.      * @param model 
  14.      * @return 
  15.      */  
  16.     @RequestMapping("/manager")  
  17.     public String login(Model model) {  
  18.         return "manager/index";  
  19.     }  
  20.       
  21.     /** 
  22.      * 显示登录页面用,主要是显示错误信息 
  23.      *  
  24.      * @param model 
  25.      * @param error 
  26.      * @return 
  27.      */  
  28.     @RequestMapping("/manager/login")  
  29.     public String login(Model model,  
  30.             @RequestParam(value = "error", required = false) String error) {  
  31.         if (error != null) {  
  32.             model.addAttribute("error""用户名或密码错误");  
  33.         }  
  34.         return "manager/login";  
  35.     }  
  36. }  

如果登录失败则error为"",满足不为null的条件


六、login-processing-url配置

既然两个登录页中的form action不同,那么login-processing-url配置对两者均要进行拦截:

  1. login-processing-url="/**/login"  

这里的"/**/login"对"/manager/login"和"/login"均能实现拦截,由UsernamePasswordAuthenticationFilter进行拦截,match部分是由Spring中的AntPathRequestMatcher实现的。

工作在父类AbstractAuthenticationProcessingFilter的requiresAuthentication方法

  1. /** 
  2.      * Indicates whether this filter should attempt to process a login request for the 
  3.      * current invocation. 
  4.      * <p> 
  5.      * It strips any parameters from the "path" section of the request URL (such as the 
  6.      * jsessionid parameter in <em>http://host/myapp/index.html;jsessionid=blah</em>) 
  7.      * before matching against the <code>filterProcessesUrl</code> property. 
  8.      * <p> 
  9.      * Subclasses may override for special requirements, such as Tapestry integration. 
  10.      * 
  11.      * @return <code>true</code> if the filter should attempt authentication, 
  12.      * <code>false</code> otherwise. 
  13.      */  
  14.     protected boolean requiresAuthentication(HttpServletRequest request,  
  15.             HttpServletResponse response) {  
  16.         return requiresAuthenticationRequestMatcher.matches(request);  
  17.     }  

可见UsernamePasswordAuthenticationFilter完成了用户的登录工作(用户是否存在,密码是否正确,和数据源只能的用户信息对比)


七、access-denied-handler

访问拒绝,该配置中有两种用户权限'ROLE_USER'和'ROLE_MANAGER',当用户登录时具有'ROLE_USER'权限,当管理员登录时具有'ROLE_MANAGER'权限;因此当用户登录的情况下访问管理中心,这个时候权限就不充分,Security系统会抛403错误,拒绝访问,那么这里就需要配置错误页,根据access-denied-handler标签就可以配置

  1. <!-- 登录成功后拒绝访问跳转的页面 -->         
  2.         <access-denied-handler error-page="/security/deny" />  


路径为"/security/deny"

  1. /** 
  2.  * security控制类 
  3.  *  
  4.  * @author HHL 
  5.  *  
  6.  * @date 2016年12月20日 
  7.  */  
  8. @Controller  
  9. public class SecurityController {  
  10.   
  11.     /** 
  12.      * 拒绝访问时跳转页面 
  13.      *  
  14.      * @param request 
  15.      * @param response 
  16.      * @return 
  17.      */  
  18.     @RequestMapping("/security/deny")  
  19.     public String deny(HttpServletRequest request,HttpServletResponse response){  
  20.         return "security_deny";  
  21.     }  
  22. }  

页面为security_deny.jsp

  1. <%@ page language="java" pageEncoding="UTF-8" contentType="text/html;charset=UTF-8"%>  
  2. <%@ include file="../includes/taglibs.jsp"%>  
  3. <!DOCTYPE html>  
  4. <html>  
  5. <head>  
  6.     <title>Mango-deny</title>  
  7.     <meta name="menu" content="home" />      
  8. </head>  
  9. <body>  
  10. <h1>对不起,您没有权限访问该页面!</h1>  
  11.          
  12. <div style="text-align:center">  
  13.     <img src="<c:url value='/resources/images/nonono.jpg'/>"/>  
  14.     <p>  
  15.         <a href="<c:url value='/'/>">首页</a>  
  16.         <a href="<c:url value='/manager'/>">管理中心</a>  
  17.         <a href="<c:url value='/logout'/>" >退出登录</a>  
  18.     </p>  
  19. </div>  
  20. </body>  
  21. </html>  


效果如下:




完整代码如下:http://download.csdn.net/detail/honghailiang888/9719715

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值