From eee27d664c500bb754886462828120fae6fc8cbd Mon Sep 17 00:00:00 2001 From: Nakul Sabharwal Date: Mon, 28 Jan 2019 11:52:26 +0530 Subject: [PATCH 01/10] 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 02/10] 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 03/10] 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(); } } From f6c9220c6ec3676f2bf6b91a37c5c4d22fe671ef Mon Sep 17 00:00:00 2001 From: Nakul Sabharwal Date: Mon, 11 Feb 2019 13:02:09 +0530 Subject: [PATCH 04/10] Added Client Credential Provider --- .../ClientCredentialProvider.java | 70 +++++++++++++++++++ .../ClientCredentialProviderTests.java | 41 +++++++++++ 2 files changed, 111 insertions(+) create mode 100644 src/main/java/com/microsoft/graph/auth/confidentialClient/ClientCredentialProvider.java create mode 100644 src/test/java/com/microsoft/graph/auth/confidentialClient/ClientCredentialProviderTests.java diff --git a/src/main/java/com/microsoft/graph/auth/confidentialClient/ClientCredentialProvider.java b/src/main/java/com/microsoft/graph/auth/confidentialClient/ClientCredentialProvider.java new file mode 100644 index 0000000..d1c073f --- /dev/null +++ b/src/main/java/com/microsoft/graph/auth/confidentialClient/ClientCredentialProvider.java @@ -0,0 +1,70 @@ +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.BaseAuthentication; +import com.microsoft.graph.auth.enums.NationalCloud; +import com.microsoft.graph.httpcore.IAuthenticationProvider; + +public class ClientCredentialProvider extends BaseAuthentication implements IAuthenticationProvider{ + + public ClientCredentialProvider(String clientId, + List scopes, + String clientSecret, + String tenant, + NationalCloud nationalCloud) { + super( scopes, + clientId, + GetAuthority(nationalCloud == null? NationalCloud.Global: nationalCloud, tenant), + null, + nationalCloud == null? NationalCloud.Global: nationalCloud, + tenant, + clientSecret); + } + + @Override + public String getAccessToken() { + if(super.response != null) { + long duration = System.currentTimeMillis() - super.startTime; + if(duration > 0 && duration < super.response.getExpiresIn()*1000) { + return super.response.getAccessToken(); + } + } + String accessToken = null; + try { + OAuthClientRequest request = getTokenRequestMessage(); + accessToken = getAccessTokenNewRequest(request); + } catch (Exception e) { + e.printStackTrace(); + } + return accessToken; + } + + protected OAuthClientRequest getTokenRequestMessage() throws OAuthSystemException { + String tokenUrl = super.authority + "/oauth2/v2.0/token"; + TokenRequestBuilder token = OAuthClientRequest. + tokenLocation(tokenUrl) + .setClientId(super.ClientId) + .setGrantType(GrantType.CLIENT_CREDENTIALS) + .setScope(getScopesAsString()); + if(super.ClientSecret != null) { + token.setClientSecret(this.ClientSecret); + } + return token.buildBodyMessage(); + } + + protected String getAccessTokenNewRequest(OAuthClientRequest request) throws OAuthSystemException, OAuthProblemException { + OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient()); + super.startTime = System.currentTimeMillis(); + super.response = oAuthClient.accessToken(request); + return super.response.getAccessToken(); + } +} diff --git a/src/test/java/com/microsoft/graph/auth/confidentialClient/ClientCredentialProviderTests.java b/src/test/java/com/microsoft/graph/auth/confidentialClient/ClientCredentialProviderTests.java new file mode 100644 index 0000000..88dc5f3 --- /dev/null +++ b/src/test/java/com/microsoft/graph/auth/confidentialClient/ClientCredentialProviderTests.java @@ -0,0 +1,41 @@ +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.common.exception.OAuthSystemException; +import org.junit.Test; + +import com.microsoft.graph.auth.enums.NationalCloud; +import com.microsoft.graph.httpcore.IAuthenticationProvider; + +public class ClientCredentialProviderTests { + public static String CLIENT_ID = "CLIENT_ID"; + public static String SCOPE = "https://graph.microsoft.com/.default"; + public static List SCOPES = Arrays.asList(SCOPE); + public static String CLIENT_SECRET = "CLIENT_SECRET"; + public static String CLIENT_ASSERTION = "CLIENT_ASSERTION"; + public static String TENANT = "TENANT_GUID_OR_DOMAIN_NAME"; + public static NationalCloud NATIONAL_CLOUD = NationalCloud.Global; + + @Test + public void createInstanceClientSecretTest() { + IAuthenticationProvider authenticationProvider = new ClientCredentialProvider(CLIENT_ID, SCOPES, CLIENT_SECRET, TENANT, NATIONAL_CLOUD); + assertNotNull(authenticationProvider); + } + + @Test + public void getTokenRequestMessageTest() throws OAuthSystemException { + ClientCredentialProvider authenticationProvider = new ClientCredentialProvider(CLIENT_ID, SCOPES, CLIENT_SECRET, TENANT, NATIONAL_CLOUD); + String expected = "grant_type=client_credentials&scope=https%3A%2F%2Fgraph.microsoft.com%2F.default+&client_secret=CLIENT_SECRET&client_id=CLIENT_ID"; + String actual = authenticationProvider.getTokenRequestMessage().getBody(); + String expectedLocationUri = "https://login.microsoftonline.com/TENANT_GUID_OR_DOMAIN_NAME/oauth2/v2.0/token"; + String actualLocationUri = authenticationProvider.getTokenRequestMessage().getLocationUri(); + assertEquals(expected, actual); + assertEquals(expectedLocationUri, actualLocationUri); + } + +} From 61d68accf2fe513c5f3f3e0490e0d88b9362c4a0 Mon Sep 17 00:00:00 2001 From: Nakul Sabharwal Date: Wed, 13 Feb 2019 17:40:34 +0530 Subject: [PATCH 05/10] Added tests for ClientCredentialProvider, edited providers with authenticateRequest impl. --- .../microsoft/graph/auth/AuthConstants.java | 3 + .../AuthorizationCodeProvider.java | 45 ++++++++++---- .../ClientCredentialProvider.java | 61 +++++++++++++------ .../UsernamePasswordProvider.java | 33 +++++----- .../AuthorizationCodeProviderTests.java | 19 ++++-- .../ClientCredentialProviderTests.java | 34 +++++++++++ .../UsernamePasswordProviderTests.java | 50 ++++++++++++++- 7 files changed, 190 insertions(+), 55 deletions(-) diff --git a/src/main/java/com/microsoft/graph/auth/AuthConstants.java b/src/main/java/com/microsoft/graph/auth/AuthConstants.java index d5386b6..15fa3d9 100644 --- a/src/main/java/com/microsoft/graph/auth/AuthConstants.java +++ b/src/main/java/com/microsoft/graph/auth/AuthConstants.java @@ -7,4 +7,7 @@ public static class Tenants public static final String Organizations = "organizations"; public static final String Consumers = "consumers"; } + public static final String BEARER = "Bearer "; + public static final String TOKEN_ENDPOINT = "/oauth2/v2.0/token"; + public static final String AUTHORIZATION_HEADER = "Authorization"; } 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 9e1d8bf..7c89978 100644 --- a/src/main/java/com/microsoft/graph/auth/confidentialClient/AuthorizationCodeProvider.java +++ b/src/main/java/com/microsoft/graph/auth/confidentialClient/AuthorizationCodeProvider.java @@ -2,6 +2,7 @@ import java.util.List; +import org.apache.http.HttpRequest; import org.apache.oltu.oauth2.client.OAuthClient; import org.apache.oltu.oauth2.client.URLConnectionClient; import org.apache.oltu.oauth2.client.request.OAuthClientRequest; @@ -18,6 +19,15 @@ public class AuthorizationCodeProvider extends BaseAuthentication implements IAuthenticationProvider{ + /* + * Authorization code provider initialization + * + * @param clientId Client ID of application + * @param scopes Scopes of application to access protected resources + * @param authorizationCode Authorization code + * @param redirectUri Redirect uri provided while getting authorization code + * @param clientSecret Client secret of application + */ public AuthorizationCodeProvider( String clientId, List scopes, @@ -27,6 +37,16 @@ public AuthorizationCodeProvider( this(clientId, scopes, authorizationCode, redirectUri, null, null, clientSecret); } + /* + * Authorization code provider initialization + * + * @param clientId Client ID of application + * @param scopes Scopes of application to access protected resources + * @param authorizationCode Authorization code + * @param redirectUri Redirect uri provided while getting authorization code + * @param nationalCloud National cloud to access + * @param clientSecret Client secret of application + */ public AuthorizationCodeProvider( String clientId, List scopes, @@ -48,11 +68,12 @@ public AuthorizationCodeProvider( } @Override - public String getAccessToken(){ - return getAccessTokenSilent(); + public void authenticateRequest(HttpRequest request) { + String tokenParameter = AuthConstants.BEARER + getAccessTokenSilent(); + request.addHeader(AuthConstants.AUTHORIZATION_HEADER, tokenParameter); } - private void getAccessToken(String authorizationCode) { + void getAccessToken(String authorizationCode) { try { OAuthClientRequest request = getTokenRequestMessage(authorizationCode); getAccessTokenNewRequest(request); @@ -61,24 +82,24 @@ private void getAccessToken(String authorizationCode) { } } - protected OAuthClientRequest getTokenRequestMessage(String authorizationCode) throws OAuthSystemException { - String tokenUrl = super.authority + "/oauth2/v2.0/token"; + OAuthClientRequest getTokenRequestMessage(String authorizationCode) throws OAuthSystemException { + String tokenUrl = getAuthority() + AuthConstants.TOKEN_ENDPOINT; TokenRequestBuilder token = OAuthClientRequest. tokenLocation(tokenUrl) - .setClientId(this.ClientId) + .setClientId(getClientId()) .setCode(authorizationCode) - .setRedirectURI(this.redirectUri) + .setRedirectURI(getRedirectUri()) .setGrantType(GrantType.AUTHORIZATION_CODE) .setScope(getScopesAsString()); - if(this.ClientSecret != null) { - token.setClientSecret(this.ClientSecret); + if(getClientSecret() != null) { + token.setClientSecret(getClientSecret()); } return token.buildBodyMessage(); } - protected void getAccessTokenNewRequest(OAuthClientRequest request) throws OAuthSystemException, OAuthProblemException { + void getAccessTokenNewRequest(OAuthClientRequest request) throws OAuthSystemException, OAuthProblemException { OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient()); - super.startTime = System.currentTimeMillis(); - super.response = oAuthClient.accessToken(request); + setStartTime(System.currentTimeMillis()); + setResponse(oAuthClient.accessToken(request)); } } diff --git a/src/main/java/com/microsoft/graph/auth/confidentialClient/ClientCredentialProvider.java b/src/main/java/com/microsoft/graph/auth/confidentialClient/ClientCredentialProvider.java index d1c073f..13d76b2 100644 --- a/src/main/java/com/microsoft/graph/auth/confidentialClient/ClientCredentialProvider.java +++ b/src/main/java/com/microsoft/graph/auth/confidentialClient/ClientCredentialProvider.java @@ -2,6 +2,7 @@ import java.util.List; +import org.apache.http.HttpRequest; import org.apache.oltu.oauth2.client.OAuthClient; import org.apache.oltu.oauth2.client.URLConnectionClient; import org.apache.oltu.oauth2.client.request.OAuthClientRequest; @@ -10,12 +11,22 @@ 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 ClientCredentialProvider extends BaseAuthentication implements IAuthenticationProvider{ + /* + * Client credential provider instance using client secret + * + * @param clientId Client ID of application + * @param scopes Scopes that application need to access protected resources + * @param clientSecret Client secret of application + * @param tenant The tenant GUID or friendly name format or common + * + */ public ClientCredentialProvider(String clientId, List scopes, String clientSecret, @@ -31,40 +42,50 @@ public ClientCredentialProvider(String clientId, } @Override - public String getAccessToken() { - if(super.response != null) { - long duration = System.currentTimeMillis() - super.startTime; - if(duration > 0 && duration < super.response.getExpiresIn()*1000) { - return super.response.getAccessToken(); - } - } - String accessToken = null; + public void authenticateRequest(HttpRequest request) { try { - OAuthClientRequest request = getTokenRequestMessage(); - accessToken = getAccessTokenNewRequest(request); + String accessToken = null; + long duration = System.currentTimeMillis() - getStartTime(); + if(getResponse()!=null && duration>0 && duration< getResponse().getExpiresIn()*1000) { + accessToken = getResponse().getAccessToken(); + } else { + OAuthClientRequest authRequest = getTokenRequestMessage(); + accessToken = getAccessTokenNewRequest(authRequest); + } + request.addHeader(AuthConstants.AUTHORIZATION_HEADER, AuthConstants.BEARER + accessToken); } catch (Exception e) { e.printStackTrace(); } - return accessToken; } - protected OAuthClientRequest getTokenRequestMessage() throws OAuthSystemException { - String tokenUrl = super.authority + "/oauth2/v2.0/token"; + /* + * Create the token request message + * + * @return The token request message + */ + OAuthClientRequest getTokenRequestMessage() throws OAuthSystemException { + String tokenUrl = getAuthority() + AuthConstants.TOKEN_ENDPOINT; TokenRequestBuilder token = OAuthClientRequest. tokenLocation(tokenUrl) - .setClientId(super.ClientId) + .setClientId(getClientId()) .setGrantType(GrantType.CLIENT_CREDENTIALS) .setScope(getScopesAsString()); - if(super.ClientSecret != null) { - token.setClientSecret(this.ClientSecret); + if(getClientSecret() != null) { + token.setClientSecret(getClientSecret()); } return token.buildBodyMessage(); } - protected String getAccessTokenNewRequest(OAuthClientRequest request) throws OAuthSystemException, OAuthProblemException { + /* + * Call using request to get response containing access token + * + * @param request The request to execute + * @return The access token in response + */ + String getAccessTokenNewRequest(OAuthClientRequest request) throws OAuthSystemException, OAuthProblemException { OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient()); - super.startTime = System.currentTimeMillis(); - super.response = oAuthClient.accessToken(request); - return super.response.getAccessToken(); + setStartTime(System.currentTimeMillis()); + setResponse(oAuthClient.accessToken(request)); + return getResponse().getAccessToken(); } } 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 72dd5d5..6d148f4 100644 --- a/src/main/java/com/microsoft/graph/auth/publicClient/UsernamePasswordProvider.java +++ b/src/main/java/com/microsoft/graph/auth/publicClient/UsernamePasswordProvider.java @@ -2,6 +2,7 @@ import java.util.List; +import org.apache.http.HttpRequest; import org.apache.oltu.oauth2.client.OAuthClient; import org.apache.oltu.oauth2.client.URLConnectionClient; import org.apache.oltu.oauth2.client.request.OAuthClientRequest; @@ -25,7 +26,7 @@ public UsernamePasswordProvider( List scopes, String username, String password){ - this(clientId, scopes, username, password, NationalCloud.Global, AuthConstants.Tenants.Organizations); + this(clientId, scopes, username, password, NationalCloud.Global, AuthConstants.Tenants.Organizations, null); } public UsernamePasswordProvider( @@ -34,49 +35,53 @@ public UsernamePasswordProvider( String username, String password, NationalCloud nationalCloud, - String tenant) { + String tenant, + String clientSecret) { super( scopes, clientId, GetAuthority(nationalCloud == null? NationalCloud.Global: nationalCloud, tenant == null? AuthConstants.Tenants.Organizations: tenant), null, nationalCloud == null? NationalCloud.Global: nationalCloud, tenant, - null); + clientSecret); this.Username = username; this.Password = password; } @Override - public String getAccessToken(){ + public void authenticateRequest(HttpRequest request) { String accessToken = getAccessTokenSilent(); if(accessToken == null) { try { - OAuthClientRequest request = getTokenRequestMessage(); - accessToken = getAccessTokenNewRequest(request); + OAuthClientRequest authRequest = getTokenRequestMessage(); + accessToken = getAccessTokenNewRequest(authRequest); }catch (Exception e) { e.printStackTrace(); } } - return accessToken; + request.addHeader("Authorization", AuthConstants.BEARER + accessToken); } - protected OAuthClientRequest getTokenRequestMessage() throws OAuthSystemException { - String tokenUrl = this.authority + "/oauth2/v2.0/token"; + OAuthClientRequest getTokenRequestMessage() throws OAuthSystemException { + String tokenUrl = getAuthority() + AuthConstants.TOKEN_ENDPOINT; TokenRequestBuilder token = OAuthClientRequest. tokenLocation(tokenUrl) - .setClientId(this.ClientId) + .setClientId(getClientId()) .setUsername(this.Username) .setPassword(this.Password) .setGrantType(GrantType.PASSWORD) .setScope(getScopesAsString()); + if(getClientSecret() != null) { + token.setClientSecret(getClientSecret()); + } OAuthClientRequest request = token.buildBodyMessage(); return request; } - protected String getAccessTokenNewRequest(OAuthClientRequest request) throws OAuthSystemException, OAuthProblemException { + String getAccessTokenNewRequest(OAuthClientRequest request) throws OAuthSystemException, OAuthProblemException { OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient()); - super.startTime = System.currentTimeMillis(); - super.response = oAuthClient.accessToken(request); - return super.response.getAccessToken(); + setStartTime(System.currentTimeMillis()); + setResponse(oAuthClient.accessToken(request)); + return getResponse().getAccessToken(); } } diff --git a/src/test/java/com/microsoft/graph/auth/confidentialClient/AuthorizationCodeProviderTests.java b/src/test/java/com/microsoft/graph/auth/confidentialClient/AuthorizationCodeProviderTests.java index 4db3cf8..0484646 100644 --- a/src/test/java/com/microsoft/graph/auth/confidentialClient/AuthorizationCodeProviderTests.java +++ b/src/test/java/com/microsoft/graph/auth/confidentialClient/AuthorizationCodeProviderTests.java @@ -6,6 +6,7 @@ import java.util.Arrays; import java.util.List; +import org.apache.http.client.methods.HttpGet; import org.apache.oltu.oauth2.client.request.OAuthClientRequest; import org.apache.oltu.oauth2.common.exception.OAuthProblemException; import org.apache.oltu.oauth2.common.exception.OAuthSystemException; @@ -54,22 +55,28 @@ public void getTokenRequestMessageTest() throws OAuthSystemException { 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); + HttpGet httpget = new HttpGet("https://graph.microsoft.com/v1.0/me/"); + authorizationCodeProvider.authenticateRequest(httpget); + String actual = httpget.getFirstHeader("Authorization").getValue(); + assertEquals("Bearer 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); + HttpGet httpget = new HttpGet("https://graph.microsoft.com/v1.0/me/"); + authorizationCodeProvider.authenticateRequest(httpget); + String actualTokenparameter = httpget.getFirstHeader("Authorization").getValue(); + assertNotNull(actualTokenparameter); } @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); + HttpGet httpget = new HttpGet("https://graph.microsoft.com/v1.0/me/"); + authorizationCodeProvider.authenticateRequest(httpget); + String actualTokenparameter = httpget.getFirstHeader("Authorization").getValue(); + assertNotNull(actualTokenparameter); } } diff --git a/src/test/java/com/microsoft/graph/auth/confidentialClient/ClientCredentialProviderTests.java b/src/test/java/com/microsoft/graph/auth/confidentialClient/ClientCredentialProviderTests.java index 88dc5f3..918f024 100644 --- a/src/test/java/com/microsoft/graph/auth/confidentialClient/ClientCredentialProviderTests.java +++ b/src/test/java/com/microsoft/graph/auth/confidentialClient/ClientCredentialProviderTests.java @@ -3,13 +3,24 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; +import java.io.IOException; import java.util.Arrays; import java.util.List; +import org.apache.http.HttpResponse; +import org.apache.http.client.ClientProtocolException; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.protocol.HttpClientContext; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.util.EntityUtils; +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 com.microsoft.graph.auth.enums.NationalCloud; +import com.microsoft.graph.httpcore.HttpClients; import com.microsoft.graph.httpcore.IAuthenticationProvider; public class ClientCredentialProviderTests { @@ -20,6 +31,7 @@ public class ClientCredentialProviderTests { public static String CLIENT_ASSERTION = "CLIENT_ASSERTION"; public static String TENANT = "TENANT_GUID_OR_DOMAIN_NAME"; public static NationalCloud NATIONAL_CLOUD = NationalCloud.Global; + public static String tenantGUID = "TENANT_GUID"; @Test public void createInstanceClientSecretTest() { @@ -38,4 +50,26 @@ public void getTokenRequestMessageTest() throws OAuthSystemException { assertEquals(expectedLocationUri, actualLocationUri); } + @Ignore + @Test + public void getAccessTokenNewRequestTest() throws OAuthSystemException, OAuthProblemException { + ClientCredentialProvider authenticationProvider = new ClientCredentialProvider(CLIENT_ID, SCOPES, CLIENT_SECRET, TENANT, NATIONAL_CLOUD); + OAuthClientRequest request = authenticationProvider.getTokenRequestMessage(); + String accessToken = authenticationProvider.getAccessTokenNewRequest(request); + assertNotNull(accessToken); + } + + @Ignore + @Test + public void authenticateRequestTest() throws ClientProtocolException, IOException { + IAuthenticationProvider iAuthenticationProvider = new ClientCredentialProvider(CLIENT_ID, SCOPES, CLIENT_SECRET, tenantGUID, NationalCloud.Global); + CloseableHttpClient httpclient = HttpClients.createDefault(iAuthenticationProvider); + HttpGet httpget = new HttpGet("https://graph.microsoft.com/v1.0/groups"); + System.out.println("Executing request " + httpget.getRequestLine()); + HttpClientContext localContext = HttpClientContext.create(); + HttpResponse response = httpclient.execute(httpget, localContext); + assertNotNull(response); + assertNotNull(EntityUtils.toString(response.getEntity())); + } + } diff --git a/src/test/java/com/microsoft/graph/auth/publicClient/UsernamePasswordProviderTests.java b/src/test/java/com/microsoft/graph/auth/publicClient/UsernamePasswordProviderTests.java index 54224bf..63a94a6 100644 --- a/src/test/java/com/microsoft/graph/auth/publicClient/UsernamePasswordProviderTests.java +++ b/src/test/java/com/microsoft/graph/auth/publicClient/UsernamePasswordProviderTests.java @@ -3,9 +3,15 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; +import java.io.IOException; import java.util.Arrays; import java.util.List; +import org.apache.http.HttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.protocol.HttpClientContext; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.util.EntityUtils; import org.apache.oltu.oauth2.client.request.OAuthClientRequest; import org.apache.oltu.oauth2.common.exception.OAuthProblemException; import org.apache.oltu.oauth2.common.exception.OAuthSystemException; @@ -13,9 +19,13 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; -import org.mockito.internal.matchers.Any; import org.mockito.junit.MockitoJUnitRunner; +import com.microsoft.graph.auth.AuthConstants; +import com.microsoft.graph.auth.enums.NationalCloud; +import com.microsoft.graph.httpcore.HttpClients; +import com.microsoft.graph.httpcore.IAuthenticationProvider; + @RunWith(MockitoJUnitRunner.class) public class UsernamePasswordProviderTests { @@ -24,6 +34,8 @@ public class UsernamePasswordProviderTests { private List SCOPES = Arrays.asList("user.read", "openid", "profile", "offline_access"); private String USERNAME = "USERNAME"; private String PASSWORD = "PASSWORD"; + private NationalCloud NATIONAL_CLOUD = NationalCloud.Global; + private String CLIENT_SECRET = "CLIENT_SECRET"; @Test public void getTokenRequestMessageTest() throws OAuthSystemException { @@ -39,8 +51,10 @@ public void authenticateRequestTest() throws OAuthSystemException, OAuthProblemE 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); + HttpGet httpget = new HttpGet("https://graph.microsoft.com/v1.0/me/"); + usernamePasswordProvider.authenticateRequest(httpget); + String actualtokenParameter = httpget.getFirstHeader("Authorization").getValue(); + assertEquals("Bearer test_accessToken" , actualtokenParameter); } @Ignore @@ -51,4 +65,34 @@ public void getAccessTokenNewRequestTest() throws OAuthSystemException, OAuthPro assertNotNull(actualAccessToken); } + @Ignore + @Test + public void publicClientWithClientSecretTest() throws OAuthSystemException, OAuthProblemException { + java.util.List s = Arrays.asList("user.read", "openid", "profile", "offline_access"); + IAuthenticationProvider authenticationProvider = + new UsernamePasswordProvider(CLIENT_ID, + SCOPES, + USERNAME, + PASSWORD, + NATIONAL_CLOUD, + AuthConstants.Tenants.Organizations, + CLIENT_SECRET); + callGraph(authenticationProvider); + } + + public static void callGraph(IAuthenticationProvider authenticationProvider) { + CloseableHttpClient httpclient = HttpClients.createDefault(authenticationProvider); + HttpGet httpget = new HttpGet("https://graph.microsoft.com/v1.0/me/"); + HttpClientContext localContext = HttpClientContext.create(); + HttpResponse response; + try { + response = httpclient.execute(httpget, localContext); + String responseBody = EntityUtils.toString(response.getEntity()); + System.out.println(responseBody); + assertNotNull(responseBody); + } catch (IOException e) { + e.printStackTrace(); + } + } + } From 4c9140b9c2c9ca114a9d424fcc0d75b44ab3493e Mon Sep 17 00:00:00 2001 From: Nakul Sabharwal Date: Wed, 13 Feb 2019 17:41:19 +0530 Subject: [PATCH 06/10] Added setter and getters for variables in BaseAuthentication. --- .../graph/auth/BaseAuthentication.java | 77 ++++++++++++++----- 1 file changed, 59 insertions(+), 18 deletions(-) diff --git a/src/main/java/com/microsoft/graph/auth/BaseAuthentication.java b/src/main/java/com/microsoft/graph/auth/BaseAuthentication.java index b6ec76a..1a12655 100644 --- a/src/main/java/com/microsoft/graph/auth/BaseAuthentication.java +++ b/src/main/java/com/microsoft/graph/auth/BaseAuthentication.java @@ -14,15 +14,15 @@ 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; + private List scopes; + private String clientId; + private String authority; + private String clientSecret; + private long startTime; + private NationalCloud nationalCloud; + private String tenant; + private String redirectUri = "https://localhost:8080"; + private OAuthJSONAccessTokenResponse response; public BaseAuthentication( List scopes, @@ -31,15 +31,15 @@ public BaseAuthentication( String redirectUri, NationalCloud nationalCloud, String tenant, - String ClientSecret) + String clientSecret) { - this.Scopes = scopes; - this.ClientId = clientId; + this.scopes = scopes; + this.clientId = clientId; this.authority = authority; this.redirectUri = redirectUri; this.nationalCloud = nationalCloud; this.tenant = tenant; - this.ClientSecret = ClientSecret; + this.clientSecret = clientSecret; } protected static HashMap CloudList = new HashMap() @@ -57,7 +57,7 @@ protected static String GetAuthority(NationalCloud authorityEndpoint, String ten protected String getScopesAsString() { StringBuilder scopeString = new StringBuilder(); - for(String s : this.Scopes) { + for(String s : this.scopes) { scopeString.append(s); scopeString.append(" "); } @@ -71,15 +71,15 @@ protected String getAccessTokenSilent() try { if(durationPassed >= response.getExpiresIn()*1000) { TokenRequestBuilder token = OAuthClientRequest. - tokenLocation(this.authority + "/oauth2/v2.0/token") - .setClientId(this.ClientId) + tokenLocation(this.authority + AuthConstants.TOKEN_ENDPOINT) + .setClientId(this.clientId) .setScope(getScopesAsString()) .setRefreshToken(response.getRefreshToken()) .setGrantType(GrantType.REFRESH_TOKEN) .setScope(getScopesAsString()) .setRedirectURI(redirectUri); - if(this.ClientSecret != null) { - token.setClientSecret(this.ClientSecret); + if(this.clientSecret != null) { + token.setClientSecret(this.clientSecret); } OAuthClientRequest request = token.buildBodyMessage(); @@ -88,10 +88,51 @@ protected String getAccessTokenSilent() this.response = oAuthClient.accessToken(request); return response.getAccessToken(); } + else return response.getAccessToken(); } catch (Exception e) { e.printStackTrace(); } return null; } + + protected String getAuthority() { + return this.authority; + } + + protected String getClientId() { + return this.clientId; + } + + protected String getClientSecret() { + return this.clientSecret; + } + + protected String getRedirectUri() { + return this.redirectUri; + } + + protected void setResponse(OAuthJSONAccessTokenResponse response) { + this.response = response; + } + + protected OAuthJSONAccessTokenResponse getResponse() { + return this.response; + } + + protected long getStartTime() { + return this.startTime; + } + + protected void setStartTime(long startTime) { + this.startTime = startTime; + } + + protected NationalCloud getNationalCloud() { + return this.nationalCloud; + } + + protected String getTenant() { + return this.tenant; + } } From 90c8301c8926cd7fa5e35849d3e60c54edf78554 Mon Sep 17 00:00:00 2001 From: Nakul Sabharwal Date: Wed, 13 Feb 2019 20:06:04 +0530 Subject: [PATCH 07/10] build and publish script --- build.gradle | 297 +++++++++++++++++++++++++++++++++++++++++++--- gradle.properties | 27 +++++ 2 files changed, 305 insertions(+), 19 deletions(-) create mode 100644 gradle.properties diff --git a/build.gradle b/build.gradle index f9cd232..94968ee 100644 --- a/build.gradle +++ b/build.gradle @@ -1,39 +1,298 @@ -/* - * 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' +apply plugin: 'java' +apply plugin: 'eclipse' +apply plugin: 'maven' +apply plugin: 'maven-publish' +apply plugin: 'signing' -// 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' } + mavenCentral() } 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 + // Use JUnit and mockito 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' - } +def pomConfig = { + licenses { + license([:]) { + name "MIT License" + url "http://opensource.org/licenses/MIT" + distribution "repo" + } + } +} + +//Publishing tasks- +//Maven Central Snapshot: publishSnapshotPublicationToMavenRepository +//Maven Central Release: publishMavenCentralReleasePublicationToMaven2Repository +//Bintray Snapshot: publishSnapshotPublicationToMaven3Repository +//Bintray Release: uploadArchives + +publishing { + + publications { + + maven(MavenPublication) { + + groupId 'com.microsoft.graph' + + artifactId 'microsoft-graph-auth' + + version "${mavenMajorVersion}.${mavenMinorVersion}.${mavenPatchVersion}${mavenArtifactSuffix}" + + from components.java + + artifact sourceJar + pom.withXml { + def root = asNode() + root.appendNode('name', 'Microsoft Graph SDK for Java') + root.appendNode('url', 'https://github.com/microsoftgraph/msgraph-sdk-java') + root.children().last() + pomConfig + def pomFile = file("${project.buildDir}/libs/microsoft-graph.pom") + writeTo(pomFile) + } + + } + Snapshot(MavenPublication) { + customizePom(pom) + groupId 'com.microsoft.graph' + artifactId 'microsoft-graph-auth' + version "${mavenMajorVersion}.${mavenMinorVersion}.${mavenPatchVersion}${mavenCentralSnapshotArtifactSuffix}" + from components.java + pom.withXml { + def pomFile = file("${project.buildDir}/generated-pom.xml") + writeTo(pomFile) + } + artifact(sourceJar) { + classifier = 'sources' + } + artifact(javadocJar) { + classifier = 'javadoc' + } + } + + mavenCentralRelease(MavenPublication) { + customizePom(pom) + groupId 'com.microsoft.graph' + artifactId 'microsoft-graph-auth' + version "${mavenMajorVersion}.${mavenMinorVersion}.${mavenPatchVersion}" + from components.java + pom.withXml { + def pomFile = file("${project.buildDir}/generated-pom.xml") + writeTo(pomFile) + def pomAscFile = signing.sign(pomFile).signatureFiles[0] + artifact(pomAscFile) { + classifier = null + extension = 'pom.asc' + } + } + artifact(sourceJar) { + classifier = 'sources' + } + artifact(javadocJar) { + classifier = 'javadoc' + } + project.tasks.signArchives.signatureFiles.each { + artifact(it) { + def matcher = it.file =~ /-(sources|javadoc)\.jar\.asc$/ + if(matcher.find()){ + classifier = matcher.group(1) + } + else{ + classifier = null + } + extension = 'jar.asc' + } + } + } + } + repositories { + maven { + url = project.property('mavenCentralSnapshotUrl') + + credentials { + if (project.rootProject.file('local.properties').exists()) { + Properties properties = new Properties() + properties.load(project.rootProject.file('local.properties').newDataInputStream()) + username = properties.getProperty('sonatypeUsername') + password = properties.getProperty('sonatypePassword') + } + } + } + + maven { + url = project.property('mavenCentralReleaseUrl') + + credentials { + if (project.rootProject.file('local.properties').exists()) { + Properties properties = new Properties() + properties.load(project.rootProject.file('local.properties').newDataInputStream()) + username = properties.getProperty('sonatypeUsername') + password = properties.getProperty('sonatypePassword') + } + } + } + + maven { + url = project.property('mavenBintraySnapshotUrl') + + credentials { + if (project.rootProject.file('local.properties').exists()) { + Properties properties = new Properties() + properties.load(project.rootProject.file('local.properties').newDataInputStream()) + username = (properties.containsKey('bintray.user')) ? properties.getProperty('bintray.user').toLowerCase() : "BINTRAY_USERNAME" + password = properties.getProperty('bintray.apikey') + } + } + } + } + +} + +task sourceJar(type: Jar) { + classifier = 'sources' + from sourceSets.main.allJava +} + +compileJava { + sourceCompatibility = 1.7 + targetCompatibility = 1.7 +} + +def getVersionCode() { + return mavenMajorVersion.toInteger() * 10000 + mavenMinorVersion.toInteger() * 100 + mavenPatchVersion.toInteger() +} + +def getVersionName() { + return "${mavenMajorVersion}.${mavenMinorVersion}.${mavenPatchVersion}${mavenArtifactSuffix}" +} + +uploadArchives { + + def bintrayUsername = "" + + def bintrayApikey = "" + + if (project.rootProject.file('local.properties').exists()) { + Properties properties = new Properties() + properties.load(project.rootProject.file('local.properties').newDataInputStream()) + bintrayUsername = properties.getProperty('bintray.user') + bintrayApikey = properties.getProperty('bintray.apikey') + } + + configuration = configurations.archives + + repositories.mavenDeployer { + + pom { + setGroupId project.mavenGroupId + setArtifactId project.mavenArtifactId + setVersion getVersionName() + } + + repository (url: project.mavenRepoUrl) { + url = url + "/" + getVersionName() + + authentication( + // put these values in local file ~/.gradle/gradle.properties + userName: project.hasProperty("bintrayUsername") ? project.bintrayUsername : bintrayUsername, + password: project.hasProperty("bintrayApikey") ? project.bintrayApikey : bintrayApikey + ) + } + } +} + +task javadocJar(type: Jar, dependsOn: javadoc) { + classifier = 'javadoc' + from javadoc.destinationDir +} + +artifacts { + archives jar + archives sourceJar + archives javadocJar +} + +signing { + sign configurations.archives +} +tasks.withType(Sign)*.enabled = mavenCentralPublishingEnabled.toBoolean() + +def customizePom(pom) { + pom.withXml { + def root = asNode() + + root.dependencies.removeAll { dep -> + dep.scope == "test" + } + + root.children().last() + { + resolveStrategy = Closure.DELEGATE_FIRST + + description 'Microsoft Graph SDK Auth' + name 'Microsoft Graph Java SDK Auth' + url 'https://github.com/microsoftgraph/msgraph-sdk-java-auth' + organization { + name 'Microsoft' + url 'https://github.com/microsoftgraph/msgraph-sdk-java-auth' + } + issueManagement { + system 'GitHub' + url 'https://github.com/microsoftgraph/msgraph-sdk-java-auth/issues' + } + licenses { + license { + name "MIT License" + url "http://opensource.org/licenses/MIT" + distribution "repo" + } + } + scm { + url 'https://github.com/microsoftgraph/msgraph-sdk-java-auth' + connection 'scm:git:git://github.com/microsoftgraph/msgraph-sdk-java-auth.git' + developerConnection 'scm:git:ssh://git@github.com:microsoftgraph/msgraph-sdk-java-auth.git' + } + developers { + developer { + name 'Microsoft' + } + } + } + } +} + +gradle.taskGraph.whenReady { taskGraph -> + if (project.rootProject.file('local.properties').exists()) { + Properties properties = new Properties() + properties.load(project.rootProject.file('local.properties').newDataInputStream()) + tasks.withType(Sign)*.enabled = (properties.containsKey('enableSigning')) ? properties.getProperty('enableSigning').toBoolean() : false + allprojects { ext."signing.keyId" = properties.getProperty('signing.keyId') } + allprojects { ext."signing.secretKeyRingFile" = properties.getProperty('signing.secretKeyRingFile') } + allprojects { ext."signing.password" = properties.getProperty('signing.password') } + } +} + +model { + tasks.generatePomFileForMavenCentralReleasePublication { + destination = file("$buildDir/generated-pom.xml") + } + tasks.publishMavenCentralReleasePublicationToMavenLocal { + dependsOn project.tasks.signArchives + } + tasks.publishMavenCentralReleasePublicationToMaven2Repository { + dependsOn project.tasks.signArchives + } +} \ No newline at end of file diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..0e1ee92 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,27 @@ +# The size of the library demands a large amount of RAM to build. Increase as necessary if you get GC errors +## linux requires 10G, OSX requires 11G +org.gradle.jvmargs=-XX:MaxPermSize=512m -Xmx2g + +mavenRepoUrl = https://api.bintray.com/content/microsoftgraph/Maven/microsoft-graph +mavenBintraySnapshotUrl = http://oss.jfrog.org/artifactory/oss-snapshot-local +mavenGroupId = com.microsoft.graph +mavenArtifactId = microsoft-graph-auth +mavenMajorVersion = 0 +mavenMinorVersion = 1 +mavenPatchVersion = 0 +mavenArtifactSuffix = +nightliesUrl = http://dl.bintray.com/MicrosoftGraph/Maven + +#These values are used to run functional tests +#If you wish to run the functional tests, edit the gradle.properties +#file in your user directory instead of adding them here. +#ex: C:\Users\username\.gradle\gradle.properties +ClientId="CLIENT_ID" +Username="USERNAME" +Password="PASSWORD" + +#enable mavenCentralPublishingEnabled to publish to maven central +mavenCentralSnapshotUrl=https://oss.sonatype.org/content/repositories/snapshots +mavenCentralReleaseUrl=https://oss.sonatype.org/service/local/staging/deploy/maven2 +mavenCentralSnapshotArtifactSuffix = -SNAPSHOT +mavenCentralPublishingEnabled=false \ No newline at end of file From 1285f0c3aefe1063ac769c5fb481bb7bf3deb9a0 Mon Sep 17 00:00:00 2001 From: Nakul Sabharwal Date: Thu, 14 Feb 2019 11:58:08 +0530 Subject: [PATCH 08/10] edited readme --- README.md | 166 +++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 165 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 44cd440..a450b5f 100644 --- a/README.md +++ b/README.md @@ -1 +1,165 @@ -"# msgraph-sdk-java-auth" +# Microsoft Graph Auth SDK for Java + +[ ![Download](https://api.bintray.com/packages/microsoftgraph/Maven/microsoft-graph/images/download.svg) ](https://bintray.com/microsoftgraph/Maven/microsoft-graph/_latestVersion) + + +Get started with the Microsoft Graph SDK for Java by integrating the [Microsoft Graph API](https://graph.microsoft.io/en-us/getting-started) into your Java application! + +## 1. Installation + +### 1.1 Install via Gradle + +Add the repository and a compile dependency for `microsoft-graph` to your project's `build.gradle`: + +```gradle +repository { + jcenter() + jcenter{ + url 'http://oss.jfrog.org/artifactory/oss-snapshot-local' + } +} + +dependency { + // Include the sdk as a dependency + compile('com.microsoft.graph:microsoft-graph-auth:0.1.0-SNAPSHOT') +} +``` + +### 1.2 Install via Maven +Add the dependency in `dependencies` in pom.xml +```dependency + + com.microsoft.graph + microsoft-graph-auth + 0.1.0-SNAPSHOT + +``` + +## 2. Getting started + +### 2.1 Register your application + +Register your application by following the steps at [Register your app with the Azure AD v2.0 endpoint](https://developer.microsoft.com/en-us/graph/docs/concepts/auth_register_app_v2). + +### 2.2 Create an IAuthenticationProvider object + +#### 2.3.1 Confidential client authentication provider + +##### a. Authorization code provider +```java +IAuthenticationProvider authorizationCodeProvider = new AuthorizationCodeProvider(CLIENT_ID, SCOPES_LIST, AUTHORIZATION_CODE, REDIRECT_URL, NATIONAL_CLOUD, TENANT, SECRET); +``` + +##### b. Client credential provider +```java +IAuthenticationProvider iAuthenticationProvider = new ClientCredentialProvider(CLIENT_ID, SCOPES_LIST, CLIENT_SECRET, tenantGUID, NationalCloud.Global); +``` +#### 2.3.2 Public client authentication provider +##### a. Username password provider +```java +IAuthenticationProvider authenticationProvider = new UsernamePasswordProvider(CLIENT_ID, SCOPES_LIST, USERNAME, PASSWORD, NATIONAL_CLOUD, TENANT, CLIENT_SECRET); +``` +### 2.3 Get a HttpClient object and make a call + +```java +import com.microsoft.graph.httpcore.HttpClients; +import org.apache.http.HttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.protocol.HttpClientContext; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.util.EntityUtils; +``` + +```java +CloseableHttpClient httpclient = HttpClients.createDefault(authenticationProvider); +HttpGet httpget = new HttpGet("https://graph.microsoft.com/v1.0/me/"); +HttpClientContext localContext = HttpClientContext.create(); +try { + HttpResponse response = httpclient.execute(httpget, localContext); + String responseBody = EntityUtils.toString(response.getEntity()); + System.out.println(responseBody); +} catch (IOException e) { + e.printStackTrace(); +} +``` + +## 3. Make requests against the service + +After you have a GraphServiceClient that is authenticated, you can begin making calls against the service. The requests against the service look like our [REST API](https://developer.microsoft.com/en-us/graph/docs/concepts/overview). + +### 3.1 Get the user's drive + +To retrieve the user's drive: + +```java +CloseableHttpClient httpclient = HttpClients.createDefault(authenticationProvider); +HttpGet httpget = new HttpGet("https://graph.microsoft.com/v1.0/me/drive"); +HttpClientContext localContext = HttpClientContext.create(); +try { + HttpResponse response = httpclient.execute(httpget, localContext); + String responseBody = EntityUtils.toString(response.getEntity()); + System.out.println(responseBody); +} catch (IOException e) { + e.printStackTrace(); +} +``` + +## 4. Sample +### 4.1 Authorization code provider + +[Steps to get authorizationCode](https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow#request-an-authorization-code) +```java +IAuthenticationProvider authenticationProvider = new AuthorizationCodeProvider("6731de76-14a6-49ae-97bc-6eba6914391e", + Arrays.asList("https://graph.microsoft.com/user.read"), + authorizationCode, + "http://localhost/myapp/", + NationalCloud.Global, + "common", + "JqQX2PNo9bpM0uEihUPzyrh"); + +CloseableHttpClient httpclient = HttpClients.createDefault(authenticationProvider); +HttpGet httpget = new HttpGet("https://graph.microsoft.com/v1.0/me/messages"); +HttpClientContext localContext = HttpClientContext.create(); +try { + HttpResponse response = httpclient.execute(httpget, localContext); + String responseBody = EntityUtils.toString(response.getEntity()); + System.out.println(responseBody); +} catch (IOException e) { + e.printStackTrace(); +} +``` + +## 5. Documentation + +For more detailed documentation, see: + +[Usage of these providers](https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-v2-protocols). + +## 6. Issues + +For known issues, see [issues](https://github.com/microsoftgraph/msgraph-sdk-java-auth/issues). + +## 7. Contributions + +The Microsoft Graph SDK is open for contribution. To contribute to this project, see [Contributing](https://github.com/microsoftgraph/msgraph-sdk-java/blob/master/CONTRIBUTING.md). + +Thanks to everyone who has already devoted time to improving the library: + + + +| [
Nakul Sabharwal](https://developer.microsoft.com/graph)
[](#question-NakulSabharwal "Answering Questions") [](https://github.com/microsoftgraph/msgraph-sdk-java/commits?author=NakulSabharwal "Code") [](https://github.com/microsoftgraph/msgraph-sdk-java/wiki "Documentation") [](#review-NakulSabharwal "Reviewed Pull Requests") [](https://github.com/microsoftgraph/msgraph-sdk-java/commits?author=NakulSabharwal "Tests")| [
Deepak Agrawal](https://github.com/deepak2016)
+| :---: | :---: | + + +This project follows the [all-contributors](https://github.com/kentcdodds/all-contributors) specification. Contributions of any kind are welcome! + +## 8. Supported Java versions +The Microsoft Graph SDK for Java library is supported at runtime for Java 7+ and [Android API revision 15](http://source.android.com/source/build-numbers.html) and greater. + +## 9. License + +Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the [MIT license](LICENSE). + +## 10. Third-party notices + +[Third-party notices](THIRD%20PARTY%20NOTICES) From 50114110114ebccc4ca7bb3bb6ae95bb40559295 Mon Sep 17 00:00:00 2001 From: Nakul Sabharwal Date: Wed, 27 Feb 2019 12:35:09 +0530 Subject: [PATCH 09/10] edited readme for maven snapshot --- README.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/README.md b/README.md index a450b5f..26dde4e 100644 --- a/README.md +++ b/README.md @@ -35,6 +35,25 @@ Add the dependency in `dependencies` in pom.xml ``` +Add in `project` +``` + + + allow-snapshots + true + + + snapshots-repo + https://oss.sonatype.org/content/repositories/snapshots + false + true + + + + + +``` + ## 2. Getting started ### 2.1 Register your application From 28ecdb8974c0068a8f7e0ac6184a19766bbbd8b9 Mon Sep 17 00:00:00 2001 From: Nakul Sabharwal Date: Wed, 27 Feb 2019 13:19:24 +0530 Subject: [PATCH 10/10] removed version image in readme --- README.md | 3 --- 1 file changed, 3 deletions(-) diff --git a/README.md b/README.md index 26dde4e..c722b31 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,5 @@ # Microsoft Graph Auth SDK for Java -[ ![Download](https://api.bintray.com/packages/microsoftgraph/Maven/microsoft-graph/images/download.svg) ](https://bintray.com/microsoftgraph/Maven/microsoft-graph/_latestVersion) - - Get started with the Microsoft Graph SDK for Java by integrating the [Microsoft Graph API](https://graph.microsoft.io/en-us/getting-started) into your Java application! ## 1. Installation