Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
Clear All
new posts

    Relogin with tomcat form authentication

    After read several tutorials and docs about login and relogin.
    I decided to write simple code geting me how to write program wich relogin
    I wrote it, but I have questions.
    I use LGPL wersion SmartGWT

    Here is code my program:
    Structure
    Code:
    war
    +- WEB_INF
    |  +- logintest
    |  |  +- ...
    |  +- lib
    |  |  +- ...
    |  +- web.xml
    +- LoginFormRequired.html
    +- LoginTest.css
    +- LoginTest.html
    +- resp.jsp
    LoginTest.java (EntryPoint)
    Code:
    package pl.miko.test.client;
    
    import java.util.HashMap;
    import java.util.Map;
    
    import com.google.gwt.core.client.EntryPoint;
    import com.smartgwt.client.rpc.LoginRequiredCallback;
    import com.smartgwt.client.rpc.RPCCallback;
    import com.smartgwt.client.rpc.RPCManager;
    import com.smartgwt.client.rpc.RPCRequest;
    import com.smartgwt.client.rpc.RPCResponse;
    import com.smartgwt.client.types.TitleOrientation;
    import com.smartgwt.client.util.SC;
    import com.smartgwt.client.widgets.IButton;
    import com.smartgwt.client.widgets.Window;
    import com.smartgwt.client.widgets.form.DynamicForm;
    import com.smartgwt.client.widgets.form.fields.BlurbItem;
    import com.smartgwt.client.widgets.form.fields.ButtonItem;
    import com.smartgwt.client.widgets.form.fields.PasswordItem;
    import com.smartgwt.client.widgets.form.fields.TextItem;
    import com.smartgwt.client.widgets.form.fields.events.ClickEvent;
    import com.smartgwt.client.widgets.form.fields.events.ClickHandler;
    import com.smartgwt.client.widgets.form.fields.events.KeyPressEvent;
    import com.smartgwt.client.widgets.form.fields.events.KeyPressHandler;
    
    /**
     * Entry point classes define <code>onModuleLoad()</code>.
     */
    public class LoginTest implements EntryPoint {
      private static final String CREDENTIALS_URL = "j_security_check";
    	private LoginWindow loginWindow;
    	private LoginForm loginForm;
    
    	public void onModuleLoad() {
    
    		RPCManager.setLoginRequiredCallback(new LoginRequiredCallback() {
    			@Override
    			public void loginRequired(int i, RPCRequest rpcRequest,
    					RPCResponse rpcResponse) {
    				if (loginWindow == null)
    					loginWindow = new LoginWindow();
    				if (!(loginWindow.isVisible() && loginWindow.isDrawn())) {
    					loginForm.clearValues();
    					loginForm.focusInItem("username");
    				}
    				loginWindow.show();
    				loginWindow.bringToFront();
    			}
    
    		});
    		
    
        IButton button2 = new IButton("Hello World 2");
        button2.addClickHandler(new com.smartgwt.client.widgets.events.ClickHandler() {
          @Override
          public void onClick(com.smartgwt.client.widgets.events.ClickEvent event) {
            RPCRequest request = new RPCRequest();
            // Note data could be a String, Map or Record
            request.setData("Some data to send to the client");
            request.setActionURL("resp.jsp");
           
            RPCManager.sendRequest(request, 
                new RPCCallback () {
                    public void execute(RPCResponse response, Object rawData, RPCRequest request) {
                        SC.say("Response from the server:" + rawData);
                    }
                }
            );   
          }
        });
        button2.draw();
        
    	}
    
    	public class LoginWindow extends Window {
    
    		public LoginWindow() {
    			loginForm = new LoginForm(CREDENTIALS_URL);
    			setShowModalMask(true);
    			centerInPage();
    			setShowCloseButton(false);
    			setShowMinimizeButton(false);
    			setIsModal(true);
    			setAutoSize(true);
    			addItem(loginForm);
    		}
    	}
    
    	private class LoginForm extends DynamicForm {
    		private String credentialsURL;
    
    		public LoginForm(String credentialsURL) {
    			this.credentialsURL = credentialsURL;
    			BlurbItem blurbItem = new BlurbItem("loginFailure");
    			blurbItem.setVisible(false);
    			blurbItem.setColSpan(2);
    			blurbItem.setDefaultValue("Invalid username or password");
    			blurbItem.setCellStyle("formCellError");
    			TextItem textItem = new TextItem("username");
    			textItem.setTitleOrientation(TitleOrientation.LEFT);
    			textItem.addKeyPressHandler(new KeyPressHandler() {
    				@Override
    				public void onKeyPress(KeyPressEvent keyPressEvent) {
    					if (keyPressEvent.getKeyName().equals("Enter")) {
    						focusInItem("password");
    					}
    				}
    			});
    			PasswordItem passwordItem = new PasswordItem("password");
    			passwordItem.setTitleOrientation(TitleOrientation.LEFT);
    			passwordItem.addKeyPressHandler(new KeyPressHandler() {
    				@Override
    				public void onKeyPress(KeyPressEvent keyPressEvent) {
    					if (keyPressEvent.getKeyName().equals("Enter")) {
    						doLogin();
    					}
    				}
    			});
    			ButtonItem buttonItem = new ButtonItem("Login");
    			buttonItem.addClickHandler(new ClickHandler() {
    
    				@Override
    				public void onClick(ClickEvent event) {
    					doLogin();
    				}
    
    			});
    			setFields(blurbItem, textItem, passwordItem, buttonItem);
    		}
    
    		public void doLogin() {
    			RPCRequest request = new RPCRequest();
    			request.setContainsCredentials(true);
    			request.setActionURL(credentialsURL);
    			request.setUseSimpleHttp(true);
    			request.setShowPrompt(false);
    			Map<String, String> params = new HashMap<String, String>();
    			params.put("j_username", getValueAsString("username"));
    			params.put("j_password", getValueAsString("password"));
    			request.setParams(params);
    			RPCManager.sendRequest(request, new RPCCallback() {
    				@Override
    				public void execute(RPCResponse response, Object rawData,
    						RPCRequest request) {
    					clearValues();
    					if (response.getStatus() == RPCResponse.STATUS_SUCCESS) {
    						hideItem("loginFailure");
    						RPCManager.resendTransaction();
    						loginWindow.hide();
    					} else if (response.getStatus() == RPCResponse.STATUS_LOGIN_INCORRECT) {
    						showItem("loginFailure");
    					} else if (response.getStatus() == RPCResponse.STATUS_MAX_LOGIN_ATTEMPTS_EXCEEDED) {
    						SC.warn("Max login attempts exceeded.");
    					}
    					focusInItem("username");
    				}
    			});
    		}
    	}
    }
    LoginFormRequired.html
    Code:
    <SCRIPT>//'"]]>>isc_loginRequired
    //
    // Embed this whole script block VERBATIM into your login page to enable
    // SmartClient RPC relogin.
    
    
    
    if (!window.isc && document.domain && document.domain.indexOf(".") != -1 
    	&& !(new RegExp("^(\\d{1,3}\\.){3}\\d{1,3}$").test(document.domain))) 
    {
        while (document.domain.indexOf(".") != -1) {
            try {
                if (window.opener && window.opener.isc) break;
                if (window.top.isc) break;
                
                document.domain = document.domain.replace(/.*?\./, '');
            } catch (e) {
                try {
                    document.domain = document.domain.replace(/.*?\./, '');
                } catch (ee) {
                    break;
                }
            }
        } 
    }
    
    var isc = top.isc ? top.isc : window.opener ? window.opener.isc : null;
    if (isc && isc.RPCManager) isc.RPCManager.delayCall("handleLoginRequired", [window]);
    </SCRIPT>
    resp.jsp
    Code:
    <%
    System.out.println("resp.jsp called -> Metod: "+request.getMethod());
    out.println("Hello!"); 
    %>
    web.xml
    Code:
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:
      xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
          http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
      version="2.5" 
      xmlns="http://java.sun.com/xml/ns/javaee">
    
        <security-role>
            <role-name>ROLE_USER</role-name>
        </security-role>
    
        <security-constraint>
            <web-resource-collection>
                <web-resource-name>management pages</web-resource-name>
                <url-pattern>/secure/*</url-pattern>
                <url-pattern>resp.jsp</url-pattern>
            </web-resource-collection>
            <auth-constraint>
                <role-name>ROLE_USER</role-name>
            </auth-constraint>
        </security-constraint>
          
    
      <!-- Default page to serve -->
      <welcome-file-list>
        <welcome-file>LoginTest.html</welcome-file>
      </welcome-file-list>
    
      <login-config>
        <auth-method>FORM</auth-method>
        <realm-name>MyRealm</realm-name>
        <form-login-config>
          <form-login-page>/LoginFormRequired.html</form-login-page>
          <form-error-page>/LoginFormRequired.html</form-error-page>
        </form-login-config>
      </login-config>
    
    </web-app>
    q1)
    After the first request (after press the button) We get redirect to LoginFormRequired.html. And We can login to server.
    But after correct login resp.jsp is called twice.

    We see this in console
    Code:
    resp.jsp called -> Metod: GET
    resp.jsp called -> Metod: POST
    How I can avoid this?

    q2)
    Why in first post to server is not data "Some data to send to the client" ?
    in Code is line:
    request.setData("Some data to send to the client");

    Is the setData method works?
    Code:
    POST /resp.jsp?isc_rpc=1&isc_v=v8.2p_2012-08-07&isc_xhr=1 HTTP/1.1
    Host: 127.0.0.1:8888
    User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:13.0) Gecko/20100101 Firefox/13.0.1
    Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
    Accept-Language: pl,en-us;q=0.7,en;q=0.3
    Accept-Encoding: gzip, deflate
    Connection: keep-alive
    Cookie: JSESSIONID=mdhdxksvar10
    Authorization: Basic YWRtaW46YWRtaW4=
    Cache-Control: no-cache
    Referer: http://127.0.0.1:8888/LoginTest.html?gwt.codesvr=127.0.0.1:9997
    Content-Type: application/x-www-form-urlencoded; charset=UTF-8
    Content-Length: 10
    Pragma: no-cache
    q3)
    I have never seen an example with response STATUS_MAX_LOGIN_ATTEMPTS_EXCEEDED maker.
    Where I can find and see this ?

    #2
    On the community wiki at wiki.smartclient.com, there are a few examples of full authentication+relogin setup, including one for Tomcat Realms.

    Comment

    Working...
    X