SpringSecurity学习四-自定义Login请求和返回的数据格式

非常感谢https://blog.csdn.net/lee353086/article/details/52610205

SpringSecurity技术学习,更多知识请访问https://www.itkc8.com

环境
 [1]Spring 3.1.2
 [2]Tomcat 7.0.68
 
概要
    完美的解决了《学习三》中自定义login方法得绕过Spring Security部份class的缺陷。
最新的例子,解决以下问题
[1]如果login递交的数据,要求验证“验证码”怎么办。
[2]若访问页面没有权限,返回json形式的错误提示。
[3]若login递交的数据非法,返回json形式的错误提示。
[4]若login递交的数据合法,返回json形式的提示。
[5]同个帐号只能同时一次有效,若异地已经登录了这个帐号,会自动把它踢掉。
[6]如何查看登录到Web App的所有用户信息。


也能解决
[1]若已经在其它地方登录的帐户,可以提个醒,你已经把其它地方登录的这个帐号踢掉了。
通过修改MyAuthenticationFilter.java。
[2]若你已经在其它地方登录,不允许再登录。
通过修改spring-security.xml。

   正文中会介绍下主要类的功能,然后直接上代码。
   《学习二》中未动的代码,这里不重复贴了。

   本文的例子在Chrome和Firefox下测试通过。

  理解整个Demo建议从spring-security.xml文件开始。

 

正文
相对于《学习二》这里最重要的是五个java文件,一个配置文件,必须要深刻理解它们之间的关系和功能。

MyAuthenticationEntryPoint.java
当用户没有权限访问某个资源的时候,你可以在这里自定义返回内容。

MyAuthenticationFilter.java
自定义login请求的格式,比如你想上传json格式的请求,可以在这里处理。
并验证用户的请求是否合法,如果不合法你可以抛出继承自AuthenticationException的Exception

MyAuthenticationException.java
继承AuthenticationException,在MyAuthenticationFilter中抛出后,交给MyAuthenticationFailureHandler处理

MyAuthenticationFailureHandler.java
当login失败,这里可以自定义返回的错误信息。

MyAuthenticationSuccessHandler.java
如何登录成功,这里可以自定义返回的成功信息。

配置文件
web.xml

 
  1. xmlns="http://java.sun.com/xml/ns/javaee"

  2. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"

  3. id="schedule-console" version="3.0">

  4. Archetype Created Web Application

  5.  
  6. encodingFilter

  7. org.springframework.web.filter.CharacterEncodingFilter

  8. encoding

  9. UTF-8

  10.  
  11. encodingFilter

  12. /*

  13.  
  14. contextConfigLocation

  15. /WEB-INF/spring-servlet.xml,/WEB-INF/spring-security.xml

  16.  
  17. org.springframework.web.context.ContextLoaderListener

  18.  
  19. org.springframework.security.web.session.HttpSessionEventPublisher

  20.  
  21. springSecurityFilterChain

  22. org.springframework.web.filter.DelegatingFilterProxy

  23.  
  24. springSecurityFilterChain

  25. /*

  26.  
  27. spring

  28. org.springframework.web.servlet.DispatcherServlet

  29. 1

  30.  
  31. spring

  32. *.do

  33.  
  34. index.jsp

  35.  
  36. 404

  37. /My404.jsp

  38.  
  39. java.lang.Exception

  40. /MyEception.jsp



spring-security.xml

 
  1. xmlns:b="http://www.springframework.org/schema/beans"

  2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

  3. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

  4. http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd">

  5.  
  6.  
  7. entry-point-ref="authenticationEntryPoint">

  8. logout-success-url="/main/customLogin.do"

  9. invalidate-session="true" />

  10.  
  11.  
  12.  
  13.  
  14.  
  15. class="org.springframework.security.web.session.ConcurrentSessionFilter">

  16.  
  17. class="com.nuoke.MyAuthenticationFilter">

  18.  
  19.  
  20. class="com.nuoke.MyFilterSecurityInterceptor">

  21.  
  22.  
  23.  
  24. class="com.nuoke.MyAccessDecisionManager">

  25.  
  26. class="org.springframework.security.web.authentication.session.ConcurrentSessionControlStrategy">

  27.  
  28. class="com.nuoke.MyInvocationSecurityMetadataSource" />


 

java文件

MyAuthenticationEntryPoint.java

 
  1. package com.nuoke;

  2.  
  3. import java.io.IOException;

  4.  
  5. import javax.servlet.ServletException;

  6. import javax.servlet.http.HttpServletRequest;

  7. import javax.servlet.http.HttpServletResponse;

  8.  
  9. import org.springframework.security.core.AuthenticationException;

  10. import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;

  11.  
  12. public class MyAuthenticationEntryPoint extends LoginUrlAuthenticationEntryPoint{

  13. //当访问的资源没有权限,会调用这里

  14. @Override

  15. public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException)

  16. throws IOException, ServletException {

  17. //super.commence(request, response, authException);

  18.  
  19. //返回json形式的错误信息

  20. response.setCharacterEncoding("UTF-8");

  21. response.setContentType("application/json");

  22.  
  23. response.getWriter().println("{\"ok\":0,\"msg\":\""+authException.getLocalizedMessage()+"\"}");

  24. response.getWriter().flush();

  25. }

  26. }


MyAuthenticationException.java

 
  1. package com.nuoke;

  2.  
  3. import org.springframework.security.core.AuthenticationException;

  4.  
  5. public class MyAuthenticationException extends AuthenticationException {

  6.  
  7. /**

  8. *

  9. */

  10. private static final long serialVersionUID = 1L;

  11.  
  12. public MyAuthenticationException(String msg) {

  13. super(msg);

  14. // TODO Auto-generated constructor stub

  15. }

  16.  
  17. }


