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/README.md b/README.md index 44cd440..c722b31 100644 --- a/README.md +++ b/README.md @@ -1 +1,181 @@ -"# msgraph-sdk-java-auth" +# Microsoft Graph Auth SDK for Java + +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 + +``` + +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 + +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) diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..94968ee --- /dev/null +++ b/build.gradle @@ -0,0 +1,298 @@ +apply plugin: 'java-library' +apply plugin: 'java' +apply plugin: 'eclipse' +apply plugin: 'maven' +apply plugin: 'maven-publish' +apply plugin: 'signing' + +repositories { + 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 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 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..15fa3d9 --- /dev/null +++ b/src/main/java/com/microsoft/graph/auth/AuthConstants.java @@ -0,0 +1,13 @@ +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"; + } + 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/BaseAuthentication.java b/src/main/java/com/microsoft/graph/auth/BaseAuthentication.java new file mode 100644 index 0000000..1a12655 --- /dev/null +++ b/src/main/java/com/microsoft/graph/auth/BaseAuthentication.java @@ -0,0 +1,138 @@ +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 { + + 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, + 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() { + StringBuilder scopeString = new StringBuilder(); + for(String s : this.scopes) { + scopeString.append(s); + scopeString.append(" "); + } + return scopeString.toString(); + } + + 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 + 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); + } + + OAuthClientRequest request = token.buildBodyMessage(); + OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient()); + this.startTime = System.currentTimeMillis(); + 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; + } + +} 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..7c89978 --- /dev/null +++ b/src/main/java/com/microsoft/graph/auth/confidentialClient/AuthorizationCodeProvider.java @@ -0,0 +1,105 @@ +package com.microsoft.graph.auth.confidentialClient; + +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; +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{ + + /* + * 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, + String authorizationCode, + String redirectUri, + String clientSecret){ + 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, + 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 void authenticateRequest(HttpRequest request) { + String tokenParameter = AuthConstants.BEARER + getAccessTokenSilent(); + request.addHeader(AuthConstants.AUTHORIZATION_HEADER, tokenParameter); + } + + void getAccessToken(String authorizationCode) { + try { + OAuthClientRequest request = getTokenRequestMessage(authorizationCode); + getAccessTokenNewRequest(request); + } catch (Exception e) { + e.printStackTrace(); + } + } + + OAuthClientRequest getTokenRequestMessage(String authorizationCode) throws OAuthSystemException { + String tokenUrl = getAuthority() + AuthConstants.TOKEN_ENDPOINT; + TokenRequestBuilder token = OAuthClientRequest. + tokenLocation(tokenUrl) + .setClientId(getClientId()) + .setCode(authorizationCode) + .setRedirectURI(getRedirectUri()) + .setGrantType(GrantType.AUTHORIZATION_CODE) + .setScope(getScopesAsString()); + if(getClientSecret() != null) { + token.setClientSecret(getClientSecret()); + } + return token.buildBodyMessage(); + } + + void getAccessTokenNewRequest(OAuthClientRequest request) throws OAuthSystemException, OAuthProblemException { + OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient()); + 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 new file mode 100644 index 0000000..13d76b2 --- /dev/null +++ b/src/main/java/com/microsoft/graph/auth/confidentialClient/ClientCredentialProvider.java @@ -0,0 +1,91 @@ +package com.microsoft.graph.auth.confidentialClient; + +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; +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 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, + String tenant, + NationalCloud nationalCloud) { + super( scopes, + clientId, + GetAuthority(nationalCloud == null? NationalCloud.Global: nationalCloud, tenant), + null, + nationalCloud == null? NationalCloud.Global: nationalCloud, + tenant, + clientSecret); + } + + @Override + public void authenticateRequest(HttpRequest request) { + try { + 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(); + } + } + + /* + * 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(getClientId()) + .setGrantType(GrantType.CLIENT_CREDENTIALS) + .setScope(getScopesAsString()); + if(getClientSecret() != null) { + token.setClientSecret(getClientSecret()); + } + return token.buildBodyMessage(); + } + + /* + * 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()); + setStartTime(System.currentTimeMillis()); + setResponse(oAuthClient.accessToken(request)); + return getResponse().getAccessToken(); + } +} 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..6d148f4 --- /dev/null +++ b/src/main/java/com/microsoft/graph/auth/publicClient/UsernamePasswordProvider.java @@ -0,0 +1,87 @@ +package com.microsoft.graph.auth.publicClient; + +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; +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, null); + } + + public UsernamePasswordProvider( + String clientId, + List scopes, + String username, + String password, + NationalCloud nationalCloud, + 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, + clientSecret); + this.Username = username; + this.Password = password; + } + + @Override + public void authenticateRequest(HttpRequest request) { + String accessToken = getAccessTokenSilent(); + if(accessToken == null) { + try { + OAuthClientRequest authRequest = getTokenRequestMessage(); + accessToken = getAccessTokenNewRequest(authRequest); + }catch (Exception e) { + e.printStackTrace(); + } + } + request.addHeader("Authorization", AuthConstants.BEARER + accessToken); + } + + OAuthClientRequest getTokenRequestMessage() throws OAuthSystemException { + String tokenUrl = getAuthority() + AuthConstants.TOKEN_ENDPOINT; + TokenRequestBuilder token = OAuthClientRequest. + tokenLocation(tokenUrl) + .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; + } + + String getAccessTokenNewRequest(OAuthClientRequest request) throws OAuthSystemException, OAuthProblemException { + OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient()); + setStartTime(System.currentTimeMillis()); + setResponse(oAuthClient.accessToken(request)); + return getResponse().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..a59a493 --- /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..0484646 --- /dev/null +++ b/src/test/java/com/microsoft/graph/auth/confidentialClient/AuthorizationCodeProviderTests.java @@ -0,0 +1,82 @@ +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.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; +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)); + 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); + 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); + 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 new file mode 100644 index 0000000..918f024 --- /dev/null +++ b/src/test/java/com/microsoft/graph/auth/confidentialClient/ClientCredentialProviderTests.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.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 { + 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; + public static String tenantGUID = "TENANT_GUID"; + + @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); + } + + @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 new file mode 100644 index 0000000..63a94a6 --- /dev/null +++ b/src/test/java/com/microsoft/graph/auth/publicClient/UsernamePasswordProviderTests.java @@ -0,0 +1,98 @@ +package com.microsoft.graph.auth.publicClient; + +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; +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; +import com.microsoft.graph.httpcore.HttpClients; +import com.microsoft.graph.httpcore.IAuthenticationProvider; + + +@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"; + private NationalCloud NATIONAL_CLOUD = NationalCloud.Global; + private String CLIENT_SECRET = "CLIENT_SECRET"; + + @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"); + 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 + @Test + public void getAccessTokenNewRequestTest() throws OAuthSystemException, OAuthProblemException { + UsernamePasswordProvider usernamePasswordProvider = new UsernamePasswordProvider(CLIENT_ID, SCOPES, USERNAME, PASSWORD); + String actualAccessToken = usernamePasswordProvider.getAccessTokenNewRequest(usernamePasswordProvider.getTokenRequestMessage()); + 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(); + } + } + +}