authentication by mysql database

50 views
Skip to first unread message

rao...@gmail.com

unread,
Apr 8, 2013, 6:21:02 AM4/8/13
to spif...@googlegroups.com
Hello,

I am trying to authenticate by changing SampleAuthServer.java in the sample as here:

I am not sure whether this is right approach. Please advise.

@Override
   public void doGet(HttpServletRequest request, HttpServletResponse response)
       throws ServletException, IOException
   {
       String authHeader = request.getHeader(AUTHORIZATION);
       response.setContentType("application/json");

       ServletOutputStream out = response.getOutputStream();
       StringBuffer buff = new StringBuffer();

       if (authHeader == null) {
           /*
            * This means someone tried to get a token but didn't specify any credentials
            */
           response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
           buff.append(generateFault("Sender", "NoAuthHeader", ""));
           out.println(buff.toString());
           return;
       }

       String[] fields = authHeader.trim().split(" ");
       if (fields.length != 2) {
           /*
            * This means someone specified an invalid authorization header
            */
           response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
           buff.append(generateFault("Sender", "InvalidAuthHeader",
                                     "The authorization header '" + authHeader + "' is invalid.  " +
                                     "The format should be BASIC <username:password> base64 encoded."));
           out.println(buff.toString());
           return;
       }
       String cred;
       try {
           cred = new String(Base64.decodeBase64(fields[1].getBytes("UTF-8")), "UTF-8");
       } catch (UnsupportedEncodingException e) {
           throw new IllegalStateException(e);
       }
       String[] creds = cred.split(":");
       if (creds.length != 2) {
           /*
            * This means someone specified an invalid authorization header
            */
           response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
           buff.append(generateFault("Sender", "InvalidAuthHeader",
                                     "The authorization header '" + authHeader + "' is invalid.  " +
                                     "The format should be BASIC <username:password> base64 encoded."));
           out.println(buff.toString());
           return;
       }
       /***********************authentication****************************/        
         
              String msq_user = creds[0];
              String msq_pass = creds[1];
             
              Connection con = null;
              String url = "jdbc:mysql://localhost:3306/";
              String db = "user_ebm";
              String driver = "com.mysql.jdbc.Driver";
              String user1 = "root";
              String pass = "cigol123";
              String pass1="";   
             
             try{
                 Class.forName(driver);
                 con = DriverManager.getConnection(url+db, user1, pass);
                 Statement st = con.createStatement();
                 ResultSet res = st.executeQuery("SELECT password FROM user_register WHERE username='"+msq_user+"'");
               
                  pass1 = res.getString("password");           
               
                     if (msq_pass.equals(pass1))
                     {
                          /*
                           * At this point we can generate our token.  In our case we just use the username followed
                            * by a random number.  The token can be any format.
                           */
                          String random = Long.toHexString(Double.doubleToLongBits(Math.random()));     
                          buff.append("{\"Token\":\""  + creds[0] + "-" + random + "\"}");  
      
                           out.println(buff.toString());
                       
                     }else{
                        
                         return;
                     }
                    
                
                 }
                 catch(Exception e){
                  System.out.println(e.getMessage());
                }
        
         /**************************end************************************/   
      
   }

regards.

AM Mohan Rao

Zack Grossbart

unread,
Apr 8, 2013, 7:07:05 AM4/8/13
to spif...@googlegroups.com
Hello Rao,

Spiffy UI defines a couple of ways to transport security credentials, but it
doesn't define what those credentials are or what they authenticate too.

Using the SampleAuthServer and authenticating against MySQL is a reasonable
way to do it. You might want to consider two things:

1. Using MyQSL as your authentication store means that every user of your
application will need a MySQL username and password. That's not very
secure.

2. We often write a servlet filter that since in front of many services and
makes sure the security authorization is valid so we don't have to write
security code in each service.

You might want to take a look at the Spiffy UI security page here:

http://www.spiffyui.org/?auth

Cheers,
Zack
--
You received this message because you are subscribed to the Google Groups
"Spiffy UI" group.
To unsubscribe from this group and stop receiving emails from it, send an
email to spiffy-ui+...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

rao...@gmail.com

unread,
Apr 11, 2013, 5:30:26 AM4/11/13
to spif...@googlegroups.com, za...@grossbart.com
Hello Zack,