MyAuthenticationFailureHandler.java

 
  1. package com.nuoke;

  2.  
  3. import java.io.IOException;

  4.  
  5. import javax.servlet.ServletException;

  6. import javax.servlet.http.HttpServletRequest;

  7. import javax.servlet.http.HttpServletResponse;

  8. import javax.servlet.http.HttpSession;

  9.  
  10. import org.springframework.security.core.AuthenticationException;

  11. import org.springframework.security.web.WebAttributes;

  12. import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;

  13.  
  14. public class MyAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler{

  15. @Override

  16. public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,

  17. AuthenticationException exception) throws IOException, ServletException {

  18. // Example1(request,response,exception);

  19. // Example2(request,response,exception);

  20. Example3(request,response,exception);

  21. }

  22.  
  23. private void Example1(HttpServletRequest request, HttpServletResponse response,

  24. AuthenticationException exception) throws IOException, ServletException

  25. {

  26. //例1:直接返回字符串

  27. response.setCharacterEncoding("UTF-8");

  28. response.setContentType("application/json");

  29.  
  30. response.getWriter().println("{\"ok\":0,\"msg\":\""+exception.getLocalizedMessage()+"\"}");

  31. }

  32.  
  33. private void Example2(HttpServletRequest request, HttpServletResponse response,

  34. AuthenticationException exception) throws IOException, ServletException

  35. {

  36. String strUrl = request.getContextPath() + "/customLoginResponse.jsp";

  37. request.getSession().setAttribute("ok", 0);

  38. request.getSession().setAttribute("message", exception.getLocalizedMessage());

  39. request.getSession().setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, exception);

  40. super.onAuthenticationFailure(request, response, exception);

  41. }

  42.  
  43. private void Example3(HttpServletRequest request, HttpServletResponse response,

  44. AuthenticationException exception) throws IOException, ServletException

  45. {

  46. //例3:自定义跳转到哪个URL

  47. //假设login.jsp在webapp路径下

  48. //注意:不能访问WEB-INF下的jsp。

  49. String strUrl = request.getContextPath() + "/customLoginResponse.jsp";

  50. request.getSession().setAttribute("ok", 0);

  51. request.getSession().setAttribute("message", exception.getLocalizedMessage());

  52. request.getSession().setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, exception);

  53. //Error request.getRequestDispatcher(strUrl).forward(request, response);

  54. response.sendRedirect(strUrl);

  55. }

  56. }


