javaandroidazuremicrosoft-graph-apionedrive

How to get authorizationCode in MS Graph API 6.12


I'm using microsoft-graph:6.12.0 in my Android Java App. I'm struggling for searching files on onedrive.

How can I get authorizsationCode for AuthorizationCodeCredentialBuilder.

final AuthorizationCodeCredential credential = new AuthorizationCodeCredentialBuilder()
                .clientId(CLIENT_ID).tenantId(TENANT_ID).clientSecret(CLIENT_SECRET_VALUE)
                .authorizationCode(authorizationCode).redirectUrl(REDIRECT_URL).build();

Thanks GGK


Solution

  • Initially, register one Entra ID application with redirect URI as below:

    enter image description here

    Make sure to grant Files.Read permission of Delegated type in this application:

    enter image description here

    To get authorization code, you need to run below request in browser that asks user to login like this:

    https://login.microsoftonline.com/tenantId/oauth2/v2.0/authorize? 
    client_id=appId
    &redirect_uri=https://jwt.ms
    &response_type=code  
    &response_mode=query  
    &scope=Files.Read
    &state=12345
    

    enter image description here

    After successful authentication, you will get authorization code in the address bar like this:

    enter image description here

    In my case, I used below sample java code to get user's drive by including authorizationCode value like this:

    Main.java:

    import com.azure.identity.AuthorizationCodeCredential;
    import com.azure.identity.AuthorizationCodeCredentialBuilder;
    import com.microsoft.graph.models.Drive;
    import com.microsoft.graph.serviceclient.GraphServiceClient;
    
    public class Main {
        public static void main(String[] args) {
            final String clientId = "appId";
            final String tenantId = "tenantId"; 
            final String clientSecret = "secret";
            final String authorizationCode = "code_value";
            final String redirectUrl = "https://jwt.ms";
            final String[] scopes = new String[] { "Files.Read" };
    
            final AuthorizationCodeCredential credential = new AuthorizationCodeCredentialBuilder()
                    .clientId(clientId).tenantId(tenantId).clientSecret(clientSecret)
                    .authorizationCode(authorizationCode).redirectUrl(redirectUrl).build();
    
            final GraphServiceClient graphClient = new GraphServiceClient(credential, scopes);
            Drive response = graphClient.me().drive().get();
            System.out.println("Drive ID: "+ response.getId());
        }
    }
    

    Response:

    enter image description here

    Reference:

    Choose a Microsoft Graph authentication provider - Microsoft Graph