Code Monkey home page Code Monkey logo

azure-activedirectory-library-for-java's Introduction


This library, ADAL for Java, will no longer receive new feature improvements. Instead, use the new MSAL4J.

  • If you are starting a new project, you can get started with the MSAL4J docs for details about the scenarios, usage, and relevant concepts.
  • If your application is using the previous ADAL for Java library, you can follow this migration guide to update to MSAL4J.
  • Existing applications relying on ADAL for Java will continue to work.

Microsoft Azure Active Directory Authentication Library (ADAL) for Java

master branch dev branch Reference Docs
Build Status Build Status Javadocs
Getting Started Docs Samples Support Feedback

The ADAL for Java library enables Java applications to authenticate with Azure AD and get tokens to access Azure AD protected web resources.

Update to MSAL4J now!

MSAL4J is the new authentication library to be used with the Microsoft identity platform.

Building on top of ADAL, MSAL works with both the Open ID Connect certified Azure AD V2 endpoint and the new social identity solution from Microsoft, Azure AD B2C.

ADAL4J is in maintenance mode and no new features will be added going forward except for security fixes. All our ongoing efforts will be focused on improving MSAL4J.

Installation and usage

You can find the steps for installation and basic usage documented in the ADAL4J Basics Wiki.

Versions

Current version - 1.6.7

Minimum recommended version - 1.6.7

From version 1.3.0 support for handling Conditional Access claims challenge was added. You can read about CA here and refer this sample to handle it.

You can find the changes for each version in the change log.

Contribution

All code is licensed under the MIT License and we triage actively on GitHub. We encourage and welcome contributions to the library. Please read the contributing guide before starting.

Build and Run

Refer this page for information on building the project and running tests.

Samples and Documentation

Refer these code samples using ADAL4J in some basic scenarios.

We also provide a full suite of sample applications and documentation to help you get started with learning the Azure Identity system. This includes tutorials for native clients such as Windows, Windows Phone, iOS, macOS, Android, and Linux. We also provide full walkthroughs for authentication flows such as OAuth2, OpenID Connect, Graph API, and other awesome features.

Community Help and Support