Thanks. I coded SpiffyUINavigation panel 1 for Auth, panel2 for Forms and panel3 for Mvsb (fancier only).
I modified CrayonColors.java with the following code for authentication:

 @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException,
            IOException
    {
       
        /**********************authentication********************************/
        int result = 0;
        String user = request.getPathInfo();
        if (user.startsWith("/")) {
            user = user.substring(1);             
           
        }
       
        //registered users
       
        JSONArray users = Users.getUserList();
        int len = users.length();
        try {
           
            for (int i = 0; i < len; i++) {
                if (!users.isNull(i) && user.equals(users.getJSONObject(i).getString("user")))  {
                    // found it!
                    result = 1;
                }
            }
        } catch (JSONException je) {
            LOGGER.throwing(User.class.getName(), "findUserInArray", je);
        }      
       
        /***************************end**************************************/
    if(result == 1)     {       
        JSONArray fullColorArray;
        String query = request.getParameter("q");

I get following error in eclipse:

14:44:17.932 [ERROR] [org.spiffyui.spiffynavigation.index] Uncaught exception escaped
java.lang.NullPointerException: null
    at org.spiffyui.client.widgets.multivaluesuggest.MultivalueSuggestBoxBase.handleQueryResponse(MultivalueSuggestBoxBase.java:1001)
    at org.spiffyui.client.widgets.multivaluesuggest.MultivalueSuggestBox$1.onSuccess(MultivalueSuggestBox.java:86)
    at org.spiffyui.client.rest.RESTility$RESTRequestCallback.handleSuccessfulResponse(RESTility.java:1233)
    at org.spiffyui.client.rest.RESTility$RESTRequestCallback.onResponseReceived(RESTility.java:1196)
    at com.google.gwt.http.client.Request.fireOnResponseReceived(Request.java:287)
    at com.google.gwt.http.client.RequestBuilder$1.onReadyStateChange(RequestBuilder.java:395)
    at sun.reflect.GeneratedMethodAccessor113.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at com.google.gwt.dev.shell.MethodAdaptor.invoke(MethodAdaptor.java:103)
    at com.google.gwt.dev.shell.MethodDispatch.invoke(MethodDispatch.java:71)
    at com.google.gwt.dev.shell.OophmSessionHandler.invoke(OophmSessionHandler.java:172)
    at com.google.gwt.dev.shell.BrowserChannelServer.reactToMessagesWhileWaitingForReturn(BrowserChannelServer.java:338)
    at com.google.gwt.dev.shell.BrowserChannelServer.invokeJavascript(BrowserChannelServer.java:219)
    at com.google.gwt.dev.shell.ModuleSpaceOOPHM.doInvoke(ModuleSpaceOOPHM.java:136)
    at com.google.gwt.dev.shell.ModuleSpace.invokeNative(ModuleSpace.java:571)
    at com.google.gwt.dev.shell.ModuleSpace.invokeNativeObject(ModuleSpace.java:279)
    at com.google.gwt.dev.shell.JavaScriptHost.invokeNativeObject(JavaScriptHost.java:91)
    at com.google.gwt.core.client.impl.Impl.apply(Impl.java)
    at com.google.gwt.core.client.impl.Impl.entry0(Impl.java:242)
    at sun.reflect.GeneratedMethodAccessor109.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at com.google.gwt.dev.shell.MethodAdaptor.invoke(MethodAdaptor.java:103)
    at com.google.gwt.dev.shell.MethodDispatch.invoke(MethodDispatch.java:71)
    at com.google.gwt.dev.shell.OophmSessionHandler.invoke(OophmSessionHandler.java:172)
    at com.google.gwt.dev.shell.BrowserChannelServer.reactToMessages(BrowserChannelServer.java:293)
    at com.google.gwt.dev.shell.BrowserChannelServer.processConnection(BrowserChannelServer.java:547)
    at com.google.gwt.dev.shell.BrowserChannelServer.run(BrowserChannelServer.java:364)
    at java.lang.Thread.run(Thread.java:619)

I also attached image which hangs but normally should display some data.
This happens if userID is valid or not.

Please help.

regards.

AM Mohan Rao
uncaught_exception.png

Zack Grossbart

unread,
Apr 11, 2013, 7:18:18 AM4/11/13
to spif...@googlegroups.com
Hi Rao,

It looks like your server is return XML and invalid XML at that. It should
be returning valid JSON.

-Zack
com.google.gwt.dev.shell.BrowserChannelServer.reactToMessages(BrowserChannel
Server.java:293)
    at
com.google.gwt.dev.shell.BrowserChannelServer.processConnection(BrowserChann

rao...@gmail.com

unread,
Apr 11, 2013, 11:50:00 AM4/11/13
to spif...@googlegroups.com, za...@grossbart.com
Hello Zack,

Thanks. I can't figure out a workaround. Could you please help.

Regards.
AM Mohan Rao
Reply all
Reply to author
Forward
0 new messages