Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Azure Application Proxy access using MSAL token #2178

Closed
Mir4ik opened this issue Nov 11, 2020 · 24 comments
Closed

Azure Application Proxy access using MSAL token #2178

Mir4ik opened this issue Nov 11, 2020 · 24 comments

Comments

@Mir4ik
Copy link

Mir4ik commented Nov 11, 2020

Implemented test windows application based on official manual: https://docs.microsoft.com/en-us/azure/active-directory/manage-apps/application-proxy-configure-native-client-application

Following code is a result:

IPublicClientApplication clientApp = PublicClientApplicationBuilder
            .Create("Native App Client Id")
            .WithRedirectUri("http://localhost")
            .WithAuthority("https://login.microsoftonline.com/"My Tenant ID"")
            .Build();

            Microsoft.Identity.Client.AuthenticationResult authResult = null;
            var accounts = await clientApp.GetAccountsAsync();
            IAccount account = accounts.FirstOrDefault();

            IEnumerable<string> scopes = new string[] { "api://"APP Proxy Uri"/user_impersonation" };

            try
            {
                authResult = await clientApp.AcquireTokenSilent(scopes, account).ExecuteAsync();
            }
            catch (MsalUiRequiredException ex)
            {
                authResult = await clientApp.AcquireTokenInteractive(scopes).ExecuteAsync();
            }

            if (authResult != null)
            {
                HttpClient httpClient = new HttpClient();
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
                HttpResponseMessage response = await httpClient.GetAsync("App Proxy based URL"+ "/api/values");

Everything works fine until HTTP request with a token, it is being redirected to login.microsoft.com: https://i.stack.imgur.com/GUe7l.png

Redirect URI to login.microsoft.com: {https://login.microsoftonline.com/9966XXXXXXXXXXXXXXXXXXXXXXXX/oauth2/authorize?response_type=code&client_id=XXXXXXXXXXXX&scope=openid&nonce=983XXXXXXXXXXXXXX&redirect_uri=https:%2f%2fXXXXXXX.msappproxy.net%2f&state=AppProxyState:{"InvalidTokenRetry":true%2c"IsMsofba":false%2c"OriginalRawUrl":"https:%5c%2f%5c%2fXXXXXXXXXXXXXXX.msappproxy.net%5c%2fapi%5c%2fvalues"%2c"RequestProfileId":"XXXXXXXXX"}%23EndOfStateParam%23&client-request-id=XXXXXXXX}

Any ideas what's wrong? Browser access works just fine, also JWT token is fully valid and being passed correctly.

@jmprieur
Copy link
Contributor

@Mir4ik maybe you need an accept default header to get Json?

@Mir4ik
Copy link
Author

Mir4ik commented Nov 11, 2020

@jmprieur adding JSON accept header do not help, same issue

@bgavrilMS
Copy link
Member

.net classic or .net core?

@bgavrilMS
Copy link
Member

Try

 var httpClient = new HttpClient(new HttpClientHandler() { 
                 UseDefaultCredentials = true });

@Mir4ik
Copy link
Author

Mir4ik commented Nov 11, 2020

@bgavrilMS no changes - https://imgur.com/YNL2NkC
It's both .Net and Core. Also same issue in Java (MSAL for Android) and iOS (MSAL for iOS). Basically I've implemented 2 mobile apps that were working fine with API's directly, but when switched to App Proxy it stopped working (even by following manuals). Now I've implemented test app according to official manual in C# - still no luck.

@bgavrilMS
Copy link
Member

In your picture it seems the Http call returns a 200 OK?

@Mir4ik
Copy link
Author

Mir4ik commented Nov 11, 2020

It redirects to login.microsoft.com asking to log in and login.microsoft.com returns 200, sample URL with parameters in initial post.

@bgavrilMS
Copy link
Member

Got it. I'm afraid I don't know what's going on. If access token is invalid, protected APIs return 401, they should not redirect.

We are not familiar enough with App Proxy to diagnose these issues. MSAL's responsability ends when a token is obtained. I recommend you open a support ticket instead from Azure Portal (they are free as far as I know).

@j5aenz
Copy link

j5aenz commented Dec 7, 2020

i have not been able to successfully connect to azure sql using msal as used above or with any of the examples using .Net 5 with WPF. I can use keyvault no problem to credential. but once i go through the msal process and try the different non-embedded views, and redirectURI recommendations, I still end up with code that never receives a response. The exact same approach works fine in the .net framework with nearly all the same libraries. let me know if you have any insights rather than waiting for better .net core integration.

@bgavrilMS
Copy link
Member

@j5aenz - I think this is a different problem. OP is getting a token, but the token is not valid. In your case, you're not getting a token.

We plan to release a .NET 5 version that has both system webview (the one with http://localhost) and an embedded webview, see #1398

@pranayubs
Copy link

Hello,
We are also facing same issue... getting login.microsoft.com redirect url in response.

Any update on this issue please?

@j5aenz
Copy link

j5aenz commented Dec 23, 2020

@pranayubs , please correct me if i am wrong @bgavrilMS , but i am patiently waiting for Microsoft.Identity.Client 4.25.0 to solve this issue or implement WAM and potentially circumvent the issue. i have tried a number of different combinations of settings in Azure without success in 4.24.0. And it looks like #1398 refers to this but kind of circularly refers back to this thread.

@chuckconway
Copy link

chuckconway commented Apr 7, 2021

@Mir4ik Was this issue ever resolved or did you find a workaround? I'm facing the same issue. I can authenticate successfully, but when I try to access an Application Proxy endpoint I'm encountering the sign-in page.

@jmprieur
Copy link
Contributor

jmprieur commented Apr 7, 2021

@chuckconway
Copy link

Are you using ASP.NET Core, @chuckconway ?
did you see? https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/proxy-load-balancer?view=aspnetcore-5.0

I am. That's very cool, I didn't know about that feature. But I'm not seeing how this feature will help with the Azure Application Proxy access issue...

@jmprieur
Copy link
Contributor

jmprieur commented Apr 7, 2021

I think that this is a problem of with headers, and that article, and in particular the forward headers, should help you.

If you are using ASP.NET Core we also suggest you use Microsoft.Identity.Web: https://github.com/AzureAD/microsoft-identity-web/wiki/1.0.0
See also https://github.com/AzureAD/microsoft-identity-web/wiki/Deploying-Web-apps-to-App-services-as-Linux-containers#issues-with-load-balancing-across-multiple-regions-using-front-door

@chuckconway
Copy link

chuckconway commented Apr 7, 2021

I miss read your question about ASP.Net Core. For some reason, I thought you were just asking about .Net Core vs .Net. I'm not using ASP.Net Core, just .Net Core.

The problem I'm having is the same as the opener of this thread. I can get the JWT Token for the user from AAD, but when I make a request to an Azure Application Proxy endpoint I'm routed to the sigin-in page.

I'm following this MS Documentation: https://docs.microsoft.com/en-us/azure/active-directory/manage-apps/application-proxy-secure-api-access#:%7E:text=Secure%20access%20to%20on-premises%20APIs%20with%20Azure%20AD,...%205%20Configure%20the%20native%20app%20code.%20

Here is the code:


       [Fact]
        public async Task Successfully_authenticate_but_cant_access_the_proxy()
        {
            // Acquire Access Token from AAD for Proxy Application
            var clientApp = PublicClientApplicationBuilder
                .Create("880f819e-xxxx-xxxx-98c0-xxxxxxxxx") //Client Id for Client Application
                .WithRedirectUri("http://localhost") // This must be configured as a "Mobile and desktop applications" platform in the client application
                //.WithDefaultRedirectUri()
                //.WithTenantId("07331439-xxxx-xxxx-xxxx-8dc72cbc00bd") //Not sure if this is needed.
                .WithAuthority("https://login.microsoftonline.com/07331439-xxxx-xxxx-xxxx-8dc72cbc00bd/oauth2/v2.0/authorize")
                .Build();

            AuthenticationResult authResult;
            var accounts = await clientApp.GetAccountsAsync();
            var account = accounts.FirstOrDefault();

            IEnumerable<string> scopes = new string[] {"https://endpoints-xxx.msappproxy.net/user_impersonation"};

            try
            {
                authResult = await clientApp.AcquireTokenSilent(scopes, account).ExecuteAsync();
            }
            catch (MsalUiRequiredException ex)
            {
                authResult = await clientApp.AcquireTokenInteractive(scopes).ExecuteAsync();                
            }

            if (authResult != null)
            {
                //Use the Access Token to access the Proxy Application
                var httpClient = new HttpClient(new HttpClientHandler() 
                { 
                    UseDefaultCredentials = true 
                });
                
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
                httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
                
                var response = await httpClient.GetAsync("https://endpoints-xxx.msappproxy.net/WeatherForecast");

                //Failing here. I'm receiving the HTML for the Sign-In page. I'm expecting a response with JSON.
                var responseValue = await response.Content.ReadAsStringAsync();
            }
        }

Accessing the endpoints via the browser works perfectly, but via code/JWT it does not work. I'm hoping someone has overcome this problem either in code or a workaround.

@chuckconway
Copy link

@chuckconway
The authority should be "https://login.microsoftonline.com/07331439-xxxx-xxxx-xxxx-8dc72cbc00bd", not "https://login.microsoftonline.com/07331439-xxxx-xxxx-xxxx-8dc72cbc00bd/oauth2/v2.0/authorize"

@jmprieur Thank you for pointing that out! I made the change, but I'm still receiving the sign-in page :(

@nasirsinani
Copy link

@chuckconway, have you found any solution to this? Thanks

@chuckconway
Copy link

chuckconway commented Nov 1, 2021 via email

@nasirsinani
Copy link

@chuckconway, thank you for providing this information. I kind of have a similar situation, can you please check: https://github.com/MicrosoftDocs/azure-docs/issues/83207, and see if you can be of help? Thanks

@chuckconway
Copy link

chuckconway commented Nov 5, 2021 via email

@bgavrilMS
Copy link
Member

Recommendation is to use WAM on public client, see https://aka.ms/msal-net-wam

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

7 participants