From eee27d664c500bb754886462828120fae6fc8cbd Mon Sep 17 00:00:00 2001 From: Nakul Sabharwal Date: Mon, 28 Jan 2019 11:52:26 +0530 Subject: [PATCH 1/3] username and authorization-code auth providers --- .gitignore | 35 ++++ build.gradle | 39 ++++ gradle/wrapper/gradle-wrapper.properties | 5 + gradlew | 172 ++++++++++++++++++ gradlew.bat | 84 +++++++++ settings.gradle | 18 ++ .../microsoft/graph/auth/AuthConstants.java | 10 + .../graph/auth/BaseAuthentication.java | 96 ++++++++++ .../AuthorizationCodeProvider.java | 84 +++++++++ .../graph/auth/enums/NationalCloud.java | 8 + .../UsernamePasswordProvider.java | 82 +++++++++ .../graph/auth/BaseAuthenticationTests.java | 43 +++++ .../AuthorizationCodeProviderTests.java | 75 ++++++++ .../UsernamePasswordProviderTests.java | 54 ++++++ 14 files changed, 805 insertions(+) create mode 100644 .gitignore create mode 100644 build.gradle create mode 100644 gradle/wrapper/gradle-wrapper.properties create mode 100644 gradlew create mode 100644 gradlew.bat create mode 100644 settings.gradle create mode 100644 src/main/java/com/microsoft/graph/auth/AuthConstants.java create mode 100644 src/main/java/com/microsoft/graph/auth/BaseAuthentication.java create mode 100644 src/main/java/com/microsoft/graph/auth/confidentialClient/AuthorizationCodeProvider.java create mode 100644 src/main/java/com/microsoft/graph/auth/enums/NationalCloud.java create mode 100644 src/main/java/com/microsoft/graph/auth/publicClient/UsernamePasswordProvider.java create mode 100644 src/test/java/com/microsoft/graph/auth/BaseAuthenticationTests.java create mode 100644 src/test/java/com/microsoft/graph/auth/confidentialClient/AuthorizationCodeProviderTests.java create mode 100644 src/test/java/com/microsoft/graph/auth/publicClient/UsernamePasswordProviderTests.java diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..67b4c4a --- /dev/null +++ b/.gitignore @@ -0,0 +1,35 @@ +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* +/.gradle/ +/build/ +/bin/ + +#Eclipse +.project +.classpath +.settings + +# Maven +/target/ +/pom.xml +local.properties diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..f9cd232 --- /dev/null +++ b/build.gradle @@ -0,0 +1,39 @@ +/* + * This build file was generated by the Gradle 'init' task. + * + * This generated file contains a sample Java Library project to get you started. + * For more details take a look at the Java Libraries chapter in the Gradle + * user guide available at https://docs.gradle.org/4.3/userguide/java_library_plugin.html + */ + +// Apply the java-library plugin to add support for Java Library +apply plugin: 'java-library' + +// In this section you declare where to find the dependencies of your project +repositories { + // Use jcenter for resolving your dependencies. + // You can declare any Maven/Ivy/file repository here. + jcenter() + jcenter{ + url 'http://oss.jfrog.org/artifactory/oss-snapshot-local' + } +} + +dependencies { + // This dependency is exported to consumers, that is to say found on their compile classpath. + api 'org.apache.commons:commons-math3:3.6.1' + + // This dependency is used internally, and not exposed to consumers on their own compile classpath. + implementation 'com.google.guava:guava:23.0' + + // Use JUnit test framework + testImplementation 'junit:junit:4.12' + + compile 'org.mockito:mockito-core:2.9.0' + + compile 'org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:1.0.2' + + compile 'com.microsoft.graph:microsoft-graph-core:0.1.0-SNAPSHOT' + +} + diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..62e1e30 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionUrl=https\://services.gradle.org/distributions/gradle-4.3-bin.zip +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStorePath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..cccdd3d --- /dev/null +++ b/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/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..f955316 --- /dev/null +++ b/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/settings.gradle b/settings.gradle new file mode 100644 index 0000000..3af804f --- /dev/null +++ b/settings.gradle @@ -0,0 +1,18 @@ +/* + * This settings file was generated by the Gradle 'init' task. + * + * The settings file is used to specify which projects to include in your build. + * In a single project build this file can be empty or even removed. + * + * Detailed information about configuring a multi-project build in Gradle can be found + * in the user guide at https://docs.gradle.org/4.3/userguide/multi_project_builds.html + */ + +/* +// To declare projects as part of a multi-project build use the 'include' method +include 'shared' +include 'api' +include 'services:webservice' +*/ + +rootProject.name = 'msgraph-sdk-java-auth' diff --git a/src/main/java/com/microsoft/graph/auth/AuthConstants.java b/src/main/java/com/microsoft/graph/auth/AuthConstants.java new file mode 100644 index 0000000..d5386b6 --- /dev/null +++ b/src/main/java/com/microsoft/graph/auth/AuthConstants.java @@ -0,0 +1,10 @@ +package com.microsoft.graph.auth; + +public class AuthConstants { + public static class Tenants + { + public static final String Common = "common"; + public static final String Organizations = "organizations"; + public static final String Consumers = "consumers"; + } +} diff --git a/src/main/java/com/microsoft/graph/auth/BaseAuthentication.java b/src/main/java/com/microsoft/graph/auth/BaseAuthentication.java new file mode 100644 index 0000000..7669e55 --- /dev/null +++ b/src/main/java/com/microsoft/graph/auth/BaseAuthentication.java @@ -0,0 +1,96 @@ +package com.microsoft.graph.auth; + +import java.util.HashMap; +import java.util.List; + +import org.apache.oltu.oauth2.client.OAuthClient; +import org.apache.oltu.oauth2.client.URLConnectionClient; +import org.apache.oltu.oauth2.client.request.OAuthClientRequest; +import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder; +import org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse; +import org.apache.oltu.oauth2.common.message.types.GrantType; + +import com.microsoft.graph.auth.enums.NationalCloud; + +public class BaseAuthentication { + + protected List Scopes; + protected String ClientId; + protected String authority; + protected String ClientSecret; + protected long startTime; + protected NationalCloud nationalCloud; + protected String tenant; + protected String redirectUri = "https://localhost:8080"; + protected OAuthJSONAccessTokenResponse response; + + public BaseAuthentication( + List scopes, + String clientId, + String authority, + String redirectUri, + NationalCloud nationalCloud, + String tenant, + String ClientSecret) + { + this.Scopes = scopes; + this.ClientId = clientId; + this.authority = authority; + this.redirectUri = redirectUri; + this.nationalCloud = nationalCloud; + this.tenant = tenant; + this.ClientSecret = ClientSecret; + } + + protected static HashMap CloudList = new HashMap() + {{ + put( "Global", "https://login.microsoftonline.com/" ); + put( "China", "https://login.chinacloudapi.cn/" ); + put( "Germany", "https://login.microsoftonline.de/" ); + put( "UsGovernment", "https://login.microsoftonline.us/" ); + }}; + + protected static String GetAuthority(NationalCloud authorityEndpoint, String tenant) + { + return CloudList.get(authorityEndpoint.toString()) + tenant; + } + + protected String getScopesAsString() { + String scopeString = new String(); + for(String s : this.Scopes) { + scopeString+=(s+" "); + } + return scopeString; + } + + protected String getAccessTokenSilent() + { + long durationPassed = System.currentTimeMillis() - startTime; + if(this.response == null || durationPassed < 0) return null; + try { + if(durationPassed >= response.getExpiresIn()*1000) { + TokenRequestBuilder token = OAuthClientRequest. + tokenLocation(this.authority + "/oauth2/v2.0/token") + .setClientId(this.ClientId) + .setScope(getScopesAsString()) + .setRefreshToken(response.getRefreshToken()) + .setGrantType(GrantType.REFRESH_TOKEN) + .setScope(getScopesAsString()) + .setRedirectURI(redirectUri); + if(this.ClientSecret != null) { + token.setClientSecret(this.ClientSecret); + } + + OAuthClientRequest r = token.buildBodyMessage(); + OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient()); + this.startTime = System.currentTimeMillis(); + this.response = oAuthClient.accessToken(r); + return response.getAccessToken(); + } + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + +} diff --git a/src/main/java/com/microsoft/graph/auth/confidentialClient/AuthorizationCodeProvider.java b/src/main/java/com/microsoft/graph/auth/confidentialClient/AuthorizationCodeProvider.java new file mode 100644 index 0000000..90beed3 --- /dev/null +++ b/src/main/java/com/microsoft/graph/auth/confidentialClient/AuthorizationCodeProvider.java @@ -0,0 +1,84 @@ +package com.microsoft.graph.auth.confidentialClient; + +import java.util.List; + +import org.apache.oltu.oauth2.client.OAuthClient; +import org.apache.oltu.oauth2.client.URLConnectionClient; +import org.apache.oltu.oauth2.client.request.OAuthClientRequest; +import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder; +import org.apache.oltu.oauth2.common.exception.OAuthProblemException; +import org.apache.oltu.oauth2.common.exception.OAuthSystemException; +import org.apache.oltu.oauth2.common.message.types.GrantType; + +import com.microsoft.graph.auth.AuthConstants; +import com.microsoft.graph.auth.BaseAuthentication; +import com.microsoft.graph.auth.enums.NationalCloud; +import com.microsoft.graph.httpcore.IAuthenticationProvider; + + +public class AuthorizationCodeProvider extends BaseAuthentication implements IAuthenticationProvider{ + + public AuthorizationCodeProvider( + String clientId, + List scopes, + String authorizationCode, + String redirectUri, + String clientSecret){ + this(clientId, scopes, authorizationCode, redirectUri, null,null, clientSecret); + } + + public AuthorizationCodeProvider( + String clientId, + List scopes, + String authorizationCode, + String redirectUri, + NationalCloud nationalCloud, + String tenant, + String clientSecret){ + + super(scopes, + clientId, + GetAuthority(nationalCloud==null?NationalCloud.Global:nationalCloud, tenant == null ? AuthConstants.Tenants.Common : tenant), + redirectUri, + nationalCloud==null?NationalCloud.Global:nationalCloud, + tenant == null ? AuthConstants.Tenants.Common : tenant, + clientSecret); + + getAccessToken(authorizationCode); + } + + @Override + public String getAccessToken(){ + return getAccessTokenSilent(); + } + + private void getAccessToken(String authorizationCode) { + try { + OAuthClientRequest req = getTokenRequestMessage(authorizationCode); + getAccessTokenNewRequest(req); + } catch (Exception e) { + e.printStackTrace(); + } + } + + protected OAuthClientRequest getTokenRequestMessage(String authorizationCode) throws OAuthSystemException { + String tokenUrl = super.authority + "/oauth2/v2.0/token"; + TokenRequestBuilder token = OAuthClientRequest. + tokenLocation(tokenUrl) + .setClientId(this.ClientId) + .setCode(authorizationCode) + .setRedirectURI(this.redirectUri) + .setGrantType(GrantType.AUTHORIZATION_CODE) + .setScope(getScopesAsString()); + if(this.ClientSecret != null) { + token.setClientSecret(this.ClientSecret); + } + return token.buildBodyMessage(); + } + + protected void getAccessTokenNewRequest(OAuthClientRequest req) throws OAuthSystemException, OAuthProblemException { + OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient()); + super.startTime = System.currentTimeMillis(); + super.response = oAuthClient.accessToken(req); + } +} diff --git a/src/main/java/com/microsoft/graph/auth/enums/NationalCloud.java b/src/main/java/com/microsoft/graph/auth/enums/NationalCloud.java new file mode 100644 index 0000000..6442cfb --- /dev/null +++ b/src/main/java/com/microsoft/graph/auth/enums/NationalCloud.java @@ -0,0 +1,8 @@ +package com.microsoft.graph.auth.enums; + +public enum NationalCloud { + Global, + China, + Germany, + UsGovernment +} diff --git a/src/main/java/com/microsoft/graph/auth/publicClient/UsernamePasswordProvider.java b/src/main/java/com/microsoft/graph/auth/publicClient/UsernamePasswordProvider.java new file mode 100644 index 0000000..9c0daff --- /dev/null +++ b/src/main/java/com/microsoft/graph/auth/publicClient/UsernamePasswordProvider.java @@ -0,0 +1,82 @@ +package com.microsoft.graph.auth.publicClient; + +import java.util.List; + +import org.apache.oltu.oauth2.client.OAuthClient; +import org.apache.oltu.oauth2.client.URLConnectionClient; +import org.apache.oltu.oauth2.client.request.OAuthClientRequest; +import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder; +import org.apache.oltu.oauth2.common.exception.OAuthProblemException; +import org.apache.oltu.oauth2.common.exception.OAuthSystemException; +import org.apache.oltu.oauth2.common.message.types.GrantType; + +import com.microsoft.graph.auth.AuthConstants; +import com.microsoft.graph.auth.BaseAuthentication; +import com.microsoft.graph.auth.enums.NationalCloud; +import com.microsoft.graph.httpcore.IAuthenticationProvider; + +public class UsernamePasswordProvider extends BaseAuthentication implements IAuthenticationProvider{ + + private String Username; + private String Password; + + public UsernamePasswordProvider( + String clientId, + List scopes, + String username, + String password){ + this(clientId, scopes, username, password, NationalCloud.Global, AuthConstants.Tenants.Organizations); + } + + public UsernamePasswordProvider( + String clientId, + List scopes, + String username, + String password, + NationalCloud nationalCloud, + String tenant) { + super( scopes, + clientId, + GetAuthority(nationalCloud == null?NationalCloud.Global:nationalCloud, tenant == null?AuthConstants.Tenants.Organizations:tenant), + null, + (nationalCloud == null) ? NationalCloud.Global : nationalCloud, + tenant, + null); + this.Username = username; + this.Password = password; + } + + @Override + public String getAccessToken(){ + String accessToken = getAccessTokenSilent(); + if(accessToken == null) { + try { + OAuthClientRequest req = getTokenRequestMessage(); + accessToken = getAccessTokenNewRequest(req); + }catch (Exception e) { + e.printStackTrace(); + } + } + return accessToken; + } + + protected OAuthClientRequest getTokenRequestMessage() throws OAuthSystemException { + String tokenUrl = this.authority + "/oauth2/v2.0/token"; + TokenRequestBuilder token = OAuthClientRequest. + tokenLocation(tokenUrl) + .setClientId(this.ClientId) + .setUsername(this.Username) + .setPassword(this.Password) + .setGrantType(GrantType.PASSWORD) + .setScope(getScopesAsString()); + OAuthClientRequest req = token.buildBodyMessage(); + return req; + } + + protected String getAccessTokenNewRequest(OAuthClientRequest req) throws OAuthSystemException, OAuthProblemException { + OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient()); + super.startTime = System.currentTimeMillis(); + super.response = oAuthClient.accessToken(req); + return super.response.getAccessToken(); + } +} diff --git a/src/test/java/com/microsoft/graph/auth/BaseAuthenticationTests.java b/src/test/java/com/microsoft/graph/auth/BaseAuthenticationTests.java new file mode 100644 index 0000000..372baa1 --- /dev/null +++ b/src/test/java/com/microsoft/graph/auth/BaseAuthenticationTests.java @@ -0,0 +1,43 @@ +package com.microsoft.graph.auth; + +import static org.junit.Assert.assertEquals; + +import java.util.Arrays; +import java.util.List; + +import org.junit.Test; + +import com.microsoft.graph.auth.enums.NationalCloud; + +public class BaseAuthenticationTests { + + private String CLIENT_ID = "CLIENT_ID"; + private String REDIRECT_URL = "http://localhost"; + private String SECRET = "CLIENT_SECRET"; + private List SCOPES = Arrays.asList("user.read", "openid", "profile", "offline_access"); + private String AUTHORIZATION_CODE = "AUTHORIZATION_CODE"; + private NationalCloud NATIONAL_CLOUD = NationalCloud.Global; + private String TENANT = AuthConstants.Tenants.Common; + + @Test + public void testCloudListMap() { + assertEquals(BaseAuthentication.CloudList.get("Global"), "https://login.microsoftonline.com/"); + assertEquals(BaseAuthentication.CloudList.get("China"), "https://login.chinacloudapi.cn/"); + } + + @Test + public void getAuthorityTest() { + String actual = BaseAuthentication.GetAuthority(NationalCloud.Global, AuthConstants.Tenants.Common); + String expected = "https://login.microsoftonline.com/common"; + assertEquals(expected, actual); + } + + @Test + public void getScopesAsStringTest() { + BaseAuthentication baseAuthentication = new BaseAuthentication(SCOPES, CLIENT_ID, BaseAuthentication.GetAuthority(NATIONAL_CLOUD, TENANT), REDIRECT_URL, NATIONAL_CLOUD, TENANT, SECRET); + String actual = baseAuthentication.getScopesAsString(); + String expected = "user.read openid profile offline_access"; + assertEquals(expected, actual); + } + +} diff --git a/src/test/java/com/microsoft/graph/auth/confidentialClient/AuthorizationCodeProviderTests.java b/src/test/java/com/microsoft/graph/auth/confidentialClient/AuthorizationCodeProviderTests.java new file mode 100644 index 0000000..4db3cf8 --- /dev/null +++ b/src/test/java/com/microsoft/graph/auth/confidentialClient/AuthorizationCodeProviderTests.java @@ -0,0 +1,75 @@ +package com.microsoft.graph.auth.confidentialClient; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.util.Arrays; +import java.util.List; + +import org.apache.oltu.oauth2.client.request.OAuthClientRequest; +import org.apache.oltu.oauth2.common.exception.OAuthProblemException; +import org.apache.oltu.oauth2.common.exception.OAuthSystemException; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; + +import com.microsoft.graph.auth.AuthConstants; +import com.microsoft.graph.auth.enums.NationalCloud; + +@Ignore +@RunWith(MockitoJUnitRunner.class) +public class AuthorizationCodeProviderTests { + + private String CLIENT_ID = "CLIENT_ID"; + private String REDIRECT_URL = "http://localhost"; + private String SECRET = "CLIENT_SECRET"; + private List SCOPES = Arrays.asList("user.read", "openid", "profile", "offline_access"); + private String AUTHORIZATION_CODE = "AUTHORIZATION_CODE"; + private NationalCloud NATIONAL_CLOUD = NationalCloud.Global; + private String TENANT = AuthConstants.Tenants.Common; + + @Test + public void getAuthorizationCodeProviderTest() { + AuthorizationCodeProvider authorizationCodeProvider = new AuthorizationCodeProvider(CLIENT_ID, SCOPES, AUTHORIZATION_CODE, REDIRECT_URL, SECRET); + assertNotNull(authorizationCodeProvider); + } + + @Test + public void getAuthorizationCodeProviderWithNationalCloudTenantTest() { + AuthorizationCodeProvider authorizationCodeProvider = new AuthorizationCodeProvider(CLIENT_ID, SCOPES, AUTHORIZATION_CODE, REDIRECT_URL, NATIONAL_CLOUD, TENANT, SECRET); + assertNotNull(authorizationCodeProvider); + } + + @Test + public void getTokenRequestMessageTest() throws OAuthSystemException { + String expected = "code=AUTHORIZATION_CODE&grant_type=authorization_code&scope=user.read+openid+profile+offline_access+&redirect_uri=http%3A%2F%2Flocalhost&client_secret=CLIENT_SECRET&client_id=CLIENT_ID"; + AuthorizationCodeProvider authorizationCodeProvider = new AuthorizationCodeProvider(CLIENT_ID, SCOPES, AUTHORIZATION_CODE, REDIRECT_URL, SECRET); + OAuthClientRequest request = authorizationCodeProvider.getTokenRequestMessage(AUTHORIZATION_CODE); + assertEquals(expected, request.getBody().toString()); + } + + @Test + public void authenticateRequestTest() throws OAuthSystemException, OAuthProblemException { + AuthorizationCodeProvider authorizationCodeProvider = Mockito.mock(AuthorizationCodeProvider.class); + Mockito.when(authorizationCodeProvider.getTokenRequestMessage(AUTHORIZATION_CODE)).thenReturn(Mockito.mock(OAuthClientRequest.class)); + String actual = authorizationCodeProvider.getAccessToken(); + assertEquals("test_accessToken" , actual); + } + + @Test + public void getAccessTokenNewRequestTest() throws OAuthSystemException, OAuthProblemException { + AuthorizationCodeProvider authorizationCodeProvider = new AuthorizationCodeProvider(CLIENT_ID, SCOPES, AUTHORIZATION_CODE, REDIRECT_URL, SECRET); + String actualAccessToken = authorizationCodeProvider.getAccessToken(); + assertNotNull(actualAccessToken); + } + + @Test + public void getAccessTokenNewRequestWithNationalCloudTenantTest() throws OAuthSystemException, OAuthProblemException { + AuthorizationCodeProvider authorizationCodeProvider = new AuthorizationCodeProvider(CLIENT_ID, SCOPES, AUTHORIZATION_CODE, REDIRECT_URL, NATIONAL_CLOUD, TENANT, SECRET); + String actualAccessToken = authorizationCodeProvider.getAccessToken(); + assertNotNull(actualAccessToken); + } + +} diff --git a/src/test/java/com/microsoft/graph/auth/publicClient/UsernamePasswordProviderTests.java b/src/test/java/com/microsoft/graph/auth/publicClient/UsernamePasswordProviderTests.java new file mode 100644 index 0000000..54224bf --- /dev/null +++ b/src/test/java/com/microsoft/graph/auth/publicClient/UsernamePasswordProviderTests.java @@ -0,0 +1,54 @@ +package com.microsoft.graph.auth.publicClient; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.util.Arrays; +import java.util.List; + +import org.apache.oltu.oauth2.client.request.OAuthClientRequest; +import org.apache.oltu.oauth2.common.exception.OAuthProblemException; +import org.apache.oltu.oauth2.common.exception.OAuthSystemException; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.mockito.internal.matchers.Any; +import org.mockito.junit.MockitoJUnitRunner; + + +@RunWith(MockitoJUnitRunner.class) +public class UsernamePasswordProviderTests { + + private String CLIENT_ID = "CLIENT_ID"; + private List SCOPES = Arrays.asList("user.read", "openid", "profile", "offline_access"); + private String USERNAME = "USERNAME"; + private String PASSWORD = "PASSWORD"; + + @Test + public void getTokenRequestMessageTest() throws OAuthSystemException { + String expected = "password=PASSWORD&grant_type=password&scope=user.read+openid+profile+offline_access+&client_id=CLIENT_ID&username=USERNAME"; + UsernamePasswordProvider usernamePasswordProvider = new UsernamePasswordProvider(CLIENT_ID, SCOPES, USERNAME, PASSWORD); + OAuthClientRequest request = usernamePasswordProvider.getTokenRequestMessage(); + assertEquals(expected, request.getBody().toString()); + } + + @Ignore + @Test + public void authenticateRequestTest() throws OAuthSystemException, OAuthProblemException { + UsernamePasswordProvider usernamePasswordProvider = Mockito.mock(UsernamePasswordProvider.class); + Mockito.when(usernamePasswordProvider.getTokenRequestMessage()).thenReturn(Mockito.mock(OAuthClientRequest.class)); + Mockito.when(usernamePasswordProvider.getAccessTokenNewRequest(Mockito.any())).thenReturn("test_accessToken"); + String actual = usernamePasswordProvider.getAccessToken(); + assertEquals("test_accessToken" , actual); + } + + @Ignore + @Test + public void getAccessTokenNewRequestTest() throws OAuthSystemException, OAuthProblemException { + UsernamePasswordProvider usernamePasswordProvider = new UsernamePasswordProvider(CLIENT_ID, SCOPES, USERNAME, PASSWORD); + String actualAccessToken = usernamePasswordProvider.getAccessTokenNewRequest(usernamePasswordProvider.getTokenRequestMessage()); + assertNotNull(actualAccessToken); + } + +} From 441567c9caba9a7b692e0809e0bfbfcaad8cf024 Mon Sep 17 00:00:00 2001 From: Nakul Sabharwal Date: Mon, 28 Jan 2019 12:11:04 +0530 Subject: [PATCH 2/3] BaseAuthenticationTests edited tests --- .../java/com/microsoft/graph/auth/BaseAuthenticationTests.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/com/microsoft/graph/auth/BaseAuthenticationTests.java b/src/test/java/com/microsoft/graph/auth/BaseAuthenticationTests.java index 372baa1..a59a493 100644 --- a/src/test/java/com/microsoft/graph/auth/BaseAuthenticationTests.java +++ b/src/test/java/com/microsoft/graph/auth/BaseAuthenticationTests.java @@ -36,7 +36,7 @@ public void getAuthorityTest() { public void getScopesAsStringTest() { BaseAuthentication baseAuthentication = new BaseAuthentication(SCOPES, CLIENT_ID, BaseAuthentication.GetAuthority(NATIONAL_CLOUD, TENANT), REDIRECT_URL, NATIONAL_CLOUD, TENANT, SECRET); String actual = baseAuthentication.getScopesAsString(); - String expected = "user.read openid profile offline_access"; + String expected = "user.read openid profile offline_access "; assertEquals(expected, actual); } From 89baa0a10eacbfd695cb794d60994a1ab1c11b43 Mon Sep 17 00:00:00 2001 From: Nakul Sabharwal Date: Fri, 1 Feb 2019 17:47:47 +0530 Subject: [PATCH 3/3] Changed variable names and indentation. --- .../graph/auth/BaseAuthentication.java | 11 +++++----- .../AuthorizationCodeProvider.java | 20 +++++++++---------- .../UsernamePasswordProvider.java | 20 +++++++++---------- 3 files changed, 26 insertions(+), 25 deletions(-) diff --git a/src/main/java/com/microsoft/graph/auth/BaseAuthentication.java b/src/main/java/com/microsoft/graph/auth/BaseAuthentication.java index 7669e55..b6ec76a 100644 --- a/src/main/java/com/microsoft/graph/auth/BaseAuthentication.java +++ b/src/main/java/com/microsoft/graph/auth/BaseAuthentication.java @@ -56,11 +56,12 @@ protected static String GetAuthority(NationalCloud authorityEndpoint, String ten } protected String getScopesAsString() { - String scopeString = new String(); + StringBuilder scopeString = new StringBuilder(); for(String s : this.Scopes) { - scopeString+=(s+" "); + scopeString.append(s); + scopeString.append(" "); } - return scopeString; + return scopeString.toString(); } protected String getAccessTokenSilent() @@ -81,10 +82,10 @@ protected String getAccessTokenSilent() token.setClientSecret(this.ClientSecret); } - OAuthClientRequest r = token.buildBodyMessage(); + OAuthClientRequest request = token.buildBodyMessage(); OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient()); this.startTime = System.currentTimeMillis(); - this.response = oAuthClient.accessToken(r); + this.response = oAuthClient.accessToken(request); return response.getAccessToken(); } } catch (Exception e) { diff --git a/src/main/java/com/microsoft/graph/auth/confidentialClient/AuthorizationCodeProvider.java b/src/main/java/com/microsoft/graph/auth/confidentialClient/AuthorizationCodeProvider.java index 90beed3..9e1d8bf 100644 --- a/src/main/java/com/microsoft/graph/auth/confidentialClient/AuthorizationCodeProvider.java +++ b/src/main/java/com/microsoft/graph/auth/confidentialClient/AuthorizationCodeProvider.java @@ -24,7 +24,7 @@ public AuthorizationCodeProvider( String authorizationCode, String redirectUri, String clientSecret){ - this(clientId, scopes, authorizationCode, redirectUri, null,null, clientSecret); + this(clientId, scopes, authorizationCode, redirectUri, null, null, clientSecret); } public AuthorizationCodeProvider( @@ -36,13 +36,13 @@ public AuthorizationCodeProvider( String tenant, String clientSecret){ - super(scopes, + super( scopes, clientId, - GetAuthority(nationalCloud==null?NationalCloud.Global:nationalCloud, tenant == null ? AuthConstants.Tenants.Common : tenant), + GetAuthority(nationalCloud == null? NationalCloud.Global: nationalCloud, tenant == null? AuthConstants.Tenants.Common: tenant), redirectUri, - nationalCloud==null?NationalCloud.Global:nationalCloud, - tenant == null ? AuthConstants.Tenants.Common : tenant, - clientSecret); + nationalCloud == null? NationalCloud.Global: nationalCloud, + tenant == null? AuthConstants.Tenants.Common: tenant, + clientSecret); getAccessToken(authorizationCode); } @@ -54,8 +54,8 @@ public String getAccessToken(){ private void getAccessToken(String authorizationCode) { try { - OAuthClientRequest req = getTokenRequestMessage(authorizationCode); - getAccessTokenNewRequest(req); + OAuthClientRequest request = getTokenRequestMessage(authorizationCode); + getAccessTokenNewRequest(request); } catch (Exception e) { e.printStackTrace(); } @@ -76,9 +76,9 @@ protected OAuthClientRequest getTokenRequestMessage(String authorizationCode) th return token.buildBodyMessage(); } - protected void getAccessTokenNewRequest(OAuthClientRequest req) throws OAuthSystemException, OAuthProblemException { + protected void getAccessTokenNewRequest(OAuthClientRequest request) throws OAuthSystemException, OAuthProblemException { OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient()); super.startTime = System.currentTimeMillis(); - super.response = oAuthClient.accessToken(req); + super.response = oAuthClient.accessToken(request); } } diff --git a/src/main/java/com/microsoft/graph/auth/publicClient/UsernamePasswordProvider.java b/src/main/java/com/microsoft/graph/auth/publicClient/UsernamePasswordProvider.java index 9c0daff..72dd5d5 100644 --- a/src/main/java/com/microsoft/graph/auth/publicClient/UsernamePasswordProvider.java +++ b/src/main/java/com/microsoft/graph/auth/publicClient/UsernamePasswordProvider.java @@ -37,11 +37,11 @@ public UsernamePasswordProvider( String tenant) { super( scopes, clientId, - GetAuthority(nationalCloud == null?NationalCloud.Global:nationalCloud, tenant == null?AuthConstants.Tenants.Organizations:tenant), + GetAuthority(nationalCloud == null? NationalCloud.Global: nationalCloud, tenant == null? AuthConstants.Tenants.Organizations: tenant), null, - (nationalCloud == null) ? NationalCloud.Global : nationalCloud, - tenant, - null); + nationalCloud == null? NationalCloud.Global: nationalCloud, + tenant, + null); this.Username = username; this.Password = password; } @@ -51,8 +51,8 @@ public String getAccessToken(){ String accessToken = getAccessTokenSilent(); if(accessToken == null) { try { - OAuthClientRequest req = getTokenRequestMessage(); - accessToken = getAccessTokenNewRequest(req); + OAuthClientRequest request = getTokenRequestMessage(); + accessToken = getAccessTokenNewRequest(request); }catch (Exception e) { e.printStackTrace(); } @@ -69,14 +69,14 @@ protected OAuthClientRequest getTokenRequestMessage() throws OAuthSystemExceptio .setPassword(this.Password) .setGrantType(GrantType.PASSWORD) .setScope(getScopesAsString()); - OAuthClientRequest req = token.buildBodyMessage(); - return req; + OAuthClientRequest request = token.buildBodyMessage(); + return request; } - protected String getAccessTokenNewRequest(OAuthClientRequest req) throws OAuthSystemException, OAuthProblemException { + protected String getAccessTokenNewRequest(OAuthClientRequest request) throws OAuthSystemException, OAuthProblemException { OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient()); super.startTime = System.currentTimeMillis(); - super.response = oAuthClient.accessToken(req); + super.response = oAuthClient.accessToken(request); return super.response.getAccessToken(); } }