Search in sources :

Example 1 with UserNamePasswordParameters

use of com.microsoft.aad.msal4j.UserNamePasswordParameters in project microsoft-authentication-library-for-java by AzureAD.

the class UsernamePasswordFlow method acquireTokenUsernamePassword.

private static IAuthenticationResult acquireTokenUsernamePassword(PublicClientApplication pca, Set<String> scope, IAccount account, String username, String password) throws Exception {
    IAuthenticationResult result;
    try {
        SilentParameters silentParameters = SilentParameters.builder(scope).account(account).build();
        // Try to acquire token silently. This will fail on the first acquireTokenUsernamePassword() call
        // because the token cache does not have any data for the user you are trying to acquire a token for
        result = pca.acquireTokenSilently(silentParameters).join();
        System.out.println("==acquireTokenSilently call succeeded");
    } catch (Exception ex) {
        if (ex.getCause() instanceof MsalException) {
            System.out.println("==acquireTokenSilently call failed: " + ex.getCause());
            UserNamePasswordParameters parameters = UserNamePasswordParameters.builder(scope, username, password.toCharArray()).build();
            // Try to acquire a token via username/password. If successful, you should see
            // the token and account information printed out to console
            result = pca.acquireToken(parameters).join();
            System.out.println("==username/password flow succeeded");
        } else {
            // Handle other exceptions accordingly
            throw ex;
        }
    }
    return result;
}
Also used : SilentParameters(com.microsoft.aad.msal4j.SilentParameters) MsalException(com.microsoft.aad.msal4j.MsalException) IAuthenticationResult(com.microsoft.aad.msal4j.IAuthenticationResult) UserNamePasswordParameters(com.microsoft.aad.msal4j.UserNamePasswordParameters) IOException(java.io.IOException) MsalException(com.microsoft.aad.msal4j.MsalException)

Aggregations

IAuthenticationResult (com.microsoft.aad.msal4j.IAuthenticationResult)1 MsalException (com.microsoft.aad.msal4j.MsalException)1 SilentParameters (com.microsoft.aad.msal4j.SilentParameters)1 UserNamePasswordParameters (com.microsoft.aad.msal4j.UserNamePasswordParameters)1 IOException (java.io.IOException)1