We leverage Stack Overflow to work with the community on supporting Azure Active Directory and its SDKs, including this one! We highly recommend you ask your questions on Stack Overflow (we're all on there!) Also browser existing issues to see if someone has had your question before.

We recommend you use the "adal" tag so we can see it! Here is the latest Q&A on Stack Overflow for ADAL: http://stackoverflow.com/questions/tagged/adal

Submit Feedback

We'd like your thoughts on this library. Please complete this short survey.

Security Reporting

If you find a security issue with our libraries or services please report it to [email protected] with as much detail as possible. Your submission may be eligible for a bounty through the Microsoft Bounty program. Please do not post security issues to GitHub Issues or any other public site. We will contact you shortly upon receiving the information. We encourage you to get notifications of when security incidents occur by visiting this page and subscribing to Security Advisory Alerts.

We Value and Adhere to the Microsoft Open Source Code of Conduct

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.

azure-activedirectory-library-for-java's People

Contributors

aiwangmicrosoft avatar aj-michael avatar atmmokyu avatar avery-dunn avatar brandwe avatar brentschmaltz avatar bryant1410 avatar conniey avatar danieldobalian avatar dependabot[bot] avatar jeffpang avatar jianghaolu avatar magiksquirrel avatar marcinzi avatar navyasric avatar nwoolls avatar olgapop avatar omercs avatar psignoret avatar rohitnarula7176 avatar sangonzal avatar shannoncantech avatar siddhijain avatar slyons avatar somkape avatar tkatochin avatar v-nisidh avatar vartlok avatar waffle-iron avatar weijjia avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

azure-activedirectory-library-for-java's Issues

Option to specify an 'SSLSocketFactory' in Azure clients

Currently there is no way to configure Azure clients with a custom SSLSocketFactory. This is required for systems which communicate with different other servers (in addition to Azure) over HTTPS. There is a need to use different SSL Contexts (with different security configurations) to create SSL Socket factories to talk to these, since the validation logic is different for certain types of servers. Hence, we cannot set the default SSL context of the system to the one required by Azure as it will be a system wide change affecting the connections to other servers.

The rationale behind this change is to be able to create isolated SSL configurations for connecting to different servers, of which one is Azure.

IllegalArgumentException: โ€˜authorityโ€™ Uri should have at least one segment in the path ( issue with translation of .NET sample )

Hi,

Translating a sample I received in .NET and trying to use the https://github.com/MSOpenTech/azure-activedirectory-library-for-java

I face a java.lang.IllegalArgumentException: โ€˜authorityโ€™ Uri should have at least one segment in the path (i.e. https:// ??? //โ€ฆ)

But the URI I received is only an host, and if I put a prefix like โ€œhttps://login.windows.net/myHostโ€ I receive a response

{โ€œerrorโ€:โ€invalid_requestโ€,โ€error_descriptionโ€:โ€AADSTS90011: Invalid request. Client application identifier value โ€˜hereIsMyServiceIDโ€™ must be a valid Guid.\r\nTrace ID: c02b731d-4823-4394-b33e-d4884faf70a6\r\nCorrelation ID: 70fbda75-70ea-415e-8ddc-dd7be649d917\r\nTimestamp: 2014-07-09 19:51:06Zโ€}

Please advice on how to use the java
AuthenticationContext authContext = new AuthenticationContext(โ€ ??? โ€œ, false, exec);

versus the .NET version:

AuthenticationContext authContext = new AuthenticationContext(โ€ ??? โ€œ);

Thanks

Tests failing because of expired client assertions

Failed tests: testAcquireToken_KeyCred(com.microsoft.aad.adal4j.AuthenticationContextTest): com.microsoft.aad.adal4j.AuthenticationException: {"error_description":"AADSTS70002: Error validating credentials. AADSTS50012: Client assertion is not within its valid time range.\r\nTrace ID: 80ad7758-a570-42f0-97b7-ae2dded006c7\r\nCorrelation ID: 986a6c2c-a596-4189-b5b5-3a1b1a9a17e2\r\nTimestamp: 2015-07-30 17:18:47Z","error":"invalid_client"}
testAcquireToken_RefreshToken(com.microsoft.aad.adal4j.AuthenticationContextTest): com.microsoft.aad.adal4j.AuthenticationException: {"error_description":"AADSTS70002: Error validating credentials. AADSTS50012: Client assertion is not within its valid time range.\r\nTrace ID: b954337f-bc46-421f-b25e-7b4c64d52ac3\r\nCorrelation ID: 59cab3ef-c94a-429c-b216-0c384e766242\r\nTimestamp: 2015-07-30 17:18:48Z","error":"invalid_client"}

It looks like we hard coded some OAuth responses with expirations, and they finally expired. I'll try and put out a fix later today.

ADAL4j proxy issue for java

Hi there,

I am trying to connect azure using adal4j1.1 library for java.But i have to connect through the proxy.Following is the snippet of code

String url = "https://login.microsoftonline.com/tenant_id/oauth2/authorize";
authContext = new AuthenticationContext(url,false,
service);
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxyhostname", 443));
authContext.setProxy(proxy);
ClientCredential clientCred = new ClientCredential(XXXX, xxxx);
Future future = authContext.acquireToken(
clientCred,
null);
authResult = future.get();
Also i have tried with

        System.setProperty("http.proxyPort", "80");
        System.setProperty("http.proxyUser", "xxxx");
        System.setProperty("http.proxyPassword", "xxxx");
        System.setProperty("http.proxyHost", "xxxxxxx");

And all the time i am getting this following error

the error is.....java.net.ConnectException: Connection timed out: connect
java.util.concurrent.ExecutionException: java.net.ConnectException: Connection timed out: connect
at java.util.concurrent.FutureTask.report(FutureTask.java:122)
at java.util.concurrent.FutureTask.get(FutureTask.java:188)
at com.toyota.eap.auth.Test.main(Test.java:76)
Caused by: java.net.ConnectException: Connection timed out: connect

Note: This error is only if we have proxy within the office. From outside the office If I ran thisprogramme there is no issue.

Any Thought on this.

Thanks

Mex parsing needs to support WS-Trust 2005

It turns out that the default configuration for ADFS doesn't support WS-Trust 1.3 which is the latest version. Instead, it supports an earlier draft version, WS-Trust 2005. We need to look for 1.3 and if it is not present in the MEX, look for WS-Trust 2005 and use that instead.

Create real documentation (generate the javadocs) for ADAL-java

On the main project page -- "We provide a full suite of sample applications and documentation on GitHub to help you get started with learning the Azure Identity system. "

There are no javadocs in the the link in the above text. Further, the examples included are basically the same as those in the azure-activedirectory-library-for-java repository.

acquireToken overload with PromptBehavior and not UserIdentity raises nullpointerexception

When you make the call to this overload:
public void acquireToken(Activity activity, String[] scope, String[] additionalScope, String clientId, String redirectUri, PromptBehavior prompt, AuthenticationCallback callback)

The AuthorizationRequest object is passed a null UserIdentity and throws a NullPointerException.

My assumption is that if the acquireToken overload does not take a UserIdentity, then a null UserIdentity should be accounted for and allowed.

Missing API call for acquireTokenUsingRefreshToken(string clientId, string resource) from Java ADAL

We have a Java Web Service and we need to protect it via AAD.

We are trying to have Web API receive an access token from a native app, and then the API would be executing On-Behalf-Of flow to get access tokens for another resource. https://docs.microsoft.com/en-us/azure/active-directory/active-directory-authentication-scenarios#daemon-or-server-application-to-web-api

However since we don't have an API call for acquireTokenUsingRefreshToken(string clientId, string resource), we aren't able to implement this scenario and make use of the Refresh Token.

Currently, there is no way in ADAL Java to use refresh token and get a new access token. Please look at code in AuthenticationContext.java.

Please get this functionality at the earliest.

Fails to create a AsymmetricKeyCredential from a windows store certificate

I am trying to use the following method "public static AsymmetricKeyCredential create(final String clientId, final PrivateKey key, final X509Certificate publicCertificate)" from a pfx certificate I installed manually in my Windows Store certificate.
For that purpose, I am getting the certificate using the "SunMSCAPI" and the java.security.KeyStore package. However, I end up with the following exception thrown within the AsymmetricKeyCredential constructor:

sun.security.mscapi.RSAPrivateKey`
cannot be cast to java.security.interfaces.RSAPrivateKey
java.lang.ClassCastException: sun.security.mscapi.RSAPrivateKey cannot be cast to java.security.interfaces.RSAPrivateKey
at com.microsoft.aad.adal4j.AsymmetricKeyCredential.(AsymmetricKeyCredential.java:74)
at com.microsoft.aad.adal4j.AsymmetricKeyCredential.create(AsymmetricKeyCredential.java:173)

Is there any workaround this ?

Authentication fails if password contains ampersand

AuthenticationContext.acquireToken(String resource, String clientId, String username, String password, AuthenticationCallback callback) fails always with a 400 server response if the password contains some characters that would need to be XML escaped, e.g. '&'.

Apparently the password (and maybe the username?) are put to the SOAP body un-escaped and thus when the password contains '&' the XML is not well-formed, and the server responds with a 400.

The fix should be, obviously, to correctly XML escape text so that the SOAP body is well-formed XML.

Problem with on-behalf-of scenario

I am trying to use a JWT token that I have already obtained from an authenticated user (and passed to back-end from front-end) to use in the on-behalf-of scenario as follows:

private static AuthenticationResult getAccessTokenOnBehalfOfUser(String resourceId, String tenant, String clientId, String clientSecret, String userJwtToken) throws MalformedURLException, ServiceUnavailableException, ExecutionException, InterruptedException {

        ClientCredential clientCredential = new ClientCredential(clientId, clientSecret);
        ClientAssertion clientAssertion = new ClientAssertion(userJwtToken);

        AuthenticationContext context = null;
        AuthenticationResult result = null;
        ExecutorService service = null;
        try {
            service = Executors.newFixedThreadPool(1);
            context = new AuthenticationContext("https://login.microsoftonline.com/" + tenant, true, service);

            Future<AuthenticationResult> future = context.acquireToken(
                    resourceId, clientAssertion, clientCredential,
                    null);

            result = future.get();
        } finally {
            service.shutdown();
        }

        if (result == null) {
            throw new ServiceUnavailableException("authentication result was null");
        }
        return result;
    }

But I keep getting an error:

{"error_description":"AADSTS70002: Error validating credentials. AADSTS50013: Assertion audience claim does not match the required value.\r\nTrace ID: 0de7c901-7f0b-4c8d-8e0c-16c94dbdd35f\r\nCorrelation ID: 7cbdc1ec-2ba8-4116-939f-575680d29934\r\nTimestamp: 2015-10-20 13:07:20Z","error":"invalid_grant"}

As I can see in the code it is using:
requested_token_use=on_behalf_of
grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer

so at first look it should work.

I was trying to simulate this also using CURL:

curl -i -H "Content-Type: application/x-www-form-urlencoded;charset=UTF-8" --request POST https://login.microsoftonline.com/miappdev.org/oauth2/token -d 'client_id=CLIENT_ID&client_secret=CLIENT_SECRET&resource=RESOURCE&requested_token_use=on_behalf_of&scope=user_impersonation&grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&assertion=JWT_TOKEN_OF_SIGNED_IN_USER'

but the result is exactly the same.

Should I be able to use some signed-in user's JWT token to access i.e. graph.windows.net on behalf of him? Or is there some misunderstanding?

not supported for this API version

We are getting this error when trying to authenticate with a valid user.

Exception in thread "main" java.util.concurrent.ExecutionException: com.microsoft.aad.adal4j.AuthenticationException: {"error_description":"AADSTS70001: Application 'a2333e4-1eaf-4b66-rr04-ed825e0dxxx' is not supported for this API version.\r\nTrace ID: e37d4bda-3db7-4dd1-b690-5d127b1a5ss5\r\nCorrelation ID: 4de96623-6669-4a17-bd44-3c1ecc722ff1\r\nTimestamp: 2016-06-28 20:10:17Z","error":"unauthorized_client"}
at java.util.concurrent.FutureTask.report(FutureTask.java:122)
at java.util.concurrent.FutureTask.get(FutureTask.java:192)

ClassCastException when I build

I'm getting this error when I build, any idea why?

2218 [pool-1-thread-1] ERROR com.microsoft.aad.adal4j.AuthenticationContext - [Correlation ID: ac256c7c-b9ae-41ff-b39c-f0746a2275f7] Request to acquire token failed.
java.lang.ClassCastException: sun.net.www.protocol.https.HttpsURLConnectionImpl cannot be cast to javax.net.ssl.HttpsURLConnection
at com.microsoft.aad.adal4j.HttpHelper.openConnection(HttpHelper.java:102)
at com.microsoft.aad.adal4j.HttpHelper.openConnection(HttpHelper.java:115)
at com.microsoft.aad.adal4j.HttpHelper.executeHttpGet(HttpHelper.java:49)
at com.microsoft.aad.adal4j.AuthenticationAuthority.doDynamicInstanceDiscovery(AuthenticationAuthority.java:146)
at com.microsoft.aad.adal4j.AuthenticationAuthority.doInstanceDiscovery(AuthenticationAuthority.java:130)
at com.microsoft.aad.adal4j.AuthenticationContext.acquireTokenCommon(AuthenticationContext.java:813)
at com.microsoft.aad.adal4j.AuthenticationContext.access$1(AuthenticationContext.java:806)
at com.microsoft.aad.adal4j.AuthenticationContext$1.call(AuthenticationContext.java:175)
at com.microsoft.aad.adal4j.AuthenticationContext$1.call(AuthenticationContext.java:1)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Warning: Could not get charToByteConverterClass!
638 [main] INFO com.microsoft.aad.adal4j.WSTrustResponse - Found token of type: urn:oasis:names:tc:SAML:1.0:assertion

aadl4j throws an NPE when encountering a 404 on an invalid URL.

Using sample code below and the following URL, the stack trace included results. Note the double slash in the URL. NPEs should be caught.

URL -- https://login.microsoftonline.com//618c8322-bd3e-4c3a-b1de-be5fcee2efe8/oauth2/authorize

conn.getResponseCode() is 404.

Call to conn.getErrorStream doesn't check for null.

Stack trace (using most recent git repo):

java.util.concurrent.ExecutionException: java.lang.NullPointerException
at java.util.concurrent.FutureTask.report(FutureTask.java:122)
at java.util.concurrent.FutureTask.get(FutureTask.java:192)
at com.innerdot.azure.rest.example.ApplicationAuthExample.main(ApplicationAuthExample.java:79)
Caused by: java.lang.NullPointerException
at java.io.Reader.(Reader.java:78)
at java.io.InputStreamReader.(InputStreamReader.java:72)
at com.microsoft.aad.adal4j.AdalOAuthRequest.processAndReadResponse(AdalOAuthRequest.java:143)
at com.microsoft.aad.adal4j.AdalOAuthRequest.send(AdalOAuthRequest.java:73)
at com.microsoft.aad.adal4j.AdalTokenRequest.executeOAuthRequestAndProcessResponse(AdalTokenRequest.java:72)
at com.microsoft.aad.adal4j.AuthenticationContext.acquireTokenCommon(AuthenticationContext.java:831)
at com.microsoft.aad.adal4j.AuthenticationContext.access$100(AuthenticationContext.java:63)
at com.microsoft.aad.adal4j.AuthenticationContext$1.call(AuthenticationContext.java:130)
at com.microsoft.aad.adal4j.AuthenticationContext$1.call(AuthenticationContext.java:119)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)

Jave code snippet:

try {
        service = Executors.newFixedThreadPool(1);
    String url = AUTHORIZATION_ENDPOINT + "/" + tenantId + "/oauth2/authorize";
    System.out.println("url -- " + url);
        context = new AuthenticationContext(url, 
                                            false, 
                                            service);
        Future<AuthenticationResult> future = null;
        future = context.acquireToken(ARM_ENDPOINT, clientId,
                                      username, credential, null);
        result = future.get();
    } catch (Exception ex) {
        System.out.println("Exception: " + ex.toString());
        System.exit(1);
    } finally {
        service.shutdown();
    }

certificate based authentication error : invalid JWT token

I am using adal4j v1.1.2 to get token based on client certificate.

Snippet referred: Why does AcquireToken with ClientCredential fail with invalid_client (ACS50012)?

String AAD_HOST_NAME = "login.windows.net";
String AAD_TENANT_ID = "XXX";
String AAD_TENANT_ENDPOINT = "https://" + AAD_HOST_NAME + "/" + AAD_TENANT_ID + "/";
String AAD_CLIENT_ID = "XXX";
String AAD_RESOURCE_ID = "https://vault.azure.net";
String AAD_CERTIFICATE_PATH = "/XXX.pfx";
String AAD_CERTIFICATE_PASSWORD = "XXX";

ExecutorService service = ExecutorServiceHelper.createThreadPool(1, "azureHSMClientExecutorService-");

KeyStore keystore = KeyStore.getInstance("PKCS12", "SunJSSE");
keystore.load(new FileInputStream(AAD_CERTIFICATE_PATH),AAD_CERTIFICATE_PASSWORD.toCharArray());
String alias = keystore.aliases().nextElement();
PrivateKey key = (PrivateKey) keystore.getKey(alias, AAD_CERTIFICATE_PASSWORD.toCharArray());
X509Certificate cert = (X509Certificate) keystore.getCertificate(alias);
AsymmetricKeyCredential asymmetricKeyCredential = AsymmetricKeyCredential.create(AAD_CLIENT_ID,key, cert);
AuthenticationContext ctx = new AuthenticationContext(AAD_TENANT_ENDPOINT, false, service);
Future result = ctx.acquireToken(AAD_RESOURCE_ID, asymmetricKeyCredential, null);
AuthenticationResult authenticationResult = result.get();
String token = authenticationResult.getAccessToken();
This results in following auth exception

AuthenticationException: com.microsoft.aad.adal4j.AuthenticationException: {"error":"invalid_client","error_description":"AADSTS70002: Error validating credentials. AADSTS50027: Invalid JWT token. No certificate thumbprint specified in token header.\r\nTrace ID: 9719e621-d8ef-4194-93cd-a78103d5df6b\r\nCorrelation ID: f0300795-fb99-44b2-bd95-8df3975290be\r\nTimestamp: 2016-08-29 13:51:26Z"}

I'm not sure how to pass thumbprint while calling acquireToken. Is anything missing here?

Regex update for AuthenticationParameters

It will be similar to node.js and ios ADAL
This is related to the Authentication Challenge. ADAL receives 401 challenge and gets authority information from the header using regex.

AuthenticationResult.expiresOn is actually expiresIn

Tough to say if this is truly a bug but I'd like an idea so I can either work with the current implementation of submit a PR.

The value of expiresOn is actually the number of seconds the token expiresIn. In the .NET version of the Azure AD auth code, expiresOn is the DateTime that the token will expire, calculated using the expires_in value from the response.

acquire token with policy identifier

I try to push some data to a cloud using a adal4j token but I didn't get acces because of the policy identifier.
An existing app uses an old adal Android library. It uses a policy identifier String using the adal

/**
     * acquire Token will start interactive flow if needed. It checks the cache
     * to return existing result if not expired. It tries to use refresh token
     * if available. If it fails to get token with refresh token, behavior will
     * depend on options. If promptbehavior is AUTO, it will remove this refresh
     * token from cache and fall back on the UI if activitycontext is not null.
     * Default is AUTO.
     * 
     * @param activity Calling activity
     * @param scope required scope identifier.
     * @param additionalScope optional scope identifier.
     * @param policy optional policy identifier.
     * @param clientId required client identifier.
     * @param redirectUri Optional. It will use packagename and provided suffix
     *            for this.
     * @param user UserIdentifier to specify a user.
     * @param prompt Optional. added as query parameter to authorization url
     * @param extraQueryParameters Optional. added to authorization url
     * @param callback required {@link AuthenticationCallback} object for async
     *            call.
     */
    public void acquireToken(Activity activity, String[] scope, String[] additionalScope, String policy,
            String clientId, String redirectUri, UserIdentifier user, PromptBehavior prompt,
            String extraQueryParameters, AuthenticationCallback<AuthenticationResult> callback) {

        redirectUri = checkInputParameters(scope, additionalScope, clientId, redirectUri, prompt,
                callback);

        final AuthenticationRequest request = new AuthenticationRequest(mAuthority, scope,
                clientId, redirectUri, user, prompt, extraQueryParameters,
                getRequestCorrelationId());
        request.setAdditionalScope(additionalScope);
        request.setPolicy(policy);
        acquireTokenLocal(wrapActivity(activity), false, request, callback);
    }

This method isn't supported with the same params in adal4j. So how can I set a policy to the token acquisition with the adal4j library?

I hope someone can help me.

1.0.1 release

1.0.1 seems to be 'released', but is nowhere to be found. May I suggest:

  • Putting 1.0.1 on Maven Central or Bintray
  • Tagging the 1.0.0 and 1.0.1 release versions in git
  • Closing any issues that have been fixed
  • Reworking the version numbering to a -RELEASE and -SNAPSHOT scheme, so everyone can see if something is a snapshot or a release
  • Using the maven-deploy plugin to make life easier for everyone

Maven GroupId does not match package names

Hi,

I see from this commit: e083290 that group id was changed to com.microsoft.azure but the package names were left unchanged. This is uncommon and makes it hard to discover.

Also, it collides with the package names in ADAL for android. This is making it really hard for a cross-platform library (run on both JDK and Android) to tell which library is loaded.

Interactive Authentication for AAD native applications

How does one go about presenting a consent dialog top the user in native interactive applications ? When using the .NET SDK, a browser window is automatically popped up asking for consent from the user of a new application. How do you get that to work when using ADAL4J ? I see that there is an issue and some commits here #73, but not sure what the status is ?

Until the Prompt Behavior is ported into ADAL4J, what options do I have to get my user to provide consent to the application ?

/Dev

build failed with "illegal character: \65279" for AuthenticationContext.java

Build using mvn on windows fails with error: "illegal character: \65279" for the file /src/main/java/com/microsoft/aad/adal4j/AuthenticationContext.java

Temporary Solution:
Open the file in Notepad++ and select Encoding -> Convert to UTF-8 without BOM.

Reference:
http://stackoverflow.com/questions/1726174/how-to-compile-a-java-source-file-which-is-encoded-as-utf-8
http://albert-myptc.blogspot.in/2011/08/illegal-character-65279-when-using-file.html

AADSTS50034

I am gettign this exception when trying to get the token from the application created in active directory.
java.util.concurrent.ExecutionException: com.microsoft.aad.adal4j.AuthenticationException: {"error":"invalid_grant","error_description":"AADSTS50034: To sign into this application the account must be added to the***** directory.\r\nTrace ID: 83910367-b165-4e60-b0a8-057dd760c910\r\nCorrelation ID: 2d045d7b-1ed9-48b1-8624-45e7334976a0\r\nTimestamp: 2015-07-02 11:41:29Z"}

But with the same credentials the C# code is giving me the token. Only difference i see is in parameters to get the token, the C# method accepts the url too as a parameter and not the user name and password, where as java code accepts user name and password not url. Please help

AuthenticationContext fails if password contains special character ("")

AuthenticationContext.acquireToken(String resource, String clientId, String username, String password, AuthenticationCallback callback) fails always and gives Server returned HTTP response code: 500 for URL: https://msft.sts.microsoft.com/adfs/services/trust/2005/usernamemixed when the user contains (double quotes "") or (single quotes '') or # in the password.
I am using Adalj 1.1.1 version . With reference to issue # 28 , other special characters works.

StackTrace:

2015-10-22 16:04:15 [ERROR] AuthenticationContext - [Correlation ID: fe07e105-9371-48e0-a0eb-c274421b9e8a] Request to acquire token failed. (p: default-threadpool; w: Idle)
java.io.IOException: Server returned HTTP response code: 500 for URL: https://msft.sts.microsoft.com/adfs/services/trust/2005/usernamemixed
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1627) ~[na:1.7.0_85]
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254) ~[na:1.7.0_85]
at com.microsoft.aad.adal4j.HttpHelper.readResponseFromConnection(HttpHelper.java:86) ~[adal4j-1.1.1.jar:1.1.1]
at com.microsoft.aad.adal4j.HttpHelper.getResponse(HttpHelper.java:182) ~[adal4j-1.1.1.jar:1.1.1]
at com.microsoft.aad.adal4j.HttpHelper.executePostRequest(HttpHelper.java:172) ~[adal4j-1.1.1.jar:1.1.1]
at com.microsoft.aad.adal4j.HttpHelper.executeHttpPost(HttpHelper.java:81) ~[adal4j-1.1.1.jar:1.1.1]
at com.microsoft.aad.adal4j.WSTrustRequest.execute(WSTrustRequest.java:61) ~[adal4j-1.1.1.jar:1.1.1]
at com.microsoft.aad.adal4j.AuthenticationContext.processPasswordGrant(AuthenticationContext.java:801) [adal4j-1.1.1.jar:1.1.1]
at com.microsoft.aad.adal4j.AuthenticationContext.access$000(AuthenticationContext.java:64) [adal4j-1.1.1.jar:1.1.1]
at com.microsoft.aad.adal4j.AuthenticationContext$1.call(AuthenticationContext.java:140) [adal4j-1.1.1.jar:1.1.1]
at com.microsoft.aad.adal4j.AuthenticationContext$1.call(AuthenticationContext.java:130) [adal4j-1.1.1.jar:1.1.1]
at java.util.concurrent.FutureTask.run(FutureTask.java:262) [na:1.7.0_85]

Validate token Signature

Hi guys, hope you're well.

Are you planning to add JWT signature validation to this library? If that's the case, could you share the estimated release date?

There are good open source libraries to do it but we'd also need to get the AAD public keys periodically, etc... It will be very nice to have it available here ๐Ÿ‘

Thank you,
Seba

How do I run the java webapp sample, Get an error saying "No main class"

Hey
I am trying to run the sample java web app
when I run the war file I get :

no main manifest attribute, in target/adal4jsample.war

when I run it as

mvn spring-boot:run

I get :

[ERROR] Failed to execute goal org.springframework.boot:spring-boot-maven-plugin:1.3.3.RELEASE:run (default-cli) on project adal4jsample: Unable to find a suitable main class, please add a 'mainClass' property -> [Help 1]

adal4j compatible with jdk1.6 version

Is there any version of adal4j compatible with jDK1.6 available. I was trying to run some junit test case using adal4j with jdk1.6 getting the following error

Caused by: java.lang.UnsupportedClassVersionError: com/nimbusds/jose/Algorithm : Unsupported major.minor version 51.0

Really appreciate
Vinoj

java.lang.NoClassDefFoundError: com/nimbusds/jwt/JWT

Hi,

I am getting below error while trying to execute source. I am just trying to get auth toekn and refresh token.

user id : Password: Exception in thread "main" java.lang.NoClassDefFoundError: com/nimbusds/jwt/JWT
at com.cts.azure.AzureAuthToekn.getAccessTokenFromUserCredentials(AzureAuthToekn.java:48)
at com.cts.azure.AzureAuthToekn.main(AzureAuthToekn.java:33)
Caused by: java.lang.ClassNotFoundException: com.nimbusds.jwt.JWT
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 2 more

Getting "Cannot inherit from final class" error while accessing library

I am trying to communicate with REST API using ADAL. getting below error

Exception in thread "main" java.lang.VerifyError: Cannot inherit from final class
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:800)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
at com.microsoft.aad.adal4j.AuthenticationContext.acquireToken(AuthenticationContext.java:382)
at edu.stanford.test.AccToken.main(AccToken.java:40)


Code used is :

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import com.microsoft.aad.adal4j.AsymmetricKeyCredential;
import com.microsoft.aad.adal4j.AuthenticationContext;
import com.microsoft.aad.adal4j.AuthenticationResult;

public class AcceToken {

public static void main(String[] args) {

    String authority = "https://login.microsoftonline.com/tenant-id/oauth2/authorize";
    ExecutorService service = null;
    service = Executors.newFixedThreadPool(1);
    try {
        AuthenticationContext authenticationContext = new AuthenticationContext(
                authority, false, service);
        System.out.println("Authentication Context is "+ authenticationContext.getAuthority() );
        String certfile = "D:\\Microsoft-tools\\Samples\\Final\\test.pfx";
        InputStream pkcs12Certificate = new FileInputStream(certfile);

        String token = "";

        AsymmetricKeyCredential credential = AsymmetricKeyCredential
                .create("id", pkcs12Certificate, "netkernel");
        System.out.println("X509 is fine!");

        Future<AuthenticationResult> future = authenticationContext.acquireToken("https://outlook.office365.com",(AsymmetricKeyCredential) credential, null);

        token = future.get().getAccessToken();

        Long uuid = UUID.randomUUID().getMostSignificantBits();

        URL url = new URL(
                "https://outlook.office365.com/api/v1.0/emailaddress/folders/inbox/messages");
        HttpURLConnection con = (HttpURLConnection) url.openConnection();

        con.setRequestMethod("GET");
        con.setRequestProperty("Accept", "application/json");
        con.setRequestProperty("User-Agent", "Testing/1.0 abc/1.1");
        Date date = new Date();

        SimpleDateFormat ft = new SimpleDateFormat(
                "E, dd MM yyyy hh:mm:ss zzz");

        System.out.println("Current Date: " + ft.format(date));
        String dateString = ft.format(date);

        con.setRequestProperty("Authorization", "Bearer " + token);

        if (con.getResponseCode() != 200) {
            System.out.println(con.getHeaderFields());

            throw new RuntimeException("Failed : HTTP error code : "
                    + con.getResponseCode());

        }

        BufferedReader br = new BufferedReader(new InputStreamReader(
                (con.getInputStream())));

        String output;
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            System.out.println(output);
        }

        con.disconnect();

        service.shutdown();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

}

I am getting error at below line
Future future = authenticationContext.acquireToken("https://outlook.office365.com",(AsymmetricKeyCredential) credential, null);

when i looked into it i found that in line 382 of AuthenticationContext.java. We are calling buildJwt method of JwtHelper class which is calling AdalJWTClaimsSet class which is extending JWTClaimsSet class.

JWTClaimsSet class is no longer public it is final now.

I tied using earlier version of JWT jars but i keep getting other errors.

Any sort of help is appreciated.

XXE vulnerability in WSTrustResponse.java

There is an XXE bug in WSTrustResponse's parse method. Please see below.

static WSTrustResponse parse(String response, WSTrustVersion version)
        throws Exception {
    WSTrustResponse responseValue = new WSTrustResponse();
    DocumentBuilderFactory builderFactory = DocumentBuilderFactory
            .newInstance();
    builderFactory.setNamespaceAware(true);
    DocumentBuilder builder = builderFactory.newDocumentBuilder();
    Document xmlDocument = builder.parse(new ByteArrayInputStream(response
            .getBytes(Charset.forName("UTF-8")))); **//XXE Bug**
    XPath xPath = XPathFactory.newInstance().newXPath();

XXE vulnerability in MexParser

static BindingPolicy getWsTrustEndpointFromMexResponse(String mexResponse)
        throws Exception {
    DocumentBuilderFactory builderFactory = DocumentBuilderFactory
            .newInstance();
    builderFactory.setNamespaceAware(true);
    DocumentBuilder builder = builderFactory.newDocumentBuilder();
    Document xmlDocument = builder.parse(new ByteArrayInputStream(
            mexResponse.getBytes(Charset.forName("UTF-8")))); **//** **XXE Bug**

    XPath xPath = XPathFactory.newInstance().newXPath(); 

Create UserAssertion class for OBO flows

Currently java code incorrectly uses ClientAssertion class to provide user assertion for OBO. We need to introduce UserAssertion class just like in .NET and update the API surface.

What is the good uniqueId

Hello,
I have a problem with my app which use Azure for Authentication. I need to get the objectId of the user, but when i get the UserInfo, the uniqueId is the "Token_subject".
I found in code the problem in UserInfo.java:

if (!StringHelper.isBlank(claims
                .getStringClaim(AuthenticationConstants.ID_TOKEN_OBJECT_ID))) {

            uniqueId = claims.getStringClaim(AuthenticationConstants.ID_TOKEN_OBJECT_ID);

        } else if (!StringHelper.isBlank(claims
                .getStringClaim(AuthenticationConstants.ID_TOKEN_SUBJECT))) {

            uniqueId = claims.getStringClaim(AuthenticationConstants.ID_TOKEN_SUBJECT);

        }

In object claims, "object_id" is null, and the good object ID is in claims.getCustomClaim (with key "oid")

I don't know if the problem come from a bad utilisation of the app or Azure or if it is a real problem. I fork to try to get "oid" in customClaim before "object_id" but i want to know if i am right or not.

Authenticating users with their userName and password using the web application

We have created and registered an web application on Azure and can do most of the operations. But we are facing issues while implementing the authentication for users with username and password and getting below errors.
While executing the PublicClient.java file it gives -
java.util.concurrent.ExecutionException: com.microsoft.aad.adal4j.AuthenticationException: {"error":"invalid_request","error_description":"AADSTS90014: The request body must contain the following parameter: 'client_secret.
I got to know from another post that the error is due to web application credentials and native application credentials should be used. Is there any way to authenticate users using web application credentials?

ClassCastException when getting access_token with code

I'm calling AuthorizationContext.acquireTokenByAuthorizationCode() and getting the following exception:

failure: java.lang.String cannot be cast to java.lang.Integer
java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
    at com.microsoft.aad.adal4j.UserInfo.createFromIdTokenClaims(UserInfo.java:144)
    at com.microsoft.aad.adal4j.AdalTokenRequest.executeOAuthRequestAndProcessResponse(AdalTokenRequest.java:85)
    at com.microsoft.aad.adal4j.AuthenticationContext.acquireTokenCommon(AuthenticationContext.java:727)
    at com.microsoft.aad.adal4j.AuthenticationContext.access$100(AuthenticationContext.java:61)
    at com.microsoft.aad.adal4j.AuthenticationContext$1.call(AuthenticationContext.java:128)
    at com.microsoft.aad.adal4j.AuthenticationContext$1.call(AuthenticationContext.java:117)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

When applying this patch, everything seems to work. However, a UserInfoTest testcase then fails, because it assumes the claim has to be an Integer.

@@ -139,17 +139,16 @@ public class UserInfo implements Serializable {
         }

         if (claims
-                .getClaim(AuthenticationConstants.ID_TOKEN_PASSWORD_EXPIRES_ON) != null
-                && (int) claims
-                        .getClaim(AuthenticationConstants.ID_TOKEN_PASSWORD_EXPIRES_ON) > 0) {
-            // pwd_exp returns seconds to expiration time
-            // it returns in seconds. Date accepts milliseconds.
-            Calendar expires = new GregorianCalendar();
-            expires.add(
-                    Calendar.SECOND,
-                    (int) claims
-                            .getClaim(AuthenticationConstants.ID_TOKEN_PASSWORD_EXPIRES_ON));
-            userInfo.passwordExpiresOn = expires.getTime();
+                .getClaim(AuthenticationConstants.ID_TOKEN_PASSWORD_EXPIRES_ON) != null) {^M
+            int claimExpiry = Integer.valueOf((String) claims^M
+                        .getClaim(AuthenticationConstants.ID_TOKEN_PASSWORD_EXPIRES_ON));^M
+            if(claimExpiry > 0) {^M
+                // pwd_exp returns seconds to expiration time^M
+                // it returns in seconds. Date accepts milliseconds.^M
+                Calendar expires = new GregorianCalendar();^M
+                expires.add(Calendar.SECOND, claimExpiry);^M
+                userInfo.passwordExpiresOn = expires.getTime();^M
+            }^M
         }

Update the sample apps to demonstrate on behalf of flow

Samples contain public and confidential client flows and we should update them to demonstrate OBO flows. This requires public client to get a token for confidential client, calling some API on confidential client that consumes the access token via Authorization header and then the confidential client calls AAD to get user token for graph.

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.