diff --git a/lab04/AuthCodeApp/.gitignore b/lab04/AuthCodeApp/.gitignore
new file mode 100644
index 0000000..dc42d53
--- /dev/null
+++ b/lab04/AuthCodeApp/.gitignore
@@ -0,0 +1,10 @@
+*.iml
+.gradle
+/local.properties
+/.idea/libraries
+/.idea/modules.xml
+/.idea/workspace.xml
+.DS_Store
+/build
+/captures
+.externalNativeBuild
diff --git a/lab04/AuthCodeApp/.idea/caches/build_file_checksums.ser b/lab04/AuthCodeApp/.idea/caches/build_file_checksums.ser
new file mode 100644
index 0000000..1bcd2ca
Binary files /dev/null and b/lab04/AuthCodeApp/.idea/caches/build_file_checksums.ser differ
diff --git a/lab04/AuthCodeApp/.idea/codeStyles/Project.xml b/lab04/AuthCodeApp/.idea/codeStyles/Project.xml
new file mode 100644
index 0000000..2715a34
--- /dev/null
+++ b/lab04/AuthCodeApp/.idea/codeStyles/Project.xml
@@ -0,0 +1,29 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/lab04/AuthCodeApp/.idea/gradle.xml b/lab04/AuthCodeApp/.idea/gradle.xml
new file mode 100644
index 0000000..7ac24c7
--- /dev/null
+++ b/lab04/AuthCodeApp/.idea/gradle.xml
@@ -0,0 +1,18 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/lab04/AuthCodeApp/.idea/misc.xml b/lab04/AuthCodeApp/.idea/misc.xml
new file mode 100644
index 0000000..99202cc
--- /dev/null
+++ b/lab04/AuthCodeApp/.idea/misc.xml
@@ -0,0 +1,34 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/lab04/AuthCodeApp/.idea/runConfigurations.xml b/lab04/AuthCodeApp/.idea/runConfigurations.xml
new file mode 100644
index 0000000..7f68460
--- /dev/null
+++ b/lab04/AuthCodeApp/.idea/runConfigurations.xml
@@ -0,0 +1,12 @@
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/lab04/AuthCodeApp/app/.gitignore b/lab04/AuthCodeApp/app/.gitignore
new file mode 100644
index 0000000..3543521
--- /dev/null
+++ b/lab04/AuthCodeApp/app/.gitignore
@@ -0,0 +1 @@
+/build
diff --git a/lab04/AuthCodeApp/app/build.gradle b/lab04/AuthCodeApp/app/build.gradle
new file mode 100644
index 0000000..f8ec293
--- /dev/null
+++ b/lab04/AuthCodeApp/app/build.gradle
@@ -0,0 +1,36 @@
+apply plugin: 'com.android.application'
+
+android {
+ compileSdkVersion 27
+ defaultConfig {
+ applicationId "spring2go.io.authcodeapp"
+ minSdkVersion 21
+ targetSdkVersion 27
+ versionCode 1
+ versionName "1.0"
+ testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
+ }
+ buildTypes {
+ release {
+ minifyEnabled false
+ proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
+ }
+ }
+
+ packagingOptions {
+ exclude 'META-INF/LICENSE'
+ }
+
+}
+
+dependencies {
+ implementation fileTree(dir: 'libs', include: ['*.jar'])
+ implementation 'com.android.support:appcompat-v7:27.1.1'
+ implementation 'com.android.support.constraint:constraint-layout:1.0.2'
+ testImplementation 'junit:junit:4.12'
+ compile 'com.squareup.retrofit2:retrofit:2.3.0'
+ compile 'com.squareup.retrofit2:converter-jackson:2.3.0'
+ compile 'com.squareup.okhttp3:logging-interceptor:3.9.0'
+ androidTestImplementation 'com.android.support.test:runner:1.0.1'
+ androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
+}
diff --git a/lab04/AuthCodeApp/app/proguard-rules.pro b/lab04/AuthCodeApp/app/proguard-rules.pro
new file mode 100644
index 0000000..6e7ffa9
--- /dev/null
+++ b/lab04/AuthCodeApp/app/proguard-rules.pro
@@ -0,0 +1,21 @@
+# Add project specific ProGuard rules here.
+# You can control the set of applied configuration files using the
+# proguardFiles setting in build.gradle.
+#
+# For more details, see
+# http://developer.android.com/guide/developing/tools/proguard.html
+
+# If your project uses WebView with JS, uncomment the following
+# and specify the fully qualified class name to the JavaScript interface
+# class:
+#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
+# public *;
+#}
+
+# Uncomment this to preserve the line number information for
+# debugging stack traces.
+#-keepattributes SourceFile,LineNumberTable
+
+# If you keep the line number information, uncomment this to
+# hide the original source file name.
+#-renamesourcefileattribute SourceFile
diff --git a/lab04/AuthCodeApp/app/src/androidTest/java/spring2go/io/authcodeapp/ExampleInstrumentedTest.java b/lab04/AuthCodeApp/app/src/androidTest/java/spring2go/io/authcodeapp/ExampleInstrumentedTest.java
new file mode 100644
index 0000000..80f1498
--- /dev/null
+++ b/lab04/AuthCodeApp/app/src/androidTest/java/spring2go/io/authcodeapp/ExampleInstrumentedTest.java
@@ -0,0 +1,26 @@
+package spring2go.io.authcodeapp;
+
+import android.content.Context;
+import android.support.test.InstrumentationRegistry;
+import android.support.test.runner.AndroidJUnit4;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import static org.junit.Assert.*;
+
+/**
+ * Instrumented test, which will execute on an Android device.
+ *
+ * @see Testing documentation
+ */
+@RunWith(AndroidJUnit4.class)
+public class ExampleInstrumentedTest {
+ @Test
+ public void useAppContext() {
+ // Context of the app under test.
+ Context appContext = InstrumentationRegistry.getTargetContext();
+
+ assertEquals("spring2go.io.authcodeapp", appContext.getPackageName());
+ }
+}
diff --git a/lab04/AuthCodeApp/app/src/main/AndroidManifest.xml b/lab04/AuthCodeApp/app/src/main/AndroidManifest.xml
new file mode 100644
index 0000000..a1306ea
--- /dev/null
+++ b/lab04/AuthCodeApp/app/src/main/AndroidManifest.xml
@@ -0,0 +1,35 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/lab04/AuthCodeApp/app/src/main/java/spring2go/io/authcodeapp/client/ClientAPI.java b/lab04/AuthCodeApp/app/src/main/java/spring2go/io/authcodeapp/client/ClientAPI.java
new file mode 100644
index 0000000..606f425
--- /dev/null
+++ b/lab04/AuthCodeApp/app/src/main/java/spring2go/io/authcodeapp/client/ClientAPI.java
@@ -0,0 +1,22 @@
+package spring2go.io.authcodeapp.client;
+
+import spring2go.io.authcodeapp.client.interceptor.OAuth2ClientAuthenticationInterceptor;
+import spring2go.io.authcodeapp.client.oauth2.OAuth2API;
+import spring2go.io.authcodeapp.client.userinfo.UserInfoAPI;
+import spring2go.io.authcodeapp.client.userinfo.UserInfoAPI;
+
+public class ClientAPI {
+ public static final String BASE_URL = "172.30.17.42:8080";
+
+ public static UserInfoAPI userInfo() {
+ RetrofitAPIFactory api = new RetrofitAPIFactory(BASE_URL, null);
+ return api.getRetrofit().create(UserInfoAPI.class);
+ }
+
+ public static OAuth2API oauth2() {
+ RetrofitAPIFactory api = new RetrofitAPIFactory(BASE_URL,
+ new OAuth2ClientAuthenticationInterceptor());
+ return api.getRetrofit().create(OAuth2API.class);
+ }
+
+}
diff --git a/lab04/AuthCodeApp/app/src/main/java/spring2go/io/authcodeapp/client/RetrofitAPIFactory.java b/lab04/AuthCodeApp/app/src/main/java/spring2go/io/authcodeapp/client/RetrofitAPIFactory.java
new file mode 100644
index 0000000..7415da9
--- /dev/null
+++ b/lab04/AuthCodeApp/app/src/main/java/spring2go/io/authcodeapp/client/RetrofitAPIFactory.java
@@ -0,0 +1,34 @@
+package spring2go.io.authcodeapp.client;
+
+import spring2go.io.authcodeapp.client.interceptor.BearerTokenHeaderInterceptor;
+import spring2go.io.authcodeapp.client.interceptor.ErrorInterceptor;
+import spring2go.io.authcodeapp.client.interceptor.OAuth2ClientAuthenticationInterceptor;
+import okhttp3.OkHttpClient;
+import retrofit2.Retrofit;
+import retrofit2.converter.jackson.JacksonConverterFactory;
+
+class RetrofitAPIFactory {
+ private final Retrofit retrofit;
+
+ RetrofitAPIFactory(String baseUrl,
+ OAuth2ClientAuthenticationInterceptor clientAuthentication) {
+ retrofit = new Retrofit.Builder()
+ .baseUrl("http://" + baseUrl)
+ .addConverterFactory(JacksonConverterFactory.create())
+ .client(createClient(clientAuthentication))
+ .build();
+ }
+
+ public Retrofit getRetrofit() { return retrofit; }
+
+ private OkHttpClient createClient(
+ OAuth2ClientAuthenticationInterceptor clientAuthentication) {
+ OkHttpClient.Builder client = new OkHttpClient.Builder();
+ client.addInterceptor(new ErrorInterceptor());
+ client.addInterceptor(new BearerTokenHeaderInterceptor());
+ if (clientAuthentication != null) {
+ client.addInterceptor(clientAuthentication);
+ }
+ return client.build();
+ }
+}
diff --git a/lab04/AuthCodeApp/app/src/main/java/spring2go/io/authcodeapp/client/interceptor/BearerTokenHeaderInterceptor.java b/lab04/AuthCodeApp/app/src/main/java/spring2go/io/authcodeapp/client/interceptor/BearerTokenHeaderInterceptor.java
new file mode 100644
index 0000000..22e963f
--- /dev/null
+++ b/lab04/AuthCodeApp/app/src/main/java/spring2go/io/authcodeapp/client/interceptor/BearerTokenHeaderInterceptor.java
@@ -0,0 +1,33 @@
+package spring2go.io.authcodeapp.client.interceptor;
+
+import java.io.IOException;
+import java.util.List;
+
+import okhttp3.Interceptor;
+import okhttp3.Request;
+import okhttp3.Response;
+
+/**
+ * Interceptor that adds Bearer prefix to an access token
+ */
+public class BearerTokenHeaderInterceptor implements Interceptor {
+ @Override
+ public Response intercept(Chain chain) throws IOException {
+
+ Request request = chain.request();
+
+ List headers = request.headers("Authorization");
+ if (headers.size() > 0) {
+ String accessTokenValue = headers.get(0);
+
+ request = request.newBuilder()
+ .removeHeader("Authorization")
+ .addHeader("Authorization", "Bearer " + accessTokenValue)
+ .build();
+
+ }
+
+ return chain.proceed(request);
+
+ }
+}
diff --git a/lab04/AuthCodeApp/app/src/main/java/spring2go/io/authcodeapp/client/interceptor/ErrorInterceptor.java b/lab04/AuthCodeApp/app/src/main/java/spring2go/io/authcodeapp/client/interceptor/ErrorInterceptor.java
new file mode 100644
index 0000000..8264a2f
--- /dev/null
+++ b/lab04/AuthCodeApp/app/src/main/java/spring2go/io/authcodeapp/client/interceptor/ErrorInterceptor.java
@@ -0,0 +1,28 @@
+package spring2go.io.authcodeapp.client.interceptor;
+
+import java.io.IOException;
+
+import okhttp3.Interceptor;
+import okhttp3.Request;
+import okhttp3.Response;
+
+public class ErrorInterceptor implements Interceptor {
+ @Override
+ public Response intercept(Chain chain) throws IOException {
+ Request request = chain.request();
+ Response response = chain.proceed(request);
+
+ boolean httpError = (response.code() >= 400);
+ if (httpError) {
+ throw new HttpException(response.code() + ":" + response.message());
+ }
+
+ return response;
+ }
+
+ public static class HttpException extends RuntimeException {
+ public HttpException(String message) {
+ super(message);
+ }
+ }
+}
diff --git a/lab04/AuthCodeApp/app/src/main/java/spring2go/io/authcodeapp/client/interceptor/OAuth2ClientAuthenticationInterceptor.java b/lab04/AuthCodeApp/app/src/main/java/spring2go/io/authcodeapp/client/interceptor/OAuth2ClientAuthenticationInterceptor.java
new file mode 100644
index 0000000..e179d1f
--- /dev/null
+++ b/lab04/AuthCodeApp/app/src/main/java/spring2go/io/authcodeapp/client/interceptor/OAuth2ClientAuthenticationInterceptor.java
@@ -0,0 +1,29 @@
+package spring2go.io.authcodeapp.client.interceptor;
+
+import android.util.Base64;
+
+import java.io.IOException;
+
+import okhttp3.Interceptor;
+import okhttp3.Request;
+import okhttp3.Response;
+
+public class OAuth2ClientAuthenticationInterceptor implements Interceptor {
+ @Override
+ public Response intercept(Chain chain) throws IOException {
+ Request request = chain.request();
+
+ Request authenticatedRequest = request.newBuilder()
+ .addHeader("Authorization", getEncodedAuthorization())
+ .addHeader("Content-Type", "application/x-www-form-urlencoded")
+ .method(request.method(), request.body())
+ .build();
+
+ return chain.proceed(authenticatedRequest);
+ }
+
+ private String getEncodedAuthorization() {
+ return "Basic " + Base64.encodeToString(
+ "mobileclient:112233".getBytes(), Base64.NO_WRAP);
+ }
+}
diff --git a/lab04/AuthCodeApp/app/src/main/java/spring2go/io/authcodeapp/client/oauth2/AccessToken.java b/lab04/AuthCodeApp/app/src/main/java/spring2go/io/authcodeapp/client/oauth2/AccessToken.java
new file mode 100644
index 0000000..bed8bf5
--- /dev/null
+++ b/lab04/AuthCodeApp/app/src/main/java/spring2go/io/authcodeapp/client/oauth2/AccessToken.java
@@ -0,0 +1,70 @@
+package spring2go.io.authcodeapp.client.oauth2;
+
+import com.fasterxml.jackson.annotation.JsonIgnore;
+import com.fasterxml.jackson.annotation.JsonProperty;
+
+import java.util.Date;
+
+public class AccessToken {
+
+ @JsonProperty("access_token")
+ private String value;
+
+ @JsonProperty("token_type")
+ private String tokenType;
+
+ @JsonProperty("expires_in")
+ private Long expiresIn;
+
+ @JsonIgnore
+ private Long issuedAt = new Date().getTime(); // issued at in milliseconds
+
+ private String scope;
+
+ public boolean isExpired() {
+ Long expirationTimeInSeconds = (issuedAt / 1000) + expiresIn;
+ Long nowInSeconds = (new Date().getTime()) / 1000;
+
+ return expirationTimeInSeconds < nowInSeconds;
+ }
+
+ public String getValue() {
+ return value;
+ }
+
+ public void setValue(String value) {
+ this.value = value;
+ }
+
+ public String getTokenType() {
+ return tokenType;
+ }
+
+ public void setTokenType(String tokenType) {
+ this.tokenType = tokenType;
+ }
+
+ public Long getExpiresIn() {
+ return expiresIn;
+ }
+
+ public void setExpiresIn(Long expiresIn) {
+ this.expiresIn = expiresIn;
+ }
+
+ public String getScope() {
+ return scope;
+ }
+
+ public void setScope(String scope) {
+ this.scope = scope;
+ }
+
+ public Long getIssuedAt() {
+ return issuedAt;
+ }
+
+ public void setIssuedAt(Long issuedAt) {
+ this.issuedAt = issuedAt;
+ }
+}
diff --git a/lab04/AuthCodeApp/app/src/main/java/spring2go/io/authcodeapp/client/oauth2/AccessTokenRequest.java b/lab04/AuthCodeApp/app/src/main/java/spring2go/io/authcodeapp/client/oauth2/AccessTokenRequest.java
new file mode 100644
index 0000000..7869278
--- /dev/null
+++ b/lab04/AuthCodeApp/app/src/main/java/spring2go/io/authcodeapp/client/oauth2/AccessTokenRequest.java
@@ -0,0 +1,17 @@
+package spring2go.io.authcodeapp.client.oauth2;
+
+import java.util.HashMap;
+import java.util.Map;
+
+public class AccessTokenRequest {
+
+ public static Map fromCode(String code) {
+ Map map = new HashMap<>();
+ map.put("code", code);
+ map.put("scope", "read_userinfo");
+ map.put("grant_type", "authorization_code");
+ map.put("redirect_uri", AuthorizationRequest.REDIRECT_URI);
+ return map;
+ }
+
+}
diff --git a/lab04/AuthCodeApp/app/src/main/java/spring2go/io/authcodeapp/client/oauth2/AuthorizationRequest.java b/lab04/AuthCodeApp/app/src/main/java/spring2go/io/authcodeapp/client/oauth2/AuthorizationRequest.java
new file mode 100644
index 0000000..d95072d
--- /dev/null
+++ b/lab04/AuthCodeApp/app/src/main/java/spring2go/io/authcodeapp/client/oauth2/AuthorizationRequest.java
@@ -0,0 +1,24 @@
+package spring2go.io.authcodeapp.client.oauth2;
+
+import android.net.Uri;
+
+import spring2go.io.authcodeapp.client.ClientAPI;
+
+public class AuthorizationRequest {
+ public static final String REDIRECT_URI
+ = "oauth2://userinfo/callback";
+
+ public static Uri createAuthorizationUri(String state) {
+ return new Uri.Builder()
+ .scheme("http")
+ .encodedAuthority(ClientAPI.BASE_URL)
+ .path("/oauth/authorize")
+ .appendQueryParameter("client_id", "mobileclient")
+ .appendQueryParameter("response_type", "code")
+ .appendQueryParameter("redirect_uri", REDIRECT_URI)
+ .appendQueryParameter("scope", "read_userinfo")
+ .appendQueryParameter("state", state)
+ .build();
+ }
+
+}
diff --git a/lab04/AuthCodeApp/app/src/main/java/spring2go/io/authcodeapp/client/oauth2/OAuth2API.java b/lab04/AuthCodeApp/app/src/main/java/spring2go/io/authcodeapp/client/oauth2/OAuth2API.java
new file mode 100644
index 0000000..b890b37
--- /dev/null
+++ b/lab04/AuthCodeApp/app/src/main/java/spring2go/io/authcodeapp/client/oauth2/OAuth2API.java
@@ -0,0 +1,16 @@
+package spring2go.io.authcodeapp.client.oauth2;
+
+import java.util.Map;
+
+import retrofit2.Call;
+import retrofit2.http.FieldMap;
+import retrofit2.http.FormUrlEncoded;
+import retrofit2.http.POST;
+
+public interface OAuth2API {
+
+ @FormUrlEncoded
+ @POST("oauth/token")
+ Call requestToken(@FieldMap Map tokenRequest);
+
+}
diff --git a/lab04/AuthCodeApp/app/src/main/java/spring2go/io/authcodeapp/client/oauth2/OAuth2StateManager.java b/lab04/AuthCodeApp/app/src/main/java/spring2go/io/authcodeapp/client/oauth2/OAuth2StateManager.java
new file mode 100644
index 0000000..330668f
--- /dev/null
+++ b/lab04/AuthCodeApp/app/src/main/java/spring2go/io/authcodeapp/client/oauth2/OAuth2StateManager.java
@@ -0,0 +1,28 @@
+package spring2go.io.authcodeapp.client.oauth2;
+
+import android.content.Context;
+import android.content.SharedPreferences;
+import android.preference.PreferenceManager;
+
+public class OAuth2StateManager {
+
+ private final SharedPreferences prefs;
+
+ public OAuth2StateManager(Context context) {
+ prefs = PreferenceManager.getDefaultSharedPreferences(context);
+ }
+
+ public void saveState(String state) {
+ SharedPreferences.Editor editor = prefs.edit();
+ editor.putString("state", state);
+ editor.commit();
+ }
+
+ public String getState() {
+ return prefs.getString("state", "");
+ }
+
+ public boolean isValidState(String state) {
+ return this.getState().equals(state);
+ }
+}
diff --git a/lab04/AuthCodeApp/app/src/main/java/spring2go/io/authcodeapp/client/oauth2/TokenStore.java b/lab04/AuthCodeApp/app/src/main/java/spring2go/io/authcodeapp/client/oauth2/TokenStore.java
new file mode 100644
index 0000000..f771e11
--- /dev/null
+++ b/lab04/AuthCodeApp/app/src/main/java/spring2go/io/authcodeapp/client/oauth2/TokenStore.java
@@ -0,0 +1,40 @@
+package spring2go.io.authcodeapp.client.oauth2;
+
+
+import android.content.Context;
+import android.content.SharedPreferences;
+import android.preference.PreferenceManager;
+
+public class TokenStore {
+ private final SharedPreferences prefs;
+
+ public TokenStore(Context context) {
+ prefs = PreferenceManager.getDefaultSharedPreferences(context);
+ }
+
+ public void save(AccessToken accessToken) {
+ SharedPreferences.Editor editor = prefs.edit();
+ editor.putBoolean("authorized", true);
+ editor.putString("access_token", accessToken.getValue());
+ editor.putString("scope", accessToken.getScope());
+ editor.putString("token_type", accessToken.getTokenType());
+ editor.putLong("expires_in", accessToken.getExpiresIn());
+ editor.putLong("issued_at", accessToken.getIssuedAt());
+ editor.commit();
+ }
+
+ public AccessToken getToken() {
+ AccessToken token = null;
+
+ boolean authorized = prefs.getBoolean("authorized", false);
+ if (authorized) {
+ token = new AccessToken();
+ token.setValue(prefs.getString("access_token", null));
+ token.setScope(prefs.getString("scope", ""));
+ token.setTokenType(prefs.getString("token_type", "bearer"));
+ token.setExpiresIn(prefs.getLong("expires_in", -1)); // prevents / 0
+ token.setIssuedAt(prefs.getLong("issued_at", -1)); // prevents / 0
+ }
+ return token;
+ }
+}
diff --git a/lab04/AuthCodeApp/app/src/main/java/spring2go/io/authcodeapp/client/userinfo/UserInfo.java b/lab04/AuthCodeApp/app/src/main/java/spring2go/io/authcodeapp/client/userinfo/UserInfo.java
new file mode 100644
index 0000000..bd63465
--- /dev/null
+++ b/lab04/AuthCodeApp/app/src/main/java/spring2go/io/authcodeapp/client/userinfo/UserInfo.java
@@ -0,0 +1,16 @@
+package spring2go.io.authcodeapp.client.userinfo;
+
+public class UserInfo {
+
+ private String name;
+ private String email;
+
+ public String getName() {
+ return name;
+ }
+
+ public String getEmail() {
+ return email;
+ }
+
+}
diff --git a/lab04/AuthCodeApp/app/src/main/java/spring2go/io/authcodeapp/client/userinfo/UserInfoAPI.java b/lab04/AuthCodeApp/app/src/main/java/spring2go/io/authcodeapp/client/userinfo/UserInfoAPI.java
new file mode 100644
index 0000000..e48da62
--- /dev/null
+++ b/lab04/AuthCodeApp/app/src/main/java/spring2go/io/authcodeapp/client/userinfo/UserInfoAPI.java
@@ -0,0 +1,13 @@
+package spring2go.io.authcodeapp.client.userinfo;
+
+
+import retrofit2.Call;
+import retrofit2.http.GET;
+import retrofit2.http.Header;
+
+public interface UserInfoAPI {
+
+ @GET("api/userinfo")
+ Call token(@Header("Authorization") String accessToken);
+
+}
diff --git a/lab04/AuthCodeApp/app/src/main/java/spring2go/io/authcodeapp/presenter/AuthorizationCodeActivity.java b/lab04/AuthCodeApp/app/src/main/java/spring2go/io/authcodeapp/presenter/AuthorizationCodeActivity.java
new file mode 100644
index 0000000..c450776
--- /dev/null
+++ b/lab04/AuthCodeApp/app/src/main/java/spring2go/io/authcodeapp/presenter/AuthorizationCodeActivity.java
@@ -0,0 +1,73 @@
+package spring2go.io.authcodeapp.presenter;
+
+import android.content.Intent;
+import android.net.Uri;
+import android.os.Bundle;
+import android.support.v7.app.AppCompatActivity;
+import android.util.Log;
+import android.widget.Toast;
+
+import spring2go.io.authcodeapp.R;
+import spring2go.io.authcodeapp.client.ClientAPI;
+import spring2go.io.authcodeapp.client.oauth2.AccessToken;
+import spring2go.io.authcodeapp.client.oauth2.AccessTokenRequest;
+import spring2go.io.authcodeapp.client.oauth2.OAuth2StateManager;
+import spring2go.io.authcodeapp.client.oauth2.TokenStore;
+import retrofit2.Call;
+import retrofit2.Callback;
+import retrofit2.Response;
+
+public class AuthorizationCodeActivity extends AppCompatActivity {
+
+ private String code;
+ private String state;
+ private TokenStore tokenStore;
+ private OAuth2StateManager manager;
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.activity_user_info);
+
+ tokenStore = new TokenStore(this);
+ manager = new OAuth2StateManager(this);
+
+ Uri callbackUri = Uri.parse(getIntent().getDataString());
+
+ code = callbackUri.getQueryParameter("code");
+ state = callbackUri.getQueryParameter("state");
+
+ // validates state
+ if (!manager.isValidState(state)) {
+ Toast.makeText(this, "CSRF Attack detected", Toast.LENGTH_SHORT).show();
+ return;
+ }
+
+ Call accessTokenCall = ClientAPI
+ .oauth2()
+ .requestToken(AccessTokenRequest.fromCode(code));
+
+ accessTokenCall.enqueue(new Callback() {
+ @Override
+ public void onResponse(Call call, Response response) {
+ AccessToken token = response.body();
+ tokenStore.save(token);
+
+ // go to the other activity with an access token in hands!!!!!!!
+
+ Intent intent = new Intent(AuthorizationCodeActivity.this,
+ UserInfoActivity.class);
+ startActivity(intent);
+ finish();
+ }
+
+ @Override
+ public void onFailure(Call call, Throwable t) {
+ Log.e("AuthorizationCode", "Error retrieving access token", t);
+ }
+ });
+
+
+ }
+
+}
diff --git a/lab04/AuthCodeApp/app/src/main/java/spring2go/io/authcodeapp/presenter/MainActivity.java b/lab04/AuthCodeApp/app/src/main/java/spring2go/io/authcodeapp/presenter/MainActivity.java
new file mode 100644
index 0000000..d8cd165
--- /dev/null
+++ b/lab04/AuthCodeApp/app/src/main/java/spring2go/io/authcodeapp/presenter/MainActivity.java
@@ -0,0 +1,62 @@
+package spring2go.io.authcodeapp.presenter;
+
+import android.content.Intent;
+import android.net.Uri;
+import android.os.Bundle;
+import android.support.v7.app.AppCompatActivity;
+import android.view.View;
+import android.widget.Button;
+
+import java.util.UUID;
+
+import spring2go.io.authcodeapp.R;
+import spring2go.io.authcodeapp.client.oauth2.AccessToken;
+import spring2go.io.authcodeapp.client.oauth2.AuthorizationRequest;
+import spring2go.io.authcodeapp.client.oauth2.OAuth2StateManager;
+import spring2go.io.authcodeapp.client.oauth2.TokenStore;
+
+public class MainActivity extends AppCompatActivity
+ implements View.OnClickListener {
+
+ private Button userInfoButton;
+
+ private TokenStore tokenStore;
+
+ private OAuth2StateManager oauth2StateManager;
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.activity_main);
+
+ tokenStore = new TokenStore(this);
+ oauth2StateManager = new OAuth2StateManager(MainActivity.this);
+
+ userInfoButton = (Button) findViewById(R.id.userinfo_button);
+ userInfoButton.setOnClickListener(this);
+ }
+
+ @Override
+ public void onClick(View view) {
+
+ AccessToken accessToken = tokenStore.getToken();
+ if (accessToken != null && !accessToken.isExpired()) {
+ Intent intent = new Intent(this, UserInfoActivity.class);
+ startActivity(intent);
+ return;
+ }
+
+ // create a state parameter to start the authorization flow
+ String state = UUID.randomUUID().toString();
+ oauth2StateManager.saveState(state);
+
+ // creates the authorization URI to redirect user
+ Uri authorizationUri = AuthorizationRequest
+ .createAuthorizationUri(state);
+
+ Intent authorizationIntent = new Intent(Intent.ACTION_VIEW);
+ authorizationIntent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
+ authorizationIntent.setData(authorizationUri);
+ startActivity(authorizationIntent);
+ }
+}
diff --git a/lab04/AuthCodeApp/app/src/main/java/spring2go/io/authcodeapp/presenter/UserInfoActivity.java b/lab04/AuthCodeApp/app/src/main/java/spring2go/io/authcodeapp/presenter/UserInfoActivity.java
new file mode 100644
index 0000000..1286e04
--- /dev/null
+++ b/lab04/AuthCodeApp/app/src/main/java/spring2go/io/authcodeapp/presenter/UserInfoActivity.java
@@ -0,0 +1,51 @@
+package spring2go.io.authcodeapp.presenter;
+
+import android.os.Bundle;
+import android.support.v7.app.AppCompatActivity;
+import android.util.Log;
+import android.widget.TextView;
+
+import spring2go.io.authcodeapp.R;
+import spring2go.io.authcodeapp.client.ClientAPI;
+import spring2go.io.authcodeapp.client.oauth2.TokenStore;
+import spring2go.io.authcodeapp.client.userinfo.UserInfo;
+import retrofit2.Call;
+import retrofit2.Callback;
+import retrofit2.Response;
+
+public class UserInfoActivity extends AppCompatActivity {
+
+ private TextView textName;
+ private TextView textEmail;
+ private TokenStore tokenStore;
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.activity_user_info);
+
+ tokenStore = new TokenStore(this);
+
+ textName = (TextView) findViewById(R.id.userinfo_name);
+ textEmail = (TextView) findViewById(R.id.userinfo_email);
+
+ Call call = ClientAPI
+ .userInfo().token(tokenStore.getToken().getValue());
+
+ call.enqueue(new Callback() {
+ @Override
+ public void onResponse(Call call, Response response) {
+ UserInfo userInfo = response.body();
+ textName.setText(userInfo.getName());
+ textEmail.setText(userInfo.getEmail());
+ }
+
+ @Override
+ public void onFailure(Call call, Throwable t) {
+ Log.e("UserInfoActivity", "Error trying to retrieve user info", t);
+ }
+ });
+
+ }
+
+}
\ No newline at end of file
diff --git a/lab04/AuthCodeApp/app/src/main/res/drawable-v24/ic_launcher_foreground.xml b/lab04/AuthCodeApp/app/src/main/res/drawable-v24/ic_launcher_foreground.xml
new file mode 100644
index 0000000..ddb26ad
--- /dev/null
+++ b/lab04/AuthCodeApp/app/src/main/res/drawable-v24/ic_launcher_foreground.xml
@@ -0,0 +1,34 @@
+
+
+
+
+
+
+
+
+
+
+
diff --git a/lab04/AuthCodeApp/app/src/main/res/drawable/ic_launcher_background.xml b/lab04/AuthCodeApp/app/src/main/res/drawable/ic_launcher_background.xml
new file mode 100644
index 0000000..3a37cf6
--- /dev/null
+++ b/lab04/AuthCodeApp/app/src/main/res/drawable/ic_launcher_background.xml
@@ -0,0 +1,170 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/lab04/AuthCodeApp/app/src/main/res/layout/activity_authorization_code.xml b/lab04/AuthCodeApp/app/src/main/res/layout/activity_authorization_code.xml
new file mode 100644
index 0000000..913aa32
--- /dev/null
+++ b/lab04/AuthCodeApp/app/src/main/res/layout/activity_authorization_code.xml
@@ -0,0 +1,9 @@
+
+
+
+
\ No newline at end of file
diff --git a/lab04/AuthCodeApp/app/src/main/res/layout/activity_main.xml b/lab04/AuthCodeApp/app/src/main/res/layout/activity_main.xml
new file mode 100644
index 0000000..b09893e
--- /dev/null
+++ b/lab04/AuthCodeApp/app/src/main/res/layout/activity_main.xml
@@ -0,0 +1,15 @@
+
+
+
+
+
+
diff --git a/lab04/AuthCodeApp/app/src/main/res/layout/activity_user_info.xml b/lab04/AuthCodeApp/app/src/main/res/layout/activity_user_info.xml
new file mode 100644
index 0000000..b0a90e7
--- /dev/null
+++ b/lab04/AuthCodeApp/app/src/main/res/layout/activity_user_info.xml
@@ -0,0 +1,21 @@
+
+
+
+
+
+
+
+
diff --git a/lab04/AuthCodeApp/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/lab04/AuthCodeApp/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
new file mode 100644
index 0000000..a26f6fb
--- /dev/null
+++ b/lab04/AuthCodeApp/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
@@ -0,0 +1,5 @@
+
+
+
+
+
\ No newline at end of file
diff --git a/lab04/AuthCodeApp/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/lab04/AuthCodeApp/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml
new file mode 100644
index 0000000..a26f6fb
--- /dev/null
+++ b/lab04/AuthCodeApp/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml
@@ -0,0 +1,5 @@
+
+
+
+
+
\ No newline at end of file
diff --git a/lab04/AuthCodeApp/app/src/main/res/mipmap-hdpi/ic_launcher.png b/lab04/AuthCodeApp/app/src/main/res/mipmap-hdpi/ic_launcher.png
new file mode 100644
index 0000000..a2f5908
Binary files /dev/null and b/lab04/AuthCodeApp/app/src/main/res/mipmap-hdpi/ic_launcher.png differ
diff --git a/lab04/AuthCodeApp/app/src/main/res/mipmap-hdpi/ic_launcher_round.png b/lab04/AuthCodeApp/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
new file mode 100644
index 0000000..1b52399
Binary files /dev/null and b/lab04/AuthCodeApp/app/src/main/res/mipmap-hdpi/ic_launcher_round.png differ
diff --git a/lab04/AuthCodeApp/app/src/main/res/mipmap-mdpi/ic_launcher.png b/lab04/AuthCodeApp/app/src/main/res/mipmap-mdpi/ic_launcher.png
new file mode 100644
index 0000000..ff10afd
Binary files /dev/null and b/lab04/AuthCodeApp/app/src/main/res/mipmap-mdpi/ic_launcher.png differ
diff --git a/lab04/AuthCodeApp/app/src/main/res/mipmap-mdpi/ic_launcher_round.png b/lab04/AuthCodeApp/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
new file mode 100644
index 0000000..115a4c7
Binary files /dev/null and b/lab04/AuthCodeApp/app/src/main/res/mipmap-mdpi/ic_launcher_round.png differ
diff --git a/lab04/AuthCodeApp/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/lab04/AuthCodeApp/app/src/main/res/mipmap-xhdpi/ic_launcher.png
new file mode 100644
index 0000000..dcd3cd8
Binary files /dev/null and b/lab04/AuthCodeApp/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ
diff --git a/lab04/AuthCodeApp/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png b/lab04/AuthCodeApp/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
new file mode 100644
index 0000000..459ca60
Binary files /dev/null and b/lab04/AuthCodeApp/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png differ
diff --git a/lab04/AuthCodeApp/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/lab04/AuthCodeApp/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
new file mode 100644
index 0000000..8ca12fe
Binary files /dev/null and b/lab04/AuthCodeApp/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ
diff --git a/lab04/AuthCodeApp/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png b/lab04/AuthCodeApp/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
new file mode 100644
index 0000000..8e19b41
Binary files /dev/null and b/lab04/AuthCodeApp/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png differ
diff --git a/lab04/AuthCodeApp/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/lab04/AuthCodeApp/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
new file mode 100644
index 0000000..b824ebd
Binary files /dev/null and b/lab04/AuthCodeApp/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ
diff --git a/lab04/AuthCodeApp/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png b/lab04/AuthCodeApp/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
new file mode 100644
index 0000000..4c19a13
Binary files /dev/null and b/lab04/AuthCodeApp/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png differ
diff --git a/lab04/AuthCodeApp/app/src/main/res/values/colors.xml b/lab04/AuthCodeApp/app/src/main/res/values/colors.xml
new file mode 100644
index 0000000..2a12c47
--- /dev/null
+++ b/lab04/AuthCodeApp/app/src/main/res/values/colors.xml
@@ -0,0 +1,6 @@
+
+
+ #3F51B5
+ #303F9F
+ #FF4081
+
diff --git a/lab04/AuthCodeApp/app/src/main/res/values/strings.xml b/lab04/AuthCodeApp/app/src/main/res/values/strings.xml
new file mode 100644
index 0000000..a726376
--- /dev/null
+++ b/lab04/AuthCodeApp/app/src/main/res/values/strings.xml
@@ -0,0 +1,3 @@
+
+ AuthCodeApp
+
diff --git a/lab04/AuthCodeApp/app/src/main/res/values/styles.xml b/lab04/AuthCodeApp/app/src/main/res/values/styles.xml
new file mode 100644
index 0000000..6f19b47
--- /dev/null
+++ b/lab04/AuthCodeApp/app/src/main/res/values/styles.xml
@@ -0,0 +1,11 @@
+
+
+
+
+
+
diff --git a/lab04/AuthCodeApp/app/src/test/java/spring2go/io/authcodeapp/ExampleUnitTest.java b/lab04/AuthCodeApp/app/src/test/java/spring2go/io/authcodeapp/ExampleUnitTest.java
new file mode 100644
index 0000000..badacb1
--- /dev/null
+++ b/lab04/AuthCodeApp/app/src/test/java/spring2go/io/authcodeapp/ExampleUnitTest.java
@@ -0,0 +1,17 @@
+package spring2go.io.authcodeapp;
+
+import org.junit.Test;
+
+import static org.junit.Assert.*;
+
+/**
+ * Example local unit test, which will execute on the development machine (host).
+ *
+ * @see Testing documentation
+ */
+public class ExampleUnitTest {
+ @Test
+ public void addition_isCorrect() {
+ assertEquals(4, 2 + 2);
+ }
+}
\ No newline at end of file
diff --git a/lab04/AuthCodeApp/build.gradle b/lab04/AuthCodeApp/build.gradle
new file mode 100644
index 0000000..abdaa8e
--- /dev/null
+++ b/lab04/AuthCodeApp/build.gradle
@@ -0,0 +1,27 @@
+// Top-level build file where you can add configuration options common to all sub-projects/modules.
+
+buildscript {
+
+ repositories {
+ google()
+ jcenter()
+ }
+ dependencies {
+ classpath 'com.android.tools.build:gradle:3.1.1'
+
+
+ // NOTE: Do not place your application dependencies here; they belong
+ // in the individual module build.gradle files
+ }
+}
+
+allprojects {
+ repositories {
+ google()
+ jcenter()
+ }
+}
+
+task clean(type: Delete) {
+ delete rootProject.buildDir
+}
diff --git a/lab04/AuthCodeApp/gradle.properties b/lab04/AuthCodeApp/gradle.properties
new file mode 100644
index 0000000..d9ae40f
--- /dev/null
+++ b/lab04/AuthCodeApp/gradle.properties
@@ -0,0 +1,13 @@
+# Project-wide Gradle settings.
+# IDE (e.g. Android Studio) users:
+# Gradle settings configured through the IDE *will override*
+# any settings specified in this file.
+# For more details on how to configure your build environment visit
+# http://www.gradle.org/docs/current/userguide/build_environment.html
+# Specifies the JVM arguments used for the daemon process.
+# The setting is particularly useful for tweaking memory settings.
+org.gradle.jvmargs=-Xmx1536m
+# When configured, Gradle will run in incubating parallel mode.
+# This option should only be used with decoupled projects. More details, visit
+# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
+# org.gradle.parallel=true
diff --git a/lab04/AuthCodeApp/gradle/wrapper/gradle-wrapper.jar b/lab04/AuthCodeApp/gradle/wrapper/gradle-wrapper.jar
new file mode 100644
index 0000000..7a3265e
Binary files /dev/null and b/lab04/AuthCodeApp/gradle/wrapper/gradle-wrapper.jar differ
diff --git a/lab04/AuthCodeApp/gradle/wrapper/gradle-wrapper.properties b/lab04/AuthCodeApp/gradle/wrapper/gradle-wrapper.properties
new file mode 100644
index 0000000..3d7a424
--- /dev/null
+++ b/lab04/AuthCodeApp/gradle/wrapper/gradle-wrapper.properties
@@ -0,0 +1,6 @@
+#Sat Apr 07 14:21:56 CST 2018
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists
+distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-all.zip
diff --git a/lab04/AuthCodeApp/gradlew b/lab04/AuthCodeApp/gradlew
new file mode 100644
index 0000000..cccdd3d
--- /dev/null
+++ b/lab04/AuthCodeApp/gradlew
@@ -0,0 +1,172 @@
+#!/usr/bin/env sh
+
+##############################################################################
+##
+## Gradle start up script for UN*X
+##
+##############################################################################
+
+# Attempt to set APP_HOME
+# Resolve links: $0 may be a link
+PRG="$0"
+# Need this for relative symlinks.
+while [ -h "$PRG" ] ; do
+ ls=`ls -ld "$PRG"`
+ link=`expr "$ls" : '.*-> \(.*\)$'`
+ if expr "$link" : '/.*' > /dev/null; then
+ PRG="$link"
+ else
+ PRG=`dirname "$PRG"`"/$link"
+ fi
+done
+SAVED="`pwd`"
+cd "`dirname \"$PRG\"`/" >/dev/null
+APP_HOME="`pwd -P`"
+cd "$SAVED" >/dev/null
+
+APP_NAME="Gradle"
+APP_BASE_NAME=`basename "$0"`
+
+# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+DEFAULT_JVM_OPTS=""
+
+# Use the maximum available, or set MAX_FD != -1 to use that value.
+MAX_FD="maximum"
+
+warn () {
+ echo "$*"
+}
+
+die () {
+ echo
+ echo "$*"
+ echo
+ exit 1
+}
+
+# OS specific support (must be 'true' or 'false').
+cygwin=false
+msys=false
+darwin=false
+nonstop=false
+case "`uname`" in
+ CYGWIN* )
+ cygwin=true
+ ;;
+ Darwin* )
+ darwin=true
+ ;;
+ MINGW* )
+ msys=true
+ ;;
+ NONSTOP* )
+ nonstop=true
+ ;;
+esac
+
+CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
+
+# Determine the Java command to use to start the JVM.
+if [ -n "$JAVA_HOME" ] ; then
+ if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
+ # IBM's JDK on AIX uses strange locations for the executables
+ JAVACMD="$JAVA_HOME/jre/sh/java"
+ else
+ JAVACMD="$JAVA_HOME/bin/java"
+ fi
+ if [ ! -x "$JAVACMD" ] ; then
+ die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+ fi
+else
+ JAVACMD="java"
+ which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+fi
+
+# Increase the maximum file descriptors if we can.
+if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
+ MAX_FD_LIMIT=`ulimit -H -n`
+ if [ $? -eq 0 ] ; then
+ if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
+ MAX_FD="$MAX_FD_LIMIT"
+ fi
+ ulimit -n $MAX_FD
+ if [ $? -ne 0 ] ; then
+ warn "Could not set maximum file descriptor limit: $MAX_FD"
+ fi
+ else
+ warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
+ fi
+fi
+
+# For Darwin, add options to specify how the application appears in the dock
+if $darwin; then
+ GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
+fi
+
+# For Cygwin, switch paths to Windows format before running java
+if $cygwin ; then
+ APP_HOME=`cygpath --path --mixed "$APP_HOME"`
+ CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
+ JAVACMD=`cygpath --unix "$JAVACMD"`
+
+ # We build the pattern for arguments to be converted via cygpath
+ ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
+ SEP=""
+ for dir in $ROOTDIRSRAW ; do
+ ROOTDIRS="$ROOTDIRS$SEP$dir"
+ SEP="|"
+ done
+ OURCYGPATTERN="(^($ROOTDIRS))"
+ # Add a user-defined pattern to the cygpath arguments
+ if [ "$GRADLE_CYGPATTERN" != "" ] ; then
+ OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
+ fi
+ # Now convert the arguments - kludge to limit ourselves to /bin/sh
+ i=0
+ for arg in "$@" ; do
+ CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
+ CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
+
+ if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
+ eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
+ else
+ eval `echo args$i`="\"$arg\""
+ fi
+ i=$((i+1))
+ done
+ case $i in
+ (0) set -- ;;
+ (1) set -- "$args0" ;;
+ (2) set -- "$args0" "$args1" ;;
+ (3) set -- "$args0" "$args1" "$args2" ;;
+ (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
+ (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
+ (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
+ (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
+ (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
+ (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
+ esac
+fi
+
+# Escape application args
+save () {
+ for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
+ echo " "
+}
+APP_ARGS=$(save "$@")
+
+# Collect all arguments for the java command, following the shell quoting and substitution rules
+eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
+
+# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
+if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
+ cd "$(dirname "$0")"
+fi
+
+exec "$JAVACMD" "$@"
diff --git a/lab04/AuthCodeApp/gradlew.bat b/lab04/AuthCodeApp/gradlew.bat
new file mode 100644
index 0000000..e95643d
--- /dev/null
+++ b/lab04/AuthCodeApp/gradlew.bat
@@ -0,0 +1,84 @@
+@if "%DEBUG%" == "" @echo off
+@rem ##########################################################################
+@rem
+@rem Gradle startup script for Windows
+@rem
+@rem ##########################################################################
+
+@rem Set local scope for the variables with windows NT shell
+if "%OS%"=="Windows_NT" setlocal
+
+set DIRNAME=%~dp0
+if "%DIRNAME%" == "" set DIRNAME=.
+set APP_BASE_NAME=%~n0
+set APP_HOME=%DIRNAME%
+
+@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+set DEFAULT_JVM_OPTS=
+
+@rem Find java.exe
+if defined JAVA_HOME goto findJavaFromJavaHome
+
+set JAVA_EXE=java.exe
+%JAVA_EXE% -version >NUL 2>&1
+if "%ERRORLEVEL%" == "0" goto init
+
+echo.
+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:findJavaFromJavaHome
+set JAVA_HOME=%JAVA_HOME:"=%
+set JAVA_EXE=%JAVA_HOME%/bin/java.exe
+
+if exist "%JAVA_EXE%" goto init
+
+echo.
+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:init
+@rem Get command-line arguments, handling Windows variants
+
+if not "%OS%" == "Windows_NT" goto win9xME_args
+
+:win9xME_args
+@rem Slurp the command line arguments.
+set CMD_LINE_ARGS=
+set _SKIP=2
+
+:win9xME_args_slurp
+if "x%~1" == "x" goto execute
+
+set CMD_LINE_ARGS=%*
+
+:execute
+@rem Setup the command line
+
+set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
+
+@rem Execute Gradle
+"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
+
+:end
+@rem End local scope for the variables with windows NT shell
+if "%ERRORLEVEL%"=="0" goto mainEnd
+
+:fail
+rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
+rem the _cmd.exe /c_ return code!
+if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
+exit /b 1
+
+:mainEnd
+if "%OS%"=="Windows_NT" endlocal
+
+:omega
diff --git a/lab04/AuthCodeApp/settings.gradle b/lab04/AuthCodeApp/settings.gradle
new file mode 100644
index 0000000..d3db109
--- /dev/null
+++ b/lab04/AuthCodeApp/settings.gradle
@@ -0,0 +1 @@
+include ':app'
diff --git a/lab04/README.md b/lab04/README.md
new file mode 100644
index 0000000..4b15824
--- /dev/null
+++ b/lab04/README.md
@@ -0,0 +1,16 @@
+基于Spring Security OAuth2+内存H2数据库的最简授权服务器
+======
+
+# 操作方式
+
+### 1. 启动mobile_authserver,端口8080
+
+### 2. 在Android Studio中启动AuthCodeApp
+
+### 3. 校验
+
+1. 校验h2内存数据库生成的访问令牌 http://localhost:8080/h2-console
+2. Android Studio中的Device File Explorer查看
+```
+data\data\spring2go.io.authcodeapp\shared_prefs
+```
\ No newline at end of file
diff --git a/lab04/mobile-authserver/.springBeans b/lab04/mobile-authserver/.springBeans
new file mode 100644
index 0000000..95d1032
--- /dev/null
+++ b/lab04/mobile-authserver/.springBeans
@@ -0,0 +1,16 @@
+
+
+ 1
+
+
+
+
+
+
+ java:io.spring2go.server.ServerApplication
+
+
+
+
+
+
diff --git a/lab04/mobile-authserver/pom.xml b/lab04/mobile-authserver/pom.xml
new file mode 100644
index 0000000..db22a0e
--- /dev/null
+++ b/lab04/mobile-authserver/pom.xml
@@ -0,0 +1,70 @@
+
+
+ 4.0.0
+
+ oauth2.spring2go.io
+ mobile-authserver
+ 0.0.1-SNAPSHOT
+ jar
+
+ mobile-authserver
+ Demo project for Spring Boot
+
+
+ org.springframework.boot
+ spring-boot-starter-parent
+ 1.5.10.RELEASE
+
+
+
+
+ UTF-8
+ UTF-8
+ 1.8
+
+
+
+
+ org.springframework.boot
+ spring-boot-starter-data-jpa
+
+
+ com.h2database
+ h2
+ runtime
+
+
+
+ org.springframework.boot
+ spring-boot-starter-security
+
+
+ org.springframework.boot
+ spring-boot-starter-web
+
+
+
+ org.springframework.security.oauth
+ spring-security-oauth2
+ 2.2.0.RELEASE
+
+
+
+ commons-codec
+ commons-codec
+
+
+
+
+
+
+
+ org.springframework.boot
+ spring-boot-maven-plugin
+
+
+
+
+
+
diff --git a/lab04/mobile-authserver/src/main/java/io/spring2go/server/SecurityConfiguration.java b/lab04/mobile-authserver/src/main/java/io/spring2go/server/SecurityConfiguration.java
new file mode 100644
index 0000000..c253325
--- /dev/null
+++ b/lab04/mobile-authserver/src/main/java/io/spring2go/server/SecurityConfiguration.java
@@ -0,0 +1,38 @@
+package io.spring2go.server;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.core.Ordered;
+import org.springframework.core.annotation.Order;
+import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
+import org.springframework.security.config.annotation.web.builders.HttpSecurity;
+import org.springframework.security.config.annotation.web.builders.WebSecurity;
+import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
+import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
+import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
+
+@Order(Ordered.LOWEST_PRECEDENCE)
+@Configuration
+@EnableWebSecurity
+public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
+
+ @Autowired
+ public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
+ auth.inMemoryAuthentication().withUser("bobo").password("xyz").roles("USER");
+ }
+
+ @Override
+ public void configure(WebSecurity web) throws Exception {
+ web.ignoring().antMatchers("/h2-console*/**", "/webjars/**", "/images/**", "/oauth/uncache_approvals",
+ "/oauth/cache_approvals");
+ }
+
+ @Override
+ protected void configure(HttpSecurity http) throws Exception {
+
+ http.authorizeRequests().antMatchers("/oauth/**").authenticated().and().csrf()
+ .requireCsrfProtectionMatcher(new AntPathRequestMatcher("/oauth/authorize")).disable().formLogin()
+ .permitAll().and().logout().permitAll().and();
+
+ }
+}
diff --git a/lab04/mobile-authserver/src/main/java/io/spring2go/server/ServerApplication.java b/lab04/mobile-authserver/src/main/java/io/spring2go/server/ServerApplication.java
new file mode 100644
index 0000000..765b93f
--- /dev/null
+++ b/lab04/mobile-authserver/src/main/java/io/spring2go/server/ServerApplication.java
@@ -0,0 +1,12 @@
+package io.spring2go.server;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+
+@SpringBootApplication
+public class ServerApplication {
+
+ public static void main(String[] args) {
+ SpringApplication.run(ServerApplication.class, args);
+ }
+}
diff --git a/lab04/mobile-authserver/src/main/java/io/spring2go/server/UserController.java b/lab04/mobile-authserver/src/main/java/io/spring2go/server/UserController.java
new file mode 100644
index 0000000..3ab46a8
--- /dev/null
+++ b/lab04/mobile-authserver/src/main/java/io/spring2go/server/UserController.java
@@ -0,0 +1,25 @@
+package io.spring2go.server;
+
+import org.springframework.http.ResponseEntity;
+import org.springframework.security.core.context.SecurityContextHolder;
+import org.springframework.security.core.userdetails.User;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.RequestMapping;
+
+@Controller
+public class UserController {
+
+ @RequestMapping("/api/userinfo")
+ public ResponseEntity getUserInfo() {
+ User user = (User) SecurityContextHolder.getContext()
+ .getAuthentication().getPrincipal();
+ String email = user.getUsername() + "@spring2go.com";
+
+ UserInfo userInfo = new UserInfo();
+ userInfo.setName(user.getUsername());
+ userInfo.setEmail(email);
+
+ return ResponseEntity.ok(userInfo);
+ }
+
+}
diff --git a/lab04/mobile-authserver/src/main/java/io/spring2go/server/UserInfo.java b/lab04/mobile-authserver/src/main/java/io/spring2go/server/UserInfo.java
new file mode 100644
index 0000000..440a332
--- /dev/null
+++ b/lab04/mobile-authserver/src/main/java/io/spring2go/server/UserInfo.java
@@ -0,0 +1,25 @@
+package io.spring2go.server;
+
+public class UserInfo {
+
+ private String name;
+
+ private String email;
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getEmail() {
+ return email;
+ }
+
+ public void setEmail(String email) {
+ this.email = email;
+ }
+
+}
diff --git a/lab04/mobile-authserver/src/main/java/io/spring2go/server/oauth2/AuthorizationServerConfiguration.java b/lab04/mobile-authserver/src/main/java/io/spring2go/server/oauth2/AuthorizationServerConfiguration.java
new file mode 100644
index 0000000..fb65651
--- /dev/null
+++ b/lab04/mobile-authserver/src/main/java/io/spring2go/server/oauth2/AuthorizationServerConfiguration.java
@@ -0,0 +1,54 @@
+package io.spring2go.server.oauth2;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.Import;
+import org.springframework.security.authentication.AuthenticationManager;
+import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
+import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
+import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
+import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
+import org.springframework.security.oauth2.provider.TokenGranter;
+import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
+import org.springframework.security.oauth2.provider.token.TokenStore;
+
+import javax.sql.DataSource;
+
+@Configuration
+@Import(OAuth2Configuration.class)
+@EnableAuthorizationServer
+public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
+
+ @Autowired
+ private DataSource dataSource;
+
+ @Autowired
+ private AuthenticationManager authenticationManager;
+
+ @Autowired
+ private TokenStore tokenStore;
+
+ @Autowired
+ private TokenGranter tokenGranter;
+
+ @Autowired
+ private AuthorizationCodeServices authorizationCodeServices;
+
+ @Override
+ public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
+ endpoints.authenticationManager(authenticationManager);
+ endpoints.tokenStore(tokenStore);
+ endpoints.tokenGranter(tokenGranter);
+
+ AuthorizationCodeServices codeServices = authorizationCodeServices;
+
+ endpoints.authorizationCodeServices(codeServices);
+ }
+
+
+ @Override
+ public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
+ clients.jdbc(dataSource);
+ }
+
+}
diff --git a/lab04/mobile-authserver/src/main/java/io/spring2go/server/oauth2/OAuth2Configuration.java b/lab04/mobile-authserver/src/main/java/io/spring2go/server/oauth2/OAuth2Configuration.java
new file mode 100644
index 0000000..a75b348
--- /dev/null
+++ b/lab04/mobile-authserver/src/main/java/io/spring2go/server/oauth2/OAuth2Configuration.java
@@ -0,0 +1,74 @@
+package io.spring2go.server.oauth2;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.security.authentication.AuthenticationManager;
+import org.springframework.security.oauth2.provider.ClientDetailsService;
+import org.springframework.security.oauth2.provider.CompositeTokenGranter;
+import org.springframework.security.oauth2.provider.TokenGranter;
+import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
+import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
+import org.springframework.security.oauth2.provider.code.AuthorizationCodeTokenGranter;
+import org.springframework.security.oauth2.provider.code.InMemoryAuthorizationCodeServices;
+import org.springframework.security.oauth2.provider.implicit.ImplicitTokenGranter;
+import org.springframework.security.oauth2.provider.password.ResourceOwnerPasswordTokenGranter;
+import org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory;
+import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
+import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
+import org.springframework.security.oauth2.provider.token.TokenStore;
+import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;
+
+import javax.sql.DataSource;
+import java.util.Arrays;
+import java.util.List;
+
+@Configuration
+public class OAuth2Configuration {
+
+ @Autowired
+ private DataSource dataSource;
+
+ @Autowired
+ private AuthenticationManager authenticationManager;
+
+ @Bean
+ public TokenGranter tokenGranter() {
+
+ DefaultOAuth2RequestFactory requestFactory = new DefaultOAuth2RequestFactory(clientDetailsService());
+
+ AuthorizationCodeServices codeServices = authorizationCodeServices();
+
+ AuthorizationServerTokenServices tokenServices = tokenServices();
+ List tokenGranters = Arrays.asList(
+ new AuthorizationCodeTokenGranter(tokenServices, codeServices, clientDetailsService(), requestFactory),
+ new ResourceOwnerPasswordTokenGranter(authenticationManager, tokenServices, clientDetailsService(), requestFactory),
+ new ImplicitTokenGranter(tokenServices, clientDetailsService(), requestFactory));
+
+ return new CompositeTokenGranter(tokenGranters);
+ }
+
+ @Bean
+ public ClientDetailsService clientDetailsService() {
+ return new JdbcClientDetailsService(dataSource);
+ }
+
+ @Bean
+ public AuthorizationServerTokenServices tokenServices() {
+ DefaultTokenServices tokenServices = new DefaultTokenServices();
+ tokenServices.setTokenStore(tokenStore());
+ tokenServices.setAuthenticationManager(authenticationManager);
+ return tokenServices;
+ }
+
+ @Bean
+ public TokenStore tokenStore() {
+ return new JdbcTokenStore(dataSource);
+ }
+
+ @Bean
+ public AuthorizationCodeServices authorizationCodeServices() {
+ return new InMemoryAuthorizationCodeServices();
+ }
+
+}
diff --git a/lab04/mobile-authserver/src/main/java/io/spring2go/server/oauth2/ResourceServerConfiguration.java b/lab04/mobile-authserver/src/main/java/io/spring2go/server/oauth2/ResourceServerConfiguration.java
new file mode 100644
index 0000000..b8e1716
--- /dev/null
+++ b/lab04/mobile-authserver/src/main/java/io/spring2go/server/oauth2/ResourceServerConfiguration.java
@@ -0,0 +1,20 @@
+package io.spring2go.server.oauth2;
+
+import org.springframework.context.annotation.Configuration;
+import org.springframework.security.config.annotation.web.builders.HttpSecurity;
+import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
+import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
+
+@Configuration
+@EnableResourceServer
+public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
+
+ @Override
+ public void configure(HttpSecurity http) throws Exception {
+ http
+ .authorizeRequests()
+ .anyRequest().authenticated().and()
+ .requestMatchers().antMatchers("/api/**");
+ }
+
+}
diff --git a/lab04/mobile-authserver/src/main/resources/application.properties b/lab04/mobile-authserver/src/main/resources/application.properties
new file mode 100644
index 0000000..34ab1f7
--- /dev/null
+++ b/lab04/mobile-authserver/src/main/resources/application.properties
@@ -0,0 +1,14 @@
+security.user.name=bobo
+security.user.password=xyz
+
+spring.datasource.url=jdbc:h2:mem:spring2go;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=false
+spring.datasource.username=testdb
+spring.datasource.password=123
+spring.datasource.driver-class-name=org.h2.Driver
+spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect
+spring.jpa.properties.hibernate.hbm2ddl.auto=create
+
+spring.h2.console.enabled=true
+spring.h2.console.path=/h2-console
+
+spring.jackson.property-naming-strategy=com.fasterxml.jackson.databind.PropertyNamingStrategy.SnakeCaseStrategy
\ No newline at end of file
diff --git a/lab04/mobile-authserver/src/main/resources/data.sql b/lab04/mobile-authserver/src/main/resources/data.sql
new file mode 100644
index 0000000..18bfcda
--- /dev/null
+++ b/lab04/mobile-authserver/src/main/resources/data.sql
@@ -0,0 +1,42 @@
+-- create the database structure for OAuth2
+create table oauth_client_details (
+ client_id VARCHAR(256) PRIMARY KEY,
+ resource_ids VARCHAR(256),
+ client_secret VARCHAR(256),
+ scope VARCHAR(256),
+ authorized_grant_types VARCHAR(256),
+ web_server_redirect_uri VARCHAR(256),
+ authorities VARCHAR(256),
+ access_token_validity INTEGER,
+ refresh_token_validity INTEGER,
+ additional_information VARCHAR(4096),
+ autoapprove VARCHAR(256)
+);
+
+create table oauth_access_token (
+ token_id VARCHAR(256),
+ token BINARY,
+ authentication_id VARCHAR(256) PRIMARY KEY,
+ user_name VARCHAR(256),
+ client_id VARCHAR(256),
+ authentication BINARY,
+ refresh_token VARCHAR(256)
+);
+
+create table oauth_approvals (
+ userId VARCHAR(256),
+ clientId VARCHAR(256),
+ scope VARCHAR(256),
+ status VARCHAR(10),
+ expiresAt TIMESTAMP,
+ lastModifiedAt TIMESTAMP
+);
+
+-- insert a default client credentials
+insert into oauth_client_details
+(client_id, client_secret, scope,
+ authorized_grant_types, web_server_redirect_uri)
+values
+('mobileclient', '112233', 'read_userinfo,read_contacts',
+'authorization_code,implicit,password', 'oauth2://userinfo/callback,http://localhost:9000/callback'
+);