├── oauth2library ├── .gitignore ├── src │ ├── main │ │ ├── res │ │ │ └── values │ │ │ │ └── strings.xml │ │ ├── AndroidManifest.xml │ │ └── java │ │ │ └── ca │ │ │ └── mimic │ │ │ └── oauth2library │ │ │ ├── OAuthResponseCallback.java │ │ │ ├── Token.java │ │ │ ├── OAuthError.java │ │ │ ├── Constants.java │ │ │ ├── AuthState.java │ │ │ ├── Utils.java │ │ │ ├── OAuthResponse.java │ │ │ ├── Access.java │ │ │ └── OAuth2Client.java │ ├── androidTest │ │ └── java │ │ │ └── ca │ │ │ └── mimic │ │ │ └── oauth2library │ │ │ └── ExampleInstrumentedTest.java │ └── test │ │ └── java │ │ └── ca │ │ └── mimic │ │ └── oauth2library │ │ └── ExampleUnitTest.java ├── proguard-rules.txt └── build.gradle ├── settings.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── .gitignore ├── gradlew.bat ├── README.md ├── gradlew └── LICENSE.txt /oauth2library/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':oauth2library' 2 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mimicmobile/okhttp-oauth2-client/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /oauth2library/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | OkHttp OAuth2 Client 3 | 4 | -------------------------------------------------------------------------------- /oauth2library/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | build 2 | .gradle 3 | local.properties 4 | .idea 5 | .DS_Store 6 | oauth2library/sign.gradle 7 | oauth2library/build 8 | *.iml 9 | gradle.properties 10 | *.keystore 11 | *.asc 12 | -------------------------------------------------------------------------------- /oauth2library/src/main/java/ca/mimic/oauth2library/OAuthResponseCallback.java: -------------------------------------------------------------------------------- 1 | package ca.mimic.oauth2library; 2 | 3 | public interface OAuthResponseCallback { 4 | void onResponse(OAuthResponse response); 5 | } 6 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Fri Feb 23 18:57:22 EST 2018 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip 7 | -------------------------------------------------------------------------------- /oauth2library/src/main/java/ca/mimic/oauth2library/Token.java: -------------------------------------------------------------------------------- 1 | package ca.mimic.oauth2library; 2 | 3 | class Token { 4 | protected Long expires_in; 5 | protected String token_type; 6 | protected String refresh_token; 7 | protected String access_token; 8 | protected String scope; 9 | } 10 | -------------------------------------------------------------------------------- /oauth2library/src/main/java/ca/mimic/oauth2library/OAuthError.java: -------------------------------------------------------------------------------- 1 | package ca.mimic.oauth2library; 2 | 3 | public class OAuthError { 4 | protected String error; 5 | protected String error_description; 6 | protected String error_uri; 7 | 8 | protected transient Exception exception; 9 | 10 | public OAuthError(Exception e) { 11 | exception = e; 12 | } 13 | 14 | public String getError() { 15 | return error; 16 | } 17 | 18 | public String getErrorDescription() { 19 | return error_description; 20 | } 21 | 22 | public String getErrorUri() { 23 | return error_uri; 24 | } 25 | 26 | public Exception getErrorException() { 27 | return exception; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /oauth2library/src/main/java/ca/mimic/oauth2library/Constants.java: -------------------------------------------------------------------------------- 1 | package ca.mimic.oauth2library; 2 | 3 | class Constants { 4 | public static final String GRANT_TYPE_REFRESH = "refresh_token"; 5 | public static final String GRANT_TYPE_PASSWORD = "password"; 6 | 7 | public static final String POST_GRANT_TYPE = "grant_type"; 8 | public static final String POST_USERNAME = "username"; 9 | public static final String POST_PASSWORD = "password"; 10 | public static final String POST_CLIENT_ID = "client_id"; 11 | public static final String POST_CLIENT_SECRET = "client_secret"; 12 | public static final String POST_SCOPE = "scope"; 13 | public static final String POST_REFRESH_TOKEN = "refresh_token"; 14 | 15 | public static final String HEADER_AUTHORIZATION = "Authorization"; 16 | } 17 | -------------------------------------------------------------------------------- /oauth2library/src/androidTest/java/ca/mimic/oauth2library/ExampleInstrumentedTest.java: -------------------------------------------------------------------------------- 1 | package ca.mimic.oauth2library; 2 | 3 | import android.content.Context; 4 | import android.support.test.InstrumentationRegistry; 5 | import android.support.test.runner.AndroidJUnit4; 6 | 7 | import org.junit.Test; 8 | import org.junit.runner.RunWith; 9 | 10 | import static org.junit.Assert.*; 11 | 12 | /** 13 | * Instrumentation test, which will execute on an Android device. 14 | * 15 | * @see Testing documentation 16 | */ 17 | @RunWith(AndroidJUnit4.class) 18 | public class ExampleInstrumentedTest { 19 | @Test 20 | public void useAppContext() throws Exception { 21 | // Context of the app under test. 22 | Context appContext = InstrumentationRegistry.getTargetContext(); 23 | 24 | assertEquals("ca.mimic.oauth2library.test", appContext.getPackageName()); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /oauth2library/proguard-rules.txt: -------------------------------------------------------------------------------- 1 | ##---------------Begin: proguard configuration for Gson ---------- 2 | # Gson uses generic type information stored in a class file when working with fields. Proguard 3 | # removes such information by default, so configure it to keep all of it. 4 | -keepattributes Signature 5 | 6 | # Gson specific classes 7 | -keep class sun.misc.Unsafe { *; } 8 | 9 | # Application classes that will be serialized/deserialized over Gson 10 | -keep class ca.mimic.oauth2library.Token { *; } 11 | -keepclassmembers class ca.mimic.oauth2library.Token { *; } 12 | -keepclassmembers class ca.mimic.oauth2library.OAuthError { 13 | protected ; 14 | } 15 | 16 | # Prevent proguard from stripping interface information from TypeAdapterFactory, 17 | # JsonSerializer, JsonDeserializer instances (so they can be used in @JsonAdapter) 18 | -keep class * implements com.google.gson.TypeAdapterFactory 19 | -keep class * implements com.google.gson.JsonSerializer 20 | -keep class * implements com.google.gson.JsonDeserializer 21 | 22 | # Prevent proguard from stripping Moshi bits 23 | -keep class com.squareup.moshi.** { *; } 24 | -keep interface com.squareup.moshi.** { *; } 25 | 26 | ##---------------End: proguard configuration for Gson ---------- 27 | -------------------------------------------------------------------------------- /oauth2library/src/main/java/ca/mimic/oauth2library/AuthState.java: -------------------------------------------------------------------------------- 1 | package ca.mimic.oauth2library; 2 | 3 | class AuthState { 4 | protected static final int ACCESS_TOKEN = 0; 5 | protected static final int REFRESH_TOKEN = 1; 6 | 7 | private static final int NO_AUTH = 0; 8 | private static final int BASIC_AUTH = 1; 9 | private static final int AUTHORIZATION_AUTH = 2; 10 | private static final int FINAL_AUTH = 3; 11 | 12 | private static final int[] ACCESS_STATES = new int[]{ 13 | NO_AUTH, 14 | BASIC_AUTH, 15 | AUTHORIZATION_AUTH, 16 | FINAL_AUTH 17 | }; 18 | 19 | private static final int[] REFRESH_STATES = new int[]{ 20 | NO_AUTH, 21 | AUTHORIZATION_AUTH, 22 | FINAL_AUTH 23 | }; 24 | 25 | private int[] state; 26 | 27 | private int position; 28 | 29 | AuthState(int tokenType) { 30 | switch (tokenType) { 31 | default: 32 | case ACCESS_TOKEN: 33 | state = ACCESS_STATES; 34 | break; 35 | case REFRESH_TOKEN: 36 | state = REFRESH_STATES; 37 | break; 38 | } 39 | } 40 | 41 | protected void nextState() { 42 | position++; 43 | } 44 | 45 | protected boolean isFinalAuth() { 46 | return state[position] == FINAL_AUTH; 47 | } 48 | 49 | protected boolean isBasicAuth() { 50 | return state[position] == BASIC_AUTH; 51 | } 52 | 53 | protected boolean isAuthorizationAuth() { 54 | return state[position] == AUTHORIZATION_AUTH; 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /oauth2library/src/test/java/ca/mimic/oauth2library/ExampleUnitTest.java: -------------------------------------------------------------------------------- 1 | package ca.mimic.oauth2library; 2 | 3 | import com.squareup.moshi.Moshi; 4 | 5 | import org.junit.Test; 6 | 7 | import java.io.IOException; 8 | 9 | import static org.junit.Assert.*; 10 | 11 | /** 12 | * Example local unit test, which will execute on the development machine (host). 13 | * 14 | * @see Testing documentation 15 | */ 16 | public class ExampleUnitTest { 17 | @Test 18 | public void additionIsCorrect() throws Exception { 19 | assertEquals(4, 2 + 2); 20 | } 21 | 22 | public Token createTokenFromJson() throws IOException { 23 | Moshi moshi = new Moshi.Builder().build(); 24 | String s = "{\"expires_in\": 2000, \"token_type\": \"bearer\", \"access_token\": \"access_token\", \"refresh_token\": \"refresh_token\", \"scope\": \"scope\"}"; 25 | 26 | return moshi.adapter(Token.class).fromJson(s); 27 | } 28 | 29 | public OAuthError createErrorFromJson() throws IOException { 30 | Moshi moshi = new Moshi.Builder().build(); 31 | String s = "{\"error\":\"unauthorized_client\",\"error_description\":\"Invalid client or doesn't have the permission to make this request.\"}"; 32 | 33 | return moshi.adapter(OAuthError.class).fromJson(s); 34 | } 35 | 36 | @Test 37 | public void tokenCheck() throws Exception { 38 | Token token = createTokenFromJson(); 39 | assertEquals("access_token", token.access_token); 40 | assertEquals("refresh_token", token.refresh_token); 41 | assertEquals("bearer", token.token_type); 42 | assertEquals("scope", token.scope); 43 | assertEquals(2000, (long) token.expires_in); 44 | } 45 | 46 | @Test 47 | public void errorCheck() throws Exception { 48 | OAuthError error = createErrorFromJson(); 49 | assertEquals("unauthorized_client", error.getError()); 50 | assertEquals("Invalid client or doesn't have the permission to make this request.", error.getErrorDescription()); 51 | assertEquals(null, error.getErrorUri()); 52 | assertEquals(null, error.getErrorException()); 53 | } 54 | } -------------------------------------------------------------------------------- /oauth2library/src/main/java/ca/mimic/oauth2library/Utils.java: -------------------------------------------------------------------------------- 1 | package ca.mimic.oauth2library; 2 | 3 | import java.io.IOException; 4 | import java.util.Map; 5 | 6 | import okhttp3.Authenticator; 7 | import okhttp3.Credentials; 8 | import okhttp3.FormBody; 9 | import okhttp3.Request; 10 | import okhttp3.Response; 11 | 12 | import okhttp3.Route; 13 | 14 | class Utils { 15 | 16 | protected static boolean isJsonResponse(Response response) { 17 | return response.body() != null && response.body().contentType() != null && response.body().contentType().subtype().equals("json"); 18 | } 19 | 20 | protected static Authenticator getAuthenticator(final OAuth2Client oAuth2Client, 21 | final AuthState authState) { 22 | return new Authenticator() { 23 | @Override 24 | public Request authenticate(Route route, Response response) throws IOException { 25 | String credential = ""; 26 | 27 | authState.nextState(); 28 | 29 | if (authState.isBasicAuth()) { 30 | credential = Credentials.basic(oAuth2Client.getUsername(), 31 | oAuth2Client.getPassword()); 32 | } else if (authState.isAuthorizationAuth()) { 33 | credential = Credentials.basic(oAuth2Client.getClientId(), 34 | oAuth2Client.getClientSecret()); 35 | } else if (authState.isFinalAuth()) { 36 | return null; 37 | } 38 | 39 | 40 | System.out.println("Authenticating for response: " + response); 41 | System.out.println("Challenges: " + response.challenges()); 42 | return response.request().newBuilder() 43 | .header(Constants.HEADER_AUTHORIZATION, credential) 44 | .build(); 45 | } 46 | }; 47 | } 48 | 49 | 50 | protected static void postAddIfValid(FormBody.Builder formBodyBuilder, Map params) { 51 | if (params == null) return; 52 | 53 | for (Map.Entry entry : params.entrySet()) { 54 | if (isValid(entry.getValue())) { 55 | formBodyBuilder.add(entry.getKey(), entry.getValue()); 56 | } 57 | } 58 | } 59 | 60 | private static boolean isValid(String s) { 61 | return (s != null && s.trim().length() > 0); 62 | } 63 | 64 | } 65 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /oauth2library/src/main/java/ca/mimic/oauth2library/OAuthResponse.java: -------------------------------------------------------------------------------- 1 | package ca.mimic.oauth2library; 2 | 3 | import com.squareup.moshi.Moshi; 4 | 5 | import java.io.IOException; 6 | 7 | import okhttp3.Response; 8 | 9 | public class OAuthResponse { 10 | private Response response; 11 | private String responseBody; 12 | private Token token; 13 | private OAuthError error; 14 | private boolean jsonParsed; 15 | private Long expiresAt; 16 | 17 | protected OAuthResponse(Response response) throws IOException { 18 | this.response = response; 19 | if (response != null) { 20 | responseBody = response.body().string(); 21 | 22 | if (Utils.isJsonResponse(response)) { 23 | Moshi moshi = new Moshi.Builder().build(); 24 | if (response.isSuccessful()) { 25 | token = moshi.adapter(Token.class).fromJson(responseBody); 26 | jsonParsed = true; 27 | 28 | if (token.expires_in != null) 29 | expiresAt = (token.expires_in * 1000) + System.currentTimeMillis(); 30 | } else { 31 | try { 32 | error = moshi.adapter(OAuthError.class).fromJson(responseBody); 33 | jsonParsed = true; 34 | } catch (Exception e) { 35 | error = new OAuthError(e); 36 | jsonParsed = false; 37 | 38 | } 39 | } 40 | } 41 | } 42 | } 43 | 44 | protected OAuthResponse(Exception e) { 45 | this.response = null; 46 | this.error = new OAuthError(e); 47 | } 48 | 49 | public boolean isSuccessful() { 50 | return response != null && response.isSuccessful() && jsonParsed; 51 | } 52 | 53 | public boolean isJsonResponse() { 54 | return jsonParsed; 55 | } 56 | 57 | public Integer getCode() { 58 | return response != null ? response.code(): null; 59 | } 60 | 61 | public Long getExpiresIn() { 62 | return token != null ? token.expires_in : null; 63 | } 64 | 65 | public Long getExpiresAt() { 66 | return expiresAt; 67 | } 68 | 69 | public String getTokenType() { 70 | return token != null ? token.token_type : null; 71 | } 72 | 73 | public String getRefreshToken() { 74 | return token != null ? token.refresh_token : null; 75 | } 76 | 77 | public String getAccessToken() { 78 | return token != null ? token.access_token : null; 79 | } 80 | 81 | public String getScope() { 82 | return token != null ? token.scope : null; 83 | } 84 | 85 | public String getBody() { 86 | return responseBody; 87 | } 88 | 89 | public OAuthError getOAuthError() { 90 | return error; 91 | } 92 | 93 | public Response getHttpResponse() { 94 | return response; 95 | } 96 | 97 | } 98 | -------------------------------------------------------------------------------- /oauth2library/src/main/java/ca/mimic/oauth2library/Access.java: -------------------------------------------------------------------------------- 1 | package ca.mimic.oauth2library; 2 | 3 | import java.io.IOException; 4 | 5 | import okhttp3.FormBody; 6 | import okhttp3.OkHttpClient; 7 | import okhttp3.Request; 8 | import okhttp3.Response; 9 | 10 | public class Access { 11 | protected static OAuthResponse refreshAccessToken(String token, OAuth2Client oAuth2Client) throws IOException { 12 | FormBody.Builder formBodyBuilder = new FormBody.Builder() 13 | .add(Constants.POST_REFRESH_TOKEN, token); 14 | 15 | Utils.postAddIfValid(formBodyBuilder, oAuth2Client.getFieldsAsMap()); 16 | 17 | final Request request = new Request.Builder() 18 | .url(oAuth2Client.getSite()) 19 | .post(formBodyBuilder.build()) 20 | .build(); 21 | 22 | return refreshTokenFromResponse(oAuth2Client, request); 23 | } 24 | 25 | private static OAuthResponse refreshTokenFromResponse(final OAuth2Client oAuth2Client, 26 | final Request request) throws IOException { 27 | return getTokenFromResponse(oAuth2Client, oAuth2Client.getOkHttpClient(), 28 | request, new AuthState(AuthState.REFRESH_TOKEN)); 29 | 30 | } 31 | 32 | protected static OAuthResponse getToken(OAuth2Client oAuth2Client) throws IOException { 33 | FormBody.Builder formBodyBuilder = new FormBody.Builder(); 34 | Utils.postAddIfValid(formBodyBuilder, oAuth2Client.getFieldsAsMap()); 35 | Utils.postAddIfValid(formBodyBuilder, oAuth2Client.getParameters()); 36 | 37 | return getAccessToken(oAuth2Client, formBodyBuilder); 38 | } 39 | 40 | private static OAuthResponse getAccessToken(OAuth2Client oAuth2Client, FormBody.Builder formBodyBuilder) 41 | throws IOException { 42 | final Request request = new Request.Builder() 43 | .url(oAuth2Client.getSite()) 44 | .post(formBodyBuilder.build()) 45 | .build(); 46 | 47 | return getTokenFromResponse(oAuth2Client, request); 48 | } 49 | 50 | private static OAuthResponse getTokenFromResponse(final OAuth2Client oAuth2Client, 51 | final Request request) throws IOException { 52 | return getTokenFromResponse(oAuth2Client, oAuth2Client.getOkHttpClient(), 53 | request, new AuthState(AuthState.ACCESS_TOKEN)); 54 | 55 | } 56 | 57 | private static OAuthResponse getTokenFromResponse(final OAuth2Client oAuth2Client, 58 | final OkHttpClient okHttpClient, 59 | final Request request, 60 | final AuthState authState) throws IOException { 61 | Response response = okHttpClient.newBuilder().authenticator(Utils.getAuthenticator(oAuth2Client, authState)) 62 | .build().newCall(request).execute(); 63 | 64 | return new OAuthResponse(response); 65 | } 66 | 67 | } 68 | -------------------------------------------------------------------------------- /oauth2library/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | apply plugin: 'com.jfrog.bintray' 3 | apply plugin: 'com.github.dcendents.android-maven' 4 | 5 | version = "2.4.2" 6 | 7 | android { 8 | compileSdkVersion 25 9 | 10 | defaultConfig { 11 | minSdkVersion 11 12 | targetSdkVersion 25 13 | versionCode 242 14 | versionName version 15 | 16 | consumerProguardFiles 'proguard-rules.txt' 17 | } 18 | 19 | buildTypes { 20 | release { 21 | minifyEnabled false 22 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt' 23 | } 24 | } 25 | 26 | lintOptions { 27 | disable 'InvalidPackage' 28 | } 29 | 30 | testOptions { 31 | unitTests.all { 32 | // All the usual Gradle options. 33 | testLogging { 34 | events "passed", "skipped", "failed", "standardOut", "standardError" 35 | outputs.upToDateWhen {false} 36 | showStandardStreams = true 37 | } 38 | } 39 | testOptions { 40 | unitTests.returnDefaultValues = true 41 | } 42 | } 43 | } 44 | 45 | dependencies { 46 | implementation fileTree(dir: 'libs', include: ['*.jar']) 47 | 48 | androidTestImplementation('com.android.support.test.espresso:espresso-core:2.2.2', { 49 | exclude group: 'com.android.support', module: 'support-annotations' 50 | }) 51 | 52 | compile 'com.squareup.okhttp3:okhttp:3.9.1' 53 | 54 | compile 'com.squareup.moshi:moshi:1.5.0' 55 | 56 | testImplementation 'junit:junit:4.12' 57 | } 58 | 59 | def siteUrl = 'https://github.com/mimicmobile/okhttp-oauth2-client' 60 | def gitUrl = 'https://github.com/mimicmobile/okhttp-oauth2-client.git' 61 | group = "ca.mimic" 62 | description = 'A modern Android oAuth2 library using OkHttp with resource owner password grant types and easy token refreshing. This library aims to provide a solution for the less commonly used resource owner password grant type as well as providing dynamic parameter support that can be used with frameworks that allow for more flexible and dynamic oAuth2 parameters.' 63 | 64 | install { 65 | repositories.mavenInstaller { 66 | // This generates POM.xml with proper parameters 67 | pom { 68 | project { 69 | packaging 'aar' 70 | 71 | // Add your description here 72 | name 'ca.mimic:oauth2library' 73 | description description 74 | url siteUrl 75 | 76 | // Set your license 77 | licenses { 78 | license { 79 | name 'The Apache Software License, Version 2.0' 80 | url 'http://www.apache.org/licenses/LICENSE-2.0.txt' 81 | } 82 | } 83 | developers { 84 | developer { 85 | id 'corcoran' 86 | name 'Jeff Corcoran' 87 | email 'jcorcoran@gmail.com' 88 | } 89 | } 90 | scm { 91 | connection gitUrl 92 | developerConnection gitUrl 93 | url siteUrl 94 | } 95 | } 96 | } 97 | } 98 | } 99 | 100 | task sourcesJar(type: Jar) { 101 | from android.sourceSets.main.java.srcDirs 102 | classifier = 'sources' 103 | } 104 | 105 | task javadoc(type: Javadoc) { 106 | source = android.sourceSets.main.java.srcDirs 107 | classpath += project.files(android.getBootClasspath().join(File.pathSeparator)) 108 | } 109 | 110 | task javadocJar(type: Jar, dependsOn: javadoc) { 111 | classifier = 'javadoc' 112 | from javadoc.destinationDir 113 | } 114 | 115 | artifacts { 116 | archives javadocJar 117 | archives sourcesJar 118 | } 119 | 120 | Properties properties = new Properties() 121 | properties.load(project.rootProject.file('local.properties').newDataInputStream()) 122 | 123 | bintray { 124 | user = properties.getProperty("bintray.user") 125 | key = properties.getProperty("bintray.apikey") 126 | 127 | configurations = ['archives'] 128 | pkg { 129 | repo = "maven" 130 | name = "ca.mimic:oauth2library" 131 | desc = description 132 | websiteUrl = siteUrl 133 | vcsUrl = gitUrl 134 | licenses = ["Apache-2.0"] 135 | publish = true 136 | publicDownloadNumbers = true 137 | version { 138 | gpg { 139 | sign = true //Determines whether to GPG sign the files. The default is false 140 | } 141 | } 142 | } 143 | } 144 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # OkHttp OAuth2 client 2 | 3 | A modern Android oAuth2 library using OkHttp with resource owner password grant types and easy token refreshing. 4 | This library aims to provide a solution for the less commonly used resource owner password grant type as well as providing dynamic parameter support that can be used with frameworks that allow for more flexible and dynamic oAuth2 parameters (such as the [Django REST framework social oAuth2 library](https://github.com/PhilipGarnero/django-rest-framework-social-oauth2)) 5 | 6 | [![License](https://img.shields.io/badge/License-Apache%202.0-yellow.svg)](https://opensource.org/licenses/Apache-2.0) 7 | [![Release](https://jitpack.io/v/mimicmobile/okhttp-oauth2-client.svg)](https://jitpack.io/#mimicmobile/okhttp-oauth2-client) 8 | [![Download](https://api.bintray.com/packages/corcoran/maven/ca.mimic%3Aoauth2library/images/download.svg) ](https://bintray.com/corcoran/maven/ca.mimic%3Aoauth2library/_latestVersion) 9 | 10 | ## Gradle 11 | 12 | The Gradle dependency is available via jCenter. jCenter is the default Maven repository used by Android Studio. 13 | 14 | ```gradle 15 | dependencies { 16 | // ... other dependencies here 17 | compile 'ca.mimic:oauth2library:2.4.2' 18 | } 19 | ``` 20 | 21 | ## Usage 22 | 23 | ```java 24 | OAuth2Client client = new OAuth2Client.Builder("username", "password", "client-id", "client-secret", "site").build(); 25 | OAuthResponse response = client.requestAccessToken(); 26 | 27 | if (response.isSuccessful()) { 28 | String accessToken = response.getAccessToken(); 29 | String refreshToken = response.getRefreshToken(); 30 | } else { 31 | OAuthError error = response.getOAuthError(); 32 | String errorMsg = error.getError(); 33 | } 34 | 35 | response.getCode(); // HTTP Status code 36 | ``` 37 | 38 | To refresh a token (defaults to "refresh_token" grant type) 39 | 40 | ```java 41 | OAuth2Client client = new OAuth2Client.Builder("client-id", "client-secret", "site").build(); 42 | OAuthResponse response = client.refreshAccessToken("refresh-token"); 43 | String accessToken = response.getAccessToken(); 44 | ``` 45 | 46 | ### Callbacks 47 | 48 | ```java 49 | client.requestAccessToken(new OAuthResponseCallback() { 50 | @Override 51 | public void onResponse(OAuthResponse response) { 52 | if (response.isSuccessful()) { 53 | // response.getAccessToken(); 54 | } else { 55 | // response.getOAuthError(); 56 | } 57 | } 58 | }); 59 | ``` 60 | 61 | ### Builder options and parameters 62 | 63 | Parameters for the builder 64 | 65 | ```java 66 | OAuth2Client.Builder builder = new OAuth2Client.Builder("client-id", "client-secret", "site") 67 | .grantType("grant-type") 68 | .scope("scope") 69 | .username("username") 70 | .password("password"); 71 | ``` 72 | 73 | Provide your own OkHttpClient to the builder 74 | 75 | ```java 76 | OkHttpClient client = new OkHttpClient(); 77 | 78 | OAuth2Client.Builder builder = new OAuth2Client.Builder("client-id", "client-secret", "site") 79 | .okHttpClient(client); 80 | ``` 81 | 82 | Provide additional name / value string parameters 83 | 84 | ```java 85 | Map map = new HashMap<>(); 86 | map.put("backend", "example-backend"); 87 | 88 | OAuth2Client.Builder builder = new OAuth2Client.Builder("client-id", "client-secret", "site") 89 | .parameters(map) 90 | ``` 91 | 92 | Wrap with RxJava! 93 | 94 | ```java 95 | OAuth2Client.Builder builder = new OAuth2Client.Builder("client-id", "client-secret", "http://localhost:8000/auth/token"); 96 | final OAuth2Client client = builder.build(); 97 | 98 | Observable observable = Observable.fromCallable(new Callable() { 99 | @Override 100 | public OAuthResponse call() throws Exception { 101 | return client.refreshAccessToken("refresh-token"); 102 | } 103 | }); 104 | 105 | observable.subscribe(new Action1() { 106 | @Override 107 | public void call(OAuthResponse oAuthResponse) { 108 | oAuthResponse.getAccessToken(); 109 | } 110 | }); 111 | ``` 112 | 113 | ### Extra response data 114 | OAuthResponse contains other potentially helpful data 115 | ```java 116 | OAuthResponse response = client.requestAccessToken(); 117 | response.getHttpResponse(); // OkHttp response 118 | response.getBody(); // Response body string 119 | response.isJsonResponse(); // Was JSON parsed? 120 | ``` 121 | 122 | ### Acknowledgments 123 | 124 | This library was inspired by the [android-oauth2-client](https://github.com/danielsz/android-oauth2-client) library by [Daniel Szmulewicz](https://github.com/danielsz) 125 | 126 | ## License 127 | 128 | ``` 129 | Copyright 2018 Mimic Mobile 130 | 131 | Licensed under the Apache License, Version 2.0 (the "License"); 132 | you may not use this file except in compliance with the License. 133 | You may obtain a copy of the License at 134 | 135 | http://www.apache.org/licenses/LICENSE-2.0 136 | 137 | Unless required by applicable law or agreed to in writing, software 138 | distributed under the License is distributed on an "AS IS" BASIS, 139 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 140 | See the License for the specific language governing permissions and 141 | limitations under the License. 142 | ``` 143 | 144 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | 12 | APP_NAME="Gradle" 13 | APP_BASE_NAME=`basename "$0"` 14 | 15 | # Use the maximum available, or set MAX_FD != -1 to use that value. 16 | MAX_FD="maximum" 17 | 18 | warn ( ) { 19 | echo "$*" 20 | } 21 | 22 | die ( ) { 23 | echo 24 | echo "$*" 25 | echo 26 | exit 1 27 | } 28 | 29 | # OS specific support (must be 'true' or 'false'). 30 | cygwin=false 31 | msys=false 32 | darwin=false 33 | case "`uname`" in 34 | CYGWIN* ) 35 | cygwin=true 36 | ;; 37 | Darwin* ) 38 | darwin=true 39 | ;; 40 | MINGW* ) 41 | msys=true 42 | ;; 43 | esac 44 | 45 | # Attempt to set APP_HOME 46 | # Resolve links: $0 may be a link 47 | PRG="$0" 48 | # Need this for relative symlinks. 49 | while [ -h "$PRG" ] ; do 50 | ls=`ls -ld "$PRG"` 51 | link=`expr "$ls" : '.*-> \(.*\)$'` 52 | if expr "$link" : '/.*' > /dev/null; then 53 | PRG="$link" 54 | else 55 | PRG=`dirname "$PRG"`"/$link" 56 | fi 57 | done 58 | SAVED="`pwd`" 59 | cd "`dirname \"$PRG\"`/" >/dev/null 60 | APP_HOME="`pwd -P`" 61 | cd "$SAVED" >/dev/null 62 | 63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 64 | 65 | # Determine the Java command to use to start the JVM. 66 | if [ -n "$JAVA_HOME" ] ; then 67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 68 | # IBM's JDK on AIX uses strange locations for the executables 69 | JAVACMD="$JAVA_HOME/jre/sh/java" 70 | else 71 | JAVACMD="$JAVA_HOME/bin/java" 72 | fi 73 | if [ ! -x "$JAVACMD" ] ; then 74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 75 | 76 | Please set the JAVA_HOME variable in your environment to match the 77 | location of your Java installation." 78 | fi 79 | else 80 | JAVACMD="java" 81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 82 | 83 | Please set the JAVA_HOME variable in your environment to match the 84 | location of your Java installation." 85 | fi 86 | 87 | # Increase the maximum file descriptors if we can. 88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 89 | MAX_FD_LIMIT=`ulimit -H -n` 90 | if [ $? -eq 0 ] ; then 91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 92 | MAX_FD="$MAX_FD_LIMIT" 93 | fi 94 | ulimit -n $MAX_FD 95 | if [ $? -ne 0 ] ; then 96 | warn "Could not set maximum file descriptor limit: $MAX_FD" 97 | fi 98 | else 99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 100 | fi 101 | fi 102 | 103 | # For Darwin, add options to specify how the application appears in the dock 104 | if $darwin; then 105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 106 | fi 107 | 108 | # For Cygwin, switch paths to Windows format before running java 109 | if $cygwin ; then 110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 112 | JAVACMD=`cygpath --unix "$JAVACMD"` 113 | 114 | # We build the pattern for arguments to be converted via cygpath 115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 116 | SEP="" 117 | for dir in $ROOTDIRSRAW ; do 118 | ROOTDIRS="$ROOTDIRS$SEP$dir" 119 | SEP="|" 120 | done 121 | OURCYGPATTERN="(^($ROOTDIRS))" 122 | # Add a user-defined pattern to the cygpath arguments 123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 125 | fi 126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 127 | i=0 128 | for arg in "$@" ; do 129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 131 | 132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 134 | else 135 | eval `echo args$i`="\"$arg\"" 136 | fi 137 | i=$((i+1)) 138 | done 139 | case $i in 140 | (0) set -- ;; 141 | (1) set -- "$args0" ;; 142 | (2) set -- "$args0" "$args1" ;; 143 | (3) set -- "$args0" "$args1" "$args2" ;; 144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 150 | esac 151 | fi 152 | 153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 154 | function splitJvmOpts() { 155 | JVM_OPTS=("$@") 156 | } 157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 159 | 160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 161 | -------------------------------------------------------------------------------- /oauth2library/src/main/java/ca/mimic/oauth2library/OAuth2Client.java: -------------------------------------------------------------------------------- 1 | package ca.mimic.oauth2library; 2 | 3 | import java.io.IOException; 4 | import java.util.HashMap; 5 | import java.util.Map; 6 | 7 | import okhttp3.OkHttpClient; 8 | 9 | public class OAuth2Client { 10 | private final String clientId; 11 | private final String clientSecret; 12 | private final String site; 13 | private final OkHttpClient okHttpClient; 14 | 15 | private String scope; 16 | private String grantType; 17 | 18 | private String username; 19 | private String password; 20 | 21 | private Map parameters; 22 | 23 | private OAuth2Client(Builder builder) { 24 | this.username = builder.username; 25 | this.password = builder.password; 26 | this.clientId = builder.clientId; 27 | this.clientSecret = builder.clientSecret; 28 | this.site = builder.site; 29 | this.scope = builder.scope; 30 | this.grantType = builder.grantType; 31 | this.okHttpClient= builder.okHttpClient; 32 | this.parameters = builder.parameters; 33 | } 34 | 35 | protected String getScope() { 36 | return scope; 37 | } 38 | 39 | protected String getGrantType() { 40 | return grantType; 41 | } 42 | 43 | protected String getClientId() { 44 | return clientId; 45 | } 46 | 47 | protected String getClientSecret() { 48 | return clientSecret; 49 | } 50 | 51 | protected String getSite() { 52 | return site; 53 | } 54 | 55 | protected String getUsername() { 56 | return username; 57 | } 58 | 59 | protected String getPassword() { 60 | return password; 61 | } 62 | 63 | public OAuthResponse refreshAccessToken(String refreshToken) throws IOException { 64 | if (this.grantType == null) 65 | this.grantType = Constants.GRANT_TYPE_REFRESH; 66 | return Access.refreshAccessToken(refreshToken, this); 67 | 68 | } 69 | 70 | public void refreshAccessToken(final String refreshToken, final OAuthResponseCallback callback) { 71 | new Thread(new Runnable() { 72 | @Override 73 | public void run() { 74 | OAuthResponse response; 75 | try { 76 | response = refreshAccessToken(refreshToken); 77 | callback.onResponse(response); 78 | } catch (Exception e) { 79 | response = new OAuthResponse(e); 80 | callback.onResponse(response); 81 | } 82 | } 83 | }).start(); 84 | } 85 | 86 | public OAuthResponse requestAccessToken() throws IOException { 87 | if (this.grantType == null) 88 | this.grantType = Constants.GRANT_TYPE_PASSWORD; 89 | return Access.getToken(this); 90 | } 91 | 92 | public void requestAccessToken(final OAuthResponseCallback callback) { 93 | new Thread(new Runnable() { 94 | @Override 95 | public void run() { 96 | OAuthResponse response; 97 | try { 98 | response = requestAccessToken(); 99 | callback.onResponse(response); 100 | } catch (Exception e) { 101 | response = new OAuthResponse(e); 102 | callback.onResponse(response); 103 | } 104 | } 105 | }).start(); 106 | } 107 | 108 | protected OkHttpClient getOkHttpClient() { 109 | if (this.okHttpClient == null) { 110 | return new OkHttpClient(); 111 | } else { 112 | return this.okHttpClient; 113 | } 114 | } 115 | 116 | protected Map getParameters() { 117 | if (parameters == null) { 118 | return new HashMap<>(); 119 | } else { 120 | return parameters; 121 | } 122 | } 123 | 124 | protected Map getFieldsAsMap() { 125 | Map oAuthParams = new HashMap<>(); 126 | oAuthParams.put(Constants.POST_CLIENT_ID, getClientId()); 127 | oAuthParams.put(Constants.POST_CLIENT_SECRET, getClientSecret()); 128 | oAuthParams.put(Constants.POST_GRANT_TYPE, getGrantType()); 129 | oAuthParams.put(Constants.POST_SCOPE, getScope()); 130 | oAuthParams.put(Constants.POST_USERNAME, getUsername()); 131 | oAuthParams.put(Constants.POST_PASSWORD, getPassword()); 132 | return oAuthParams; 133 | } 134 | 135 | public static class Builder { 136 | private final String clientId; 137 | private final String clientSecret; 138 | private final String site; 139 | 140 | private String scope; 141 | private String grantType; 142 | 143 | private String username; 144 | private String password; 145 | 146 | private OkHttpClient okHttpClient; 147 | 148 | private Map parameters; 149 | 150 | public Builder(String username, String password, String clientId, String clientSecret, 151 | String site) { 152 | this.username = username; 153 | this.password = password; 154 | this.clientId = clientId; 155 | this.clientSecret = clientSecret; 156 | this.site = site; 157 | this.okHttpClient = null; 158 | } 159 | 160 | public Builder(String clientId, String clientSecret, String site) { 161 | this.username = null; 162 | this.password = null; 163 | this.clientId = clientId; 164 | this.clientSecret = clientSecret; 165 | this.site = site; 166 | this.okHttpClient = null; 167 | } 168 | 169 | public Builder grantType(String grantType) { 170 | this.grantType = grantType; 171 | return this; 172 | } 173 | 174 | public Builder scope(String scope) { 175 | this.scope = scope; 176 | return this; 177 | } 178 | 179 | public Builder username(String username) { 180 | this.username = username; 181 | return this; 182 | } 183 | 184 | public Builder password(String password) { 185 | this.password = password; 186 | return this; 187 | } 188 | 189 | public Builder okHttpClient(OkHttpClient client) { 190 | this.okHttpClient = client; 191 | return this; 192 | } 193 | 194 | public Builder parameters(Map parameters) { 195 | this.parameters = parameters; 196 | return this; 197 | } 198 | 199 | public OAuth2Client build() { 200 | return new OAuth2Client(this); 201 | } 202 | 203 | } 204 | 205 | } 206 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | --------------------------------------------------------------------------------