Skip to content

Commit

Permalink
Rest Service secured by Http-Basic-Auth with Spring Security; Android…
Browse files Browse the repository at this point in the history
… app sends Basic-Auth Header on each request, if user is logged in
  • Loading branch information
rpelger committed Mar 6, 2013
1 parent c112168 commit 9816a0a
Show file tree
Hide file tree
Showing 32 changed files with 430 additions and 205 deletions.
2 changes: 1 addition & 1 deletion android-app/project.properties
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,4 @@
# project structure.

# Project target.
target=Google Inc.:Google APIs:16
target=Google Inc.:Google APIs:14
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import android.accounts.AccountManager;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
Expand All @@ -14,9 +15,12 @@
import android.widget.TextView;

import com.comsysto.dalli.android.R;
import com.comsysto.dalli.android.application.Constants;
import com.comsysto.dalli.android.application.PartyManagerApplication;
import com.comsysto.dalli.android.authentication.AccountAuthenticator;
import com.comsysto.dalli.android.model.UserAccount;
import com.comsysto.findparty.User;
import org.w3c.dom.UserDataHandler;

/**
* Displays the login page.
Expand All @@ -25,6 +29,8 @@
*/
public class LoginActivity extends AccountAuthenticatorActivity {

private final static String TAG = Constants.LOG_AUTH_PREFIX + LoginActivity.class.getSimpleName();

public static final String PARAM_AUTHTOKEN_TYPE = "authtokenType";
boolean loggedIn = false;
protected EditText userName;
Expand Down Expand Up @@ -66,6 +72,7 @@ private void loginRegisteredUser() {
Bundle extras = getIntent().getExtras();
if(extras!=null) {
User user = (User) extras.get("registeredUser");
Log.d(TAG, "trying to login existing User: " + user);
login(user.getUsername(), user.getPassword());
}
}
Expand All @@ -89,11 +96,13 @@ protected void register(String username, String password) {

protected void login(String username, String password) {
if (isNotEmpty(username) && isNotEmpty(password) && authenticate(username, password)) {
Log.d(TAG, "creating Application Account on device");
createApplicationAccount(username, password);
Intent intent = new Intent(this, StartActivity.class);
startActivity(intent);
finish();
} else {
Log.d(TAG, "login failed for username/password: " +username + "/" + password);
error.setText(getString(R.string.LOGIN_FAILED_LABEL));
error.startAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_in));
error.setVisibility(View.VISIBLE);
Expand Down Expand Up @@ -160,8 +169,16 @@ public boolean onTouch(View v, MotionEvent event) {
private void createApplicationAccount(String username, String password) {
final Account account = new Account(username, AccountAuthenticator.AUTH_TYPE);
Account[] accountsByType = accountManager.getAccountsByType(AccountAuthenticator.AUTH_TYPE);
if(accountsByType.length==0)
accountManager.addAccountExplicitly(account, password, null);
if(accountsByType.length==0) {
Log.d(TAG, "adding new device Account: " + account);
Bundle userData = new Bundle();
userData.putString("password", password);
accountManager.addAccountExplicitly(account, password, userData);
} else if(accountsByType.length == 1) {
Log.d(TAG, "account already exists on device -> using this account");
} else {
Log.d(TAG, "multiple accounts for this application exists: " + accountsByType.length);
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import com.comsysto.dalli.android.application.Constants;
import com.comsysto.dalli.android.application.PartyManagerApplication;
import com.comsysto.findparty.User;

Expand All @@ -17,6 +19,8 @@
public class RegisterActivity extends LoginActivity {


private static final String TAG = Constants.LOG_SERVICE_PREFIX + RegisterActivity.class.getSimpleName();

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Expand All @@ -34,6 +38,7 @@ public void onClick(View view) {
}

private void register(EditText userName, EditText password) {
Log.d(TAG, "creating new User Account on Server: " + userName);
User user = ((PartyManagerApplication) getApplication()).createAccount(userName.getText().toString(), password.getText().toString());

Intent intent = new Intent(this, LoginActivity.class);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,11 @@
import android.app.Activity;
import android.content.Intent;
import android.os.StrictMode;
import android.util.Log;
import com.comsysto.dalli.android.application.Constants;
import com.comsysto.dalli.android.application.PartyManagerApplication;
import com.comsysto.dalli.android.authentication.AccountAuthenticator;
import com.comsysto.dalli.android.model.UserAccount;
import com.comsysto.findparty.User;


Expand All @@ -24,7 +27,8 @@
*/
public class StartActivity extends Activity {


private final static String TAG = Constants.LOG_AUTH_PREFIX + StartActivity.class.getSimpleName();

@Override
protected void onResume() {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().detectAll().permitAll().build();
Expand All @@ -40,14 +44,22 @@ protected void onResume() {
mAccountManager.addAccount(AccountAuthenticator.AUTH_TYPE, null, null, null, this, null, null);
} else {
PartyManagerApplication application = (PartyManagerApplication)getApplication();

User user = new User();
user.setUsername(accountsByType[0].name);

application.setUser(user);

Account account = accountsByType[0];
setUser(application, account);

Intent intent = new Intent(this, SplashScreenActivity.class);
startActivity(intent);
}
}

}

private void setUser(PartyManagerApplication application, Account account) {
User user = new User();
user.setUsername(account.name);
user.setPassword(AccountManager.get(this).getPassword(account));
application.setUser(user);
}



}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package com.comsysto.dalli.android.application;

/**
* User: rpelger
* Date: 06.03.13
*/
public class Constants {

public static final String LOG_PREFIX = "CS_";

public static final String LOG_AUTH_PREFIX = LOG_PREFIX + "AUTH_";

public static final String LOG_SERVICE_PREFIX = LOG_PREFIX + "SERVICE_";

public static final String LOG_APP_PREFIX = LOG_PREFIX + "APP_";
}
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,9 @@ public class PartyManagerApplication extends Application {
private static final String CLOUD_HOST = "snuggle.eu01.aws.af.cm";
private static final String LOCAL_EMULATOR = "10.0.2.2:8080";
private static final String LOCAL_ROB = "192.168.1.169:8080";
private static final String TAG = Constants.LOG_APP_PREFIX + PartyManagerApplication.class.getSimpleName();

private Party selectedParty;
private Party selectedParty;

private PartyService partyService;

Expand All @@ -49,11 +50,13 @@ public void onCreate() {
}

public void initializeService() {
Log.d(TAG, "initializing application");
this.ready = false;
if (isConnected()) {
initializeOnlineService(CLOUD_HOST);
initializeOnlineService(LOCAL_EMULATOR);
} else {
//TODO: If no network connection available close the application with a hint!
Log.d(TAG, "using Mock-Service");
this.partyService = new PartyManagementServiceMock();
}
}
Expand All @@ -63,16 +66,16 @@ private void initializeOnlineService(final String host) {

@Override
protected Void doInBackground(Void... params) {
PartyManagerApplication.this.partyService = new PartyManagementServiceImpl(host);
PartyManagerApplication.this.partyService = new PartyManagementServiceImpl(host, PartyManagerApplication.this);
try {
String echo = PartyManagerApplication.this.partyService.echo("echo");
if (echo.equals("echo")) {
Log.i("Server Check", "Server is online");
Log.i(TAG, "Server-Check ["+host+"]: Server is online");
} else {
Log.e("Server Check", "Server returned wrong echo ("+ echo + "), going offline.");
Log.e(TAG, "Server-Check ["+host+"]: Server returned wrong echo ("+ echo + "), going offline.");
}
} catch (Exception e) {
Log.e("Server Check", "Server not reachable", e);
Log.e(TAG, "Server-Check ["+host+"]: Server not reachable", e);

}
PartyManagerApplication.this.ready = true;
Expand Down Expand Up @@ -100,8 +103,10 @@ boolean isConnected() {
NetworkInfo activeNetworkInfo = cm.getActiveNetworkInfo();
if (activeNetworkInfo != null && activeNetworkInfo.isAvailable()
&& activeNetworkInfo.isConnected()) {
Log.d(TAG, "device connected successfully to network");
return true;
} else {
Log.d(TAG, "device not connected to network");
return false;
}
}
Expand Down Expand Up @@ -144,10 +149,13 @@ public List<String> getAllCategories() {
}

public boolean authenticate(String username, String password) {
Log.d(TAG, "authenticating username/password: " + username + "/" + password);
User user = partyService.getUser(username);
if(user!=null && user.getPassword() != null && user.getPassword().equals(password)) {
Log.d(TAG, "user successfully authenticated: " + user);
return true;
}
Log.d(TAG, "authentication failed!");
return false;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
import android.util.Log;

import com.comsysto.dalli.android.activity.LoginActivity;
import com.comsysto.dalli.android.application.Constants;

/**
* Handles requests from the app for login or creating accounts.
*
Expand All @@ -22,6 +24,8 @@
*/
public class AccountAuthenticator extends AbstractAccountAuthenticator {

private final static String TAG = Constants.LOG_AUTH_PREFIX + AccountAuthenticator.class.getSimpleName();

private Context context;

public static final String AUTH_TYPE = "com.comsysto.authentication";
Expand All @@ -31,14 +35,15 @@ public class AccountAuthenticator extends AbstractAccountAuthenticator {
public AccountAuthenticator(Context context) {
super(context);
this.context = context;
Log.d("AccountAuthenticator", "AccountAuthenticator created");
Log.d(TAG, "AccountAuthenticator created");
}

@Override
public Bundle addAccount(AccountAuthenticatorResponse response,
String accountType, String authTokenType,
String[] requiredFeatures, Bundle options)
throws NetworkErrorException {
Log.d(TAG, "preparing intent to add new account");
final Intent intent = new Intent(context, LoginActivity.class);
intent.putExtra(LoginActivity.PARAM_AUTHTOKEN_TYPE, authTokenType);
intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import com.comsysto.dalli.android.application.Constants;

/**
* The {@link AccountManager} will use this service to obtain the {@link AccountAuthenticator} of the app.
Expand All @@ -14,31 +15,23 @@
*/
public class AuthenticationService extends Service {

private static final String TAG = "AuthenticationService";
private static final String TAG = Constants.LOG_AUTH_PREFIX + AuthenticationService.class.getSimpleName();
private AccountAuthenticator mAuthenticator;

@Override
public void onCreate() {
if (Log.isLoggable(TAG, Log.VERBOSE)) {
}
Log.d(TAG, "comSysto Authentication Service started.");
mAuthenticator = new AccountAuthenticator(this);
}

@Override
public void onDestroy() {
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log.v(TAG, "comSysto Authentication Service stopped.");
}
Log.d(TAG, "comSysto Authentication Service stopped.");
}

@Override
public IBinder onBind(Intent intent) {
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log.v(TAG,
"getBinder()... returning the AccountAuthenticator binder for intent "
+ intent);
}
Log.d(TAG, "getBinder()... returning the AccountAuthenticator binder for intent " + intent);
return mAuthenticator.getIBinder();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,31 +11,19 @@
*/
public class UserAccount extends Account {

private String username;

private String password;

public UserAccount(String name, String password, String type) {
super(name, type);
this.username = username;
this.password = password;
}

public String getUsername() {
return username;
}

public void setUsername(String username) {
this.username = username;
return name;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}


}
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package com.comsysto.dalli.android.service;

import android.util.Base64;
import android.util.Log;
import com.comsysto.dalli.android.application.Constants;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
Expand All @@ -9,24 +11,23 @@
import java.io.IOException;

/**
* Created with IntelliJ IDEA.
* User: rpelger
* Date: 20.11.12
* Time: 12:04
* To change this template use File | Settings | File Templates.
*/
public class NoCacheClientRequestInterceptor implements ClientHttpRequestInterceptor {

private final static String TAG = Constants.LOG_SERVICE_PREFIX + NoCacheClientRequestInterceptor.class.getSimpleName();

@Override
public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] bytes, ClientHttpRequestExecution clientHttpRequestExecution) throws IOException {

Log.d(TAG, "Setting no-cache headers for request: " + httpRequest.getMethod() + " " + httpRequest.getURI());
httpRequest.getHeaders().add("Pragma","No-cache");
httpRequest.getHeaders().add("Cache-Control","max-age=0, no-cache, no-store");
httpRequest.getHeaders().add("Expires", "0");

ClientHttpResponse response = clientHttpRequestExecution.execute(httpRequest, bytes);
Log.i("MY_PARTIES_REQ_RES", "Server-Response ("+httpRequest.getMethod()+" -> " + httpRequest.getURI()+"): " +response.getStatusCode());
return response;
return clientHttpRequestExecution.execute(httpRequest, bytes);
}

}
Loading

0 comments on commit 9816a0a

Please sign in to comment.