GithubHelp home page GithubHelp logo

isabella232 / ms-identity-java-devicecodeflow Goto Github PK

View Code? Open in Web Editor NEW

This project forked from azure-samples/ms-identity-java-devicecodeflow

0.0 0.0 0.0 91 KB

A Java sample of a browserless app using the device code flow to get tokens to call Microsoft Graph API

License: MIT License

PowerShell 69.49% Java 30.51%

ms-identity-java-devicecodeflow's Introduction

services platforms author level client service endpoint page_type languages products description
active-directory
java
ramya25
200
java console app
Microsoft Graph
Microsoft identity platform
sample
java
azure
azure-active-directory
office-ms-graph
This sample demonstrates calling the Microsoft Graph from a Java console application without a browser for interaction

Invoking an API protected by Azure AD from a device without a browser for interaction

About this sample

Overview

This sample shows how to use the OAuth 2.0 device code flowto sign in users to input-constrained devices such as a smart TV, IoT device, or printer. It leverages MSAL for Java (MSAL4J) from an app that does not have the capability of offering an interactive authentication experience. It enables these apps to:

To emulate an app on a device that is not capable of showing a UX, the sample is packaged as a Java console application. The application signs-in users with Azure Active Directory (Azure AD), using the Microsoft Authentication Library for Java (MSAL4J) to obtain a JWT access token through the OAuth 2.0 protocol. The access token is then used to call the Microsoft Graph API to obtain information about the user who signed-in. The sample is structured as such so that you can call your own API.

Topology

Scenario

The application obtains tokens through a two step process especially designed for devices and operating systems that cannot display any UX. Examples of such applications are applications running on IoT, or Command-Line tools (CLI). The idea is that:

  1. Whenever a user is required to authenticate, the command-line app provides a code and asks the user to use another device (such as an internet-connected smartphone) to navigate to https://microsoft.com/devicelogin, where the user will be prompted to enter the code provided earlier. Once the user enters the code, the web page will lead the user through a normal authentication experience, including presenting any consent prompts and taking the user through a multi-factor authentication experience if necessary.

  2. Upon successful authentication, the command-line app will receive the required tokens through a back channel and will use it to perform the web API calls it needs. In this case, the sample retrieves a list of users in the signed-in user's tenant from Microsoft Graph and lists it in the window.

How to run this sample

To run this sample, you'll need:

Step 1: Clone or download this repository

From your shell or command line:

git clone https://github.com/Azure-Samples/ms-identity-java-devicecodeflow.git

or download and extract the repository .zip file.

Step 2: Register the sample application with your Azure Active Directory tenant

To register the project, you can:

If you want to use this automation, read the instructions in App Creation Scripts Please note that the configuration of your code (Step 3) still needs to be done manually.

Follow the steps below to manually walk through the steps to register and configure the applications.

Choose the Azure AD tenant where you want to create your applications

As a first step you'll need to:

  1. Sign in to the Azure portal using either a work or school account or a personal Microsoft account.
  2. If your account is present in more than one Azure AD tenant, select your profile at the top right corner in the menu on top of the page, and then switch directory. Change your portal session to the desired Azure AD tenant.
  3. In the portal menu, select the Azure Active Directory service, and then select App registrations.

Register the client app (active-directory-java-deviceprofile)

  1. Navigate to the Microsoft identity platform for developers App registrations page.
  2. Click New registration on top.
  3. In the Register an application page that appears, enter your application's registration information:
    • In the Name section, enter a meaningful application name that will be displayed to users of the app, for example active-directory-java-deviceprofile.
    • Change Supported account types to Accounts in any organizational directory.
  4. Click on the Register button at the bottom to create the application.
  5. In the app's registration screen, find the Application (client) ID value and record it for later. You'll need it to configure the configuration file(s) later in your code.
  6. In the app's registration screen, click on the Manifest blade, and:
    • In the manifest editor, set the allowPublicClient property to true
    • Click on Save in the bar above the manifest editor.
  7. In the app's registration screen, click on the Authentication blade in the left and:
  8. In the app's registration screen, click on the API permissions blade in the left to open the page where we add access to the Apis that your application needs. You will need both User.Read and User.ReadBasic.All permissions for this sample.
    • Click the Add a permission button, and select Microsoft Graph
    • Choose Delegated permissions, and select User.Read and User.ReadBasic.All in the list. Use the search box if necessary.
    • Click on the Add permissions button at the bottom to save your changes.
Configure the client app (active-directory-java-deviceprofile) to use your app registration

Open the project in your IDE to configure the code.

In the steps below, "ClientID" is the same as "Application ID" or "AppId".

  1. Open the src\main\java\DeviceCodeFlow class
  2. Find the variable CLIENT_ID and replace the existing value with the application ID (clientId) that you recorded in earlier steps.

Step 4: Run the sample

From your shell or command line:

  • $ mvn clean compile assembly:single

This will generate a ms-identity-java-devicecodeflow-1.0.jar file in your /targets directory. Run this using your Java executable like below:

  • $ java -jar ms-identity-java-devicecodeflow-1.0.jar

Or run it from an IDE.

Application will start and it will display similar as below:

To sign in, use a web browser to open the page https://microsoft.com/devicelogin and enter the code ABCDEF123 to authenticate.

Now you can navigate to the above URL and it will then prompt to enter the code which is displayed as above. After successful authentication of the user, the webpage displays a window as below:

You have signed in to the active-directory-java-deviceprofile on your device. You may now close this window.

Now you can come back your application and you can see the users list and basic information of the users in the tenant.

About the code

  1. The relevant code for this sample is in the DeviceCodeFlow.java file.

The code below calls the acquireToken method of the PublicClientApplication class to which you pass a callback that will display information to the user about where they should navigate to, and which code to enter to initiate a sign-in.

PublicClientApplication app = PublicClientApplication.builder(PUBLIC_CLIENT_ID)
                .authority(AUTHORITY_COMMON)
                .build();

        Consumer<DeviceCode> deviceCodeConsumer = (DeviceCode deviceCode) -> {
            System.out.println(deviceCode.message());
        };

        CompletableFuture<IAuthenticationResult> future = app.acquireToken(
                DeviceCodeFlowParameters.builder(
                        Collections.singleton(GRAPH_SCOPE),
                        deviceCodeConsumer)
                        .build());

Community Help and Support

Use Stack Overflow to get support from the community. Ask your questions on Stack Overflow first and browse existing issues to see if someone has asked your question before. Make sure that your questions or comments are tagged with [azure-active-directory msal java].

If you find a bug in the sample, please raise the issue on GitHub Issues.

To provide a recommendation, visit the following User Voice page.

Contributing

If you'd like to contribute to this sample, see CONTRIBUTING.MD.

This project has adopted the Microsoft Open Source Code of Conduct. For more information, see the Code of Conduct FAQ or contact [email protected] with any additional questions or comments.

More information

For more information, see:

For more information about the Microsoft identity platform, see:

For more information about how OAuth 2.0 protocols work in this scenario and other scenarios, see Authentication Scenarios for Azure AD

ms-identity-java-devicecodeflow's People

Contributors

avery-dunn avatar microsoft-github-operations[bot] avatar microsoftopensource avatar sangonzal avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.