`

spring security ajax

阅读更多

转自 http://loianegroner.com/2010/02/integrating-spring-security-with-extjs-login-page/

 

This tutorial will walk through how to configure ExtJS Login form (Ajax login form) instead of default Spring Security login.jsp.

Instead of using login.jsp from spring security, why do not use an ajax login form?

And How to integrate the ExtJS Login Form with Spring Security ?

You did try to do it, the user is successfully authenticated, but the user is not redirected to the application main page. How to fix this situation? How to make it work?

It does not matter if you set the default-target-url in applicationContext-security.xml, or set a redirect URL on server side. It will not work this way.

The issue is that ExtJS make Ajax calls, and no redirect will work on server side. You have to redirect it on the client side, which is the ExtJS/javascript code.

First, you need to create the login form. You can use the javascript code provided by ExtJS and you can modify it to work with spring security.

If you take a look at the login.jsp, you will see three key points:

  1. URL / form action: j_spring_security_check
  2. Username input name: j_username
  3. Password input name: j_password

That is what you need to customize to make ExtJS Login form works! But do not be too comfortable, there are some issues you need to fix to make it work perfectly.

Take a look how login.js looks like (after customization):

01 Ext.onReady( function (){
02      Ext.QuickTips.init();
03  
04      // Create a variable to hold our EXT Form Panel.
05  
06      // Assign various config options as seen.
07      var login = new Ext.FormPanel({
08          labelWidth:80,
09          url: 'j_spring_security_check' ,
10          frame: true ,
11          title: 'Please Login' ,
12  
13          defaultType: 'textfield' ,
14          width:300,
15          height:150,
16          monitorValid: true ,
17          // Specific attributes for the text fields for username / password.
18          // The "name" attribute defines the name of variables sent to the server.
19  
20          items:[{
21              fieldLabel: 'Username' ,
22              name: 'j_username' ,
23              allowBlank: false
24          },{
25              fieldLabel: 'Password' ,
26  
27              name: 'j_password' ,
28              inputType: 'password' ,
29              allowBlank: false
30          }],
31  
32          // All the magic happens after the user clicks the button
33          buttons:[{
34  
35              text: 'Login' ,
36              formBind: true ,
37              // Function that fires when user clicks the button
38              handler: function (){
39              login.getForm().submit({
40  
41                  method: 'POST' ,
42  
43                  // Functions that fire (success or failure) when the server responds.
44                  // The server would actually respond with valid JSON,
45                  // something like: response.write "{ success: true}" or
46  
47                  // response.write "{ success: false, errors: { reason: 'Login failed. Try again.' }}"
48                  // depending on the logic contained within your server script.
49                  // If a success occurs, the user is notified with an alert messagebox,
50  
51                  // and when they click "OK", they are redirected to whatever page
52                  // you define as redirect.
53  
54                  success: function (){
55                  Ext.Msg.alert( 'Status' , 'Login Successful!' , function (btn, text){
56  
57                      if (btn == 'ok' ){
58                          window.location = 'main.action' ;
59                      }
60                  });
61  
62              },
63  
64              // Failure function, see comment above re: success and failure.
65              // You can see here, if login fails, it throws a messagebox
66              // at the user telling him / her as much.
67  
68              failure: function (form, action){
69                  if (action.failureType == 'server' ){
70                      obj = Ext.util.JSON.decode(action.response.responseText);
71  
72                      Ext.Msg.alert( 'Login Failed!' , obj.errors.reason);
73                  } else {
74                      Ext.Msg.alert( 'Warning!' , 'Authentication server is unreachable : ' + action.response.responseText);
75  
76                  }
77                  login.getForm().reset();
78              }
79  
80              });
81          }
82          }]
83      });
84  
85      login.render( 'login' );
86  
87 });

If you make these changes and try to execute the application with a basic applicationContext-security.xml file, the user will be successfully authenticated, but is not going to be redirected.

What are we missing then?

You need to customize AuthenticationProcessingFilter class for spring security to perform actions on login.

The “onSuccessfulAuthentication” and “onUnsuccessfulAuthentication” methods need to return some JSON content. If user is successfully authenticated, then redirect to main page, otherwise, the application will show an error message.

This is MyAuthenticationProcessingFilter class:

01 package com.loiane.security;
02  
03 import java.io.IOException;
04 import java.io.Writer;
05  
06 import javax.servlet.http.HttpServletRequest;
07 import javax.servlet.http.HttpServletResponse;
08 import javax.servlet.http.HttpServletResponseWrapper;
09  
10 import org.springframework.security.Authentication;
11 import org.springframework.security.AuthenticationException;
12 import org.springframework.security.ui.webapp.AuthenticationProcessingFilter;
13  
14 public class MyAuthenticationProcessingFilter extends AuthenticationProcessingFilter {
15  
16      protected void onSuccessfulAuthentication(HttpServletRequest request,
17              HttpServletResponse response, Authentication authResult)
18      throws IOException {
19          super .onSuccessfulAuthentication(request, response, authResult);
20  
21          HttpServletResponseWrapper responseWrapper = new HttpServletResponseWrapper(response);
22  
23          Writer out = responseWrapper.getWriter();
24  
25          String targetUrl = determineTargetUrl( request );
26          out.write( "{success:true, targetUrl : \'" + targetUrl + "\'}" );
27          out.close();
28  
29      }
30  
31      protected void onUnsuccessfulAuthentication( HttpServletRequest request,
32              HttpServletResponse response, AuthenticationException failed )
33      throws IOException {
34  
35          HttpServletResponseWrapper responseWrapper = new HttpServletResponseWrapper(response);
36  
37          Writer out = responseWrapper.getWriter();
38  
39          out.write( "{ success: false, errors: { reason: 'Login failed. Try again.' }}" );
40          out.close();
41  
42      }
43  
44 }

And this is how applicationContext-security.xml looks like :

01 <? xml version = "1.0" encoding = "UTF-8" ?>
02  
04      xmlns:security = "http://www.springframework.org/schema/security "
05      xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance "
08  
09      < security:global-method-security />
10  
11      < security:http auto-config = "false" entry-point-ref = "authenticationProcessingFilterEntryPoint" >
12          < security:intercept-url pattern = "/index.jsp" filters = "none" />
13          < security:intercept-url pattern = "/*.action" access = "ROLE_USER" />
14      </ security:http >
15  
16      < bean id = "authenticationProcessingFilter" class = "com.loiane.security.MyAuthenticationProcessingFilter" >
17          < security:custom-filter position = "AUTHENTICATION_PROCESSING_FILTER" />
18          < property name = "defaultTargetUrl" value = "/main.html" />
19          < property name = "authenticationManager" ref = "authenticationManager" />
20      </ bean >
21  
22      < security:authentication-manager alias = "authenticationManager" />
23  
24      < bean id = "authenticationProcessingFilterEntryPoint"
25          class = "org.springframework.security.ui.webapp.AuthenticationProcessingFilterEntryPoint" >
26          < property name = "loginFormUrl" value = "/index.jsp" />
27          < property name = "forceHttps" value = "false" />
28      </ bean >
29  
30      <!--
31      Usernames/Passwords are
32          rod/koala
33          dianne/emu
34          scott/wombat
35          peter/opal
36      These passwords are from spring security app example
37      -->
38      < security:authentication-provider >
39          < security:password-encoder hash = "md5" />
40          < security:user-service >
41              < security:user name = "rod" password = "a564de63c2d0da68cf47586ee05984d7" authorities = "ROLE_SUPERVISOR, ROLE_USER, ROLE_TELLER" />
42              < security:user name = "dianne" password = "65d15fe9156f9c4bbffd98085992a44e" authorities = "ROLE_USER,ROLE_TELLER" />
43              < security:user name = "scott" password = "2b58af6dddbd072ed27ffc86725d7d3a" authorities = "ROLE_USER" />
44              < security:user name = "peter" password = "22b5c9accc6e1ba628cedc63a72d57f8" authorities = "ROLE_USER" />
45          </ security:user-service >
46      </ security:authentication-provider >
47 </ beans >

Now you can login using ExtJS login form.

I coded a sample application for this example. If you like it, you can download it from my GitHub: http://github.com/loiane/spring-security-extjs-login

Happy coding!

分享到:
评论

相关推荐

    “推荐系统”相关资源推荐

    推荐了国内外对推荐系统的讲解相关资源

    全渠道电商平台业务中台解决方案.pptx

    全渠道电商平台业务中台解决方案.pptx

    云计算企业私有云平台建设方案.pptx

    云计算企业私有云平台建设方案.pptx

    通过CNN卷积神经网络对盆栽识别-含图片数据集.zip

    本代码是基于python pytorch环境安装的。 下载本代码后,有个requirement.txt文本,里面介绍了如何安装环境,环境需要自行配置。 或可直接参考下面博文进行环境安装。 https://blog.csdn.net/no_work/article/details/139246467 如果实在不会安装的,可以直接下载免安装环境包,有偿的哦 https://download.csdn.net/download/qq_34904125/89365780 安装好环境之后, 代码需要依次运行 01数据集文本生成制作.py 02深度学习模型训练.py 和03pyqt_ui界面.py 数据集文件夹存放了本次识别的各个类别图片。 本代码对数据集进行了预处理,包括通过在较短边增加灰边,使得图片变为正方形(如果图片原本就是正方形则不会增加灰边),和旋转角度,来扩增增强数据集, 运行01数据集文本制作.py文件,会就读取数据集下每个类别文件中的图片路径和对应的标签 运行02深度学习模型训练.py就会将txt文本中记录的训练集和验证集进行读取训练,训练好后会保存模型在本地

    0.96寸OLED显示屏

    尺寸与分辨率:该显示屏的尺寸为0.96英寸,常见分辨率为128x64像素,意味着横向有128个像素点,纵向有64个像素点。这种分辨率足以显示基本信息和简单的图形。 显示技术:OLED(有机发光二极管)技术使得每个像素都能自发光,不需要背光源,因此对比度高、色彩鲜艳、视角宽广,且在低亮度环境下表现更佳,同时能实现更低的功耗。 接口类型:这种显示屏通常支持I²C(IIC)和SPI两种通信接口,有些型号可能还支持8080或6800并行接口。I²C接口因其简单且仅需两根数据线(SCL和SDA)而广受欢迎,适用于降低硬件复杂度和节省引脚资源。 驱动IC:常见的驱动芯片为SSD1306,它负责控制显示屏的图像显示,支持不同显示模式和刷新频率的设置。 物理接口:根据型号不同,可能有4针(I²C接口)或7针(SPI接口)的物理连接器。 颜色选项:虽然大多数0.96寸OLED屏为单色(通常是白色或蓝色),但也有双色版本,如黄蓝双色,其中屏幕的一部分显示黄色,另一部分显示蓝色。

    2024年欧洲高端家用P1.29 LED显示屏市场主要企业市场占有率及排名.docx

    2024年欧洲高端家用P1.29 LED显示屏市场主要企业市场占有率及排名

    5G智慧校园顶层设计方案.pptx

    5G智慧校园顶层设计方案.pptx

    在Delphi编程环境下实现上位机与PLC的串行通信

    介绍了通过引进 ActiveX控件 MSComm ,在 Delphi 6. 0 编程环境下 ,实现上位机与 Omron C200H PLC串行通信的一般方法 ,并给出了工程实例。该方法简单可靠、便于移植、实用性强 ,在工业控制中有着广泛的用途。

    程序设计训练之 Rust 编程语言 第四讲:泛型、特型与生命周期

    程序设计训练之 Rust 编程语言 第四讲:泛型、特型与生命周期

    山寨版的神州数码802.1x认证supplicant,基于pcap库的C语言的跨平台的原生客户端。.zip

    山寨版的神州数码802.1x认证supplicant,基于pcap库的C语言的跨平台的原生客户端。

    数字乡村建设方案.pptx

    数字乡村建设方案.pptx

    基于CRT(远程访问终端)+ARM(GEC)+Linux+C语言的视频监控系统.zip

    基于CRT(远程访问终端)+ARM(GEC)+Linux+C语言的视频监控系统

    建筑结构水电欧式6套(14.5x20.2)\施工图\A型施工图-建筑-空施00.dwg

    建筑结构水电欧式6套(14.5x20.2)\施工图\A型施工图-建筑-空施00.dwg

    基于ThinkPHP8.0搭建的后台管理系统EasyAdmin8

    该资源内项目源码是个人的课程设计、毕业设计,代码都测试ok,都是运行成功后才上传资源,答辩评审平均分达到96分,放心下载使用! ## 项目备注 1、该资源内项目代码都经过测试运行成功,功能ok的情况下才上传的,请放心下载使用! 2、本项目适合计算机相关专业(如计科、人工智能、通信工程、自动化、电子信息等)的在校学生、老师或者企业员工下载学习,也适合小白学习进阶,当然也可作为毕设项目、课程设计、作业、项目初期立项演示等。 3、如果基础还行,也可在此代码基础上进行修改,以实现其他功能,也可用于毕设、课设、作业等。 下载后请首先打开README.md文件(如有),仅供学习参考, 切勿用于商业用途。 该资源内项目源码是个人的课程设计,代码都测试ok,都是运行成功后才上传资源,答辩评审平均分达到96分,放心下载使用! ## 项目备注 1、该资源内项目代码都经过测试运行成功,功能ok的情况下才上传的,请放心下载使用! 2、本项目适合计算机相关专业(如计科、人工智能、通信工程、自动化、电子信息等)的在校学生、老师或者企业员工下载学习,也适合小白学习进阶,当然也可作为毕设项目、课程设计、作业、项目初期立项演示等。 3、如果基础还行,也可在此代码基础上进行修改,以实现其他功能,也可用于毕设、课设、作业等。 下载后请首先打开README.md文件(如有),仅供学习参考, 切勿用于商业用途。

    21121344 马丽娟.doc

    21121344 马丽娟.doc

    C++与操作系统等面试题63

    C++与操作系统等面试题63

    【工具模型】麦肯锡咨询师常用模型.pptx

    【工具模型】麦肯锡咨询师常用模型.pptx

    《LEARNING Vue.js》是一本免费电子书,由Stack Overflow社区的贡献者们创建和编写

    这本书的内容汇集了来自Stack Overflow上关于Vue.js的高质量回答和讨论,旨在帮助读者学习和掌握Vue.js框架的基本知识和应用技巧。 书籍特点: 社区贡献:内容来源于Stack Overflow社区中经验丰富的开发者,他们分享了自己的知识和解决方案。 免费获取:这本书可以免费获取,适合希望以低成本学习Vue.js的读者。 实用性强:内容包括实际问题的解决方案和最佳实践,帮助读者在真实项目中应用所学知识。 适合读者: 初学者:刚开始学习Vue.js,希望通过实际问题的解决方案来理解基本概念的读者。 有经验的开发者:希望深入了解Vue.js的具体应用和最佳实践,并从社区经验中受益的开发者。

    cy的python作业.zip

    Python零基础,大作业,加强,复习巩固!!!

Global site tag (gtag.js) - Google Analytics