MyAuthenticationFilter.java

 
  1. package com.nuoke;

  2.  
  3. import java.util.Enumeration;

  4.  
  5. import javax.servlet.http.HttpServletRequest;

  6. import javax.servlet.http.HttpServletResponse;

  7. import javax.servlet.http.HttpSession;

  8.  
  9. import org.springframework.security.core.Authentication;

  10. import org.springframework.security.core.AuthenticationException;

  11. import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

  12.  
  13. /*

  14. * 说明:

  15. * UsernamePasswordAuthenticationFilter用于处理来自表单提交的认证。该表单必须提供对应的用户名和密码,

  16. * 对应的参数名默认为j_username和j_password。

  17. * 如果不想使用默认的参数名,可以通过UsernamePasswordAuthenticationFilter的usernameParameter和passwordParameter进行指定。

  18. * 表单的提交路径默认是“j_spring_security_check”,可以通过UsernamePasswordAuthenticationFilter的filterProcessesUrl进行指定。

  19. * 通过属性postOnly可以指定只允许登录表单进行post请求,默认是true。

  20. */

  21.  
  22. public class MyAuthenticationFilter extends UsernamePasswordAuthenticationFilter{

  23. public Authentication attemptAuthentication(HttpServletRequest request,

  24. HttpServletResponse response) throws AuthenticationException {

  25. //这里可以抛出继承自AuthenticationException的exception

  26. //然后会转到MyAuthenticationFailureHandler。

  27. //比如说验证码什么的可以在这里验证,然后抛出异常。

  28. //然后让MyAuthenticationFailureHandler去处理,并输出返回

  29.  
  30. //下面的代码段是具体的示例

  31. //当用户输入的用户名为“123”抛出自定义的AuthenticationException异常。

  32. String username = request.getParameter("username");

  33. if(username.equals("123"))

  34. {

  35. throw new MyAuthenticationException("测试异常被MyAuthenticationFailureHandler处理");

  36.  
  37. }

  38.  
  39. return super.attemptAuthentication(request, response);

  40. }

  41. }


MyAuthenticationSuccessHandler.java

 
  1. package com.nuoke;

  2.  
  3. import java.io.IOException;

  4.  
  5. import javax.servlet.ServletException;

  6. import javax.servlet.http.HttpServletRequest;

  7. import javax.servlet.http.HttpServletResponse;

  8.  
  9. import org.springframework.security.core.Authentication;

  10. import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;

  11.  
  12.  
  13. public class MyAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler{

  14. @Override

  15. public void onAuthenticationSuccess(HttpServletRequest request,

  16. HttpServletResponse response,

  17. Authentication authentication) throws ServletException, IOException

  18. {

  19. //例1:不跳到XML设定的页面,而是直接返回json字符串

  20. response.setCharacterEncoding("UTF-8");

  21. response.setContentType("application/json");

  22.  
  23. response.getWriter().println("{\"ok\":\"1\",\"msg\":\"登录成功\"}");

  24.  
  25. //例2:跳转到XML中设定的URL。其实已经没有定义这个class的意义

  26. //super.onAuthenticationSuccess(request, response, authentication);

  27.  
  28. //例3:自定义跳转到哪个URL

  29. //http://cl315917525.iteye.com/blog/1768396

  30. }

  31. }


MyController.java

 
  1. package com.nuoke.controller;

  2.  
  3. import java.util.ArrayList;

  4. import java.util.List;

  5.  
  6. import javax.servlet.http.HttpServletRequest;

  7. import javax.servlet.http.HttpSession;

  8.  
  9. import org.springframework.beans.factory.annotation.Autowired;

  10. import org.springframework.beans.factory.annotation.Qualifier;

  11. import org.springframework.security.authentication.AuthenticationManager;

  12. import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;

  13. import org.springframework.security.core.Authentication;

  14. import org.springframework.security.core.AuthenticationException;

  15. import org.springframework.security.core.context.SecurityContextHolder;

  16. import org.springframework.security.core.session.SessionRegistry;

  17. import org.springframework.security.core.userdetails.User;

  18. import org.springframework.stereotype.Controller;

  19. import org.springframework.web.bind.annotation.RequestMapping;

  20. import org.springframework.web.bind.annotation.RequestParam;

  21. import org.springframework.web.servlet.ModelAndView;

  22.  
  23. @Controller

  24. @RequestMapping(value = "/main")

  25. public class MyController {

  26. @Autowired

  27. @Qualifier("sessionRegistry")

  28. private SessionRegistry sessionRegistry;

  29.  
  30. @RequestMapping(value = "/admin.do")

  31. public ModelAndView adminPage() {

  32. ModelAndView model = new ModelAndView();

  33. model.addObject("title", "Spring Security Hello World");

  34. model.addObject("message", "这是一个安全被保护的页面!");

  35. //在MyInvocationSecurityMetadataSource类中指定了保护。

  36. model.setViewName("admin");

  37.  
  38. return model;

  39. }

  40.  
  41. @RequestMapping(value = "/welcome.do")

  42. public ModelAndView WelcomeAction() {

  43. this.PrintAllOnlineUser();

  44. ModelAndView model = new ModelAndView();

  45. model.addObject("title", "Spring Security Hello World");

  46. model.addObject("message", "这是一个欢迎页面!");

  47. model.setViewName("welcome");

  48. return model;

  49. }

  50.  
  51. //打印在线用户

  52. void PrintAllOnlineUser()

  53. {

  54. List principals = sessionRegistry.getAllPrincipals();

  55.  
  56. List usersNamesList = new ArrayList();

  57.  
  58. for (Object principal: principals) {

  59. if (principal instanceof User) {

  60. usersNamesList.add(((User) principal).getUsername());

  61. }

  62. }

  63.  
  64. System.out.println("count:"+usersNamesList.size()+"=>"+usersNamesList.toString());

  65. }

  66.  
  67. @RequestMapping(value="/customLogin.do")

  68. public String customLoginAction(HttpServletRequest request){

  69. return "customLogin";

  70. }

  71. }//end class



  72. jsp文件
    webapp目录下的

    customLoginResponse.jsp

     
    1. <%@ page language="java" import="java.util.*,java.text.*" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

    2. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

    3. {"ok":${sessionScope.ok},"msg":"${sessionScope.message}","SPRING_SECURITY_LAST_EXCEPTION":"${sessionScope.SPRING_SECURITY_LAST_EXCEPTION}"}


    MyException.jsp

     
    1. <%@ page contentType="text/html;charset=UTF-8" language="java" %>

    2. <%

    3. Exception ex = (Exception) request.getAttribute("Exception");

    4. String strMsg = "未知错误";

    5. if(ex!=null)

    6. strMsg = ex.getMessage();

    7. %>

    8. {"ok":"0","msg":"<%=strMsg%>"}


    sessionExpired.jsp

     
    1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

    2. <%

    3. String path = request.getContextPath();

    4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

    5. %>

    6. {"ok":0,"msg":"你已经在其它地方登录!"}


    My404.jsp

     
    1. <%@ page language="java" contentType="text/html; charset=UTF-8"

    2. pageEncoding="UTF-8"%>

    3. {"ok":0,"msg":"404错误"}


    WEB-INF/view目录下的

    customLogin.jsp

     
    1. <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

    2. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

    3. 自定义登录控制

    4.  
    5.  
    6. 示例二 自定义login方法

    7.  


     


    总结
       太庞大复杂,不敢用在现有的项目当中,怕又出现新的坑,打算以后新的项目中尝试Spring Security框架。

     

    常见问题

    Q MyAuthenticationFilter不会被调用的问题

    如果你使用了类似下面的语句

    排除哪些url  pattern spring security不检查权限,

    则指定login路径的时候不能在public路径下,如下,下面用main代替了public:

    问题解决。

    SpringSecurity技术学习,更多知识请访问https://www.itkc8.com
       
    参考资料
    [1]《Spring Security and JSON Authentication》
    继承UsernamePasswordAuthenticationFilter实现json形式的登录
    http://stackoverflow.com/questions/19500332/spring-security-and-json-authentication
    [2]失败返回json字符串
    http://blog.csdn.net/jmppok/article/details/44832641

    你可能感兴趣的:(系统架构,用户系统)