Android Client Authentication with Spring Security 3
Hi Spring Community,
I have a webapplication and an android client. I would like to implement a secure login method. From the client I send a request to a webservice method:
Code:
@POST
@Produces(MediaType.TEXT_PLAIN)
@Path("/login")
public String login(String credentials) {
JSONObject jo = null;
String name = "";
String password = "";
try {
jo = new JSONObject(credentials);
name = jo.getString("name");
password = jo.getString("password");
} catch (JSONException e) {
e.printStackTrace();
}
HttpResponse r = springSecurityCheck(name, password);
for (Header h : r.getAllHeaders()) {
System.out.println(h.getName() + " " + " " + h.getValue() + "");
}
String s = r.getFirstHeader("Location").toString();
boolean isError = s.contains("login_error");
if (!isError) {
Header[] cookies = r.getHeaders("Set-Cookie");
for (int i = 0; i < cookies.length; i++) {
if (cookies[i].toString().contains(
"SPRING_SECURITY_REMEMBER_ME_COOKIE")) {
String[] cookie = cookies[i].toString().split("=");
String token = cookie[1].substring(0,
cookie[1].indexOf(";"));
if (token != null) {
return "token:" + token;
}
}
}
}
System.out.println(" ----- Login from" + name
+ " failed----- ");
return "newLogin";
}
The springsecuritycheck does the following:
Code:
public HttpResponse springSecurityCheck(String name, String password) {
DefaultHttpClient client = new DefaultHttpClient();
HttpPost requestLogin = new HttpPost(
"http://mywebapp.com/j_spring_security_check?");
HttpResponse response = null;
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("j_username", name));
params.add(new BasicNameValuePair("j_password", password));
params.add(new BasicNameValuePair("_spring_security_remember_me","true"));
try {
requestLogin
.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
response = client.execute(requestLogin);
return response;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
So everything works fine. The token is stored in the persitent_logins table of the serverdata base and the loginmethod gives the token back to the client. But how do I use token for further requests to other webservice methods?
For example, the springsecurity login url is j_spring_security_check?j_username="abc"&j_passwor d="xyz". Are there any urls like j_token="1d3ds"?
Thanks for your help
Greetings