DefaultAzureCredential Failing for console app after redirect to localhost -localhost sent invalid response - azure-active-directory

I am using DefaultCredential to connect to build configuration from azure keyvault.
var secretClient = new SecretClient(new Uri($"https://{keyvaultName}.vault.azure.net/"),
new DefaultAzureCredential(true)
);
IConfigurationRoot configuration = null;
configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json")
.AddEnvironmentVariables()
.AddAzureKeyVault(secretClient, new PrefixKeyVaultSecretManager(environment))
.AddUserSecrets<Program>().Build();
This was working earlier but now it is failing with interactive browser authentication.
After selecting account, it is redirecting back to localhost and throwing error ("localhost sent an invalid response")
I am using "Azure.Identity" Version="1.4.1" . I also tried with latest beta package(1.5.0-beta.4).
Also Azure.Security.KeyVault.Secrets" Version="4.2.0"

I was getting a similar error from a Windows app using interactive AzureAD authentication. It turned out to be the result of the localhost domain appearing in my Edge (and Chrome) HSTS policy cache. The Azure AD signin flow was trying to redirect to http://localhost:61425/?code=.... But because I had been developing an unrelated ASP.NET application on my machine that used the HSTS middleware (i.e. called app.UseHsts) my browser was remembering that policy and forcing the AzureAD signin redirect to https://localhost:61425/?code=.... That switch from http to https broke the redirect handling in my Windows app.
The solution was to delete the localhost domain from the browser's list of domain security policies.
In edge, type this in the address bar: edge://net-internals/#hsts
In Chrome: chrome://net-internals/#hsts
See ERR_SSL_PROTOCOL_ERROR for localhost from Visual Studio debug

Check your application's redirect URI at Azure Portal. You can find it under Authentication on your application's page.
Set the redirect URI to https://login.microsoftonline.com/common/oauth2/nativeclient.
More information about redirect URIs: https://learn.microsoft.com/en-us/azure/active-directory/develop/reply-url

Related

How to set up access to Azure blob storage from React app (deployed in Azure web app) with credentials from browser?

I got stuck on trying to access Azure blob storage from React app (thus from browser) with credentials.
And firstly I want to admit, that I am newbie in Azure, so maybe I misunderstood some basic concepts...
My current situation and goal:
I am developing React app (lets say MyReactApp). This app uses some files from Azure blob storage (lets say MyBlobStorage) -> it reads, creates and deletes blobs.
I started to develop it on my local and for this dev purpose I was connecting to MyBlobStorage with SAS - this worked perfectly.
MyReactApp is browser only, so it does not have any backend.
After finishing local development, I deployed it as Azure web app with SAS. What have I done:
created App service (lets say MyAppService)
register app in Azure Active Directory and use it as Identity Provider in MyAppService
After this the app works from Azure url perfectly too.
But my app on Azure should fulfill 2 conditions:
User has to log in with AAD account before access to MyReactApp
App itself must get rid of SAS (because it is not secure as it can be obtained from browser) and use some Azure credentials to connect to Azure blob storage
First condition - user log in:
I enabled "easy" logging in MyAppService -> Authentication and chose users, who can have access.
in Authentication section of app in AAD I set up Web type Redirect Uri as /.auth/login/aad/callback
Still everything works great - the user, who is assigned to the app, can log in and work with the app - so far so good, but now the problem comes
Second condition - I wanted to get rid of the SAS to access MyBlobStorage and use DefaultAzureCredentials:
I turned on managed identity for MyAppService and add it as Storage Blob Data Contributor for MyBlobStorage
I obtained user_impersonation and User.Read Api permissions for my app
I removed SAS and tried to add DefaultAzureCredentials to my code -> but it seems, that they can't be used in browser and only option is InteractiveBrowserCredentails
so I tried to use InteractiveBrowserCredentails like this:
this.interactiveBrowserCredential = new InteractiveBrowserCredential({
tenantId: "<appTenant>", // got from app registration on AAD
clientId: "<appClient>", // got from app registration on AAD
redirectUri: <MyAppServiceURi>/.auth/login/aad/callback // the same as in Azure AAD app,
});
this.blobSC = new BlobServiceClient(Constants.STORAGE_PATH, this.interactiveBrowserCredential);
My current result:
This shows login popup after getting to the page and after another signing in it results in error:
AADSTS9002326: Cross-origin token redemption is permitted only for the
'Single-Page Application' client-type.
I googled it of course and according to some answers I tried to change the Web type of redirect URI to SPA.
I tried it, but some other error showed up:
AADSTS9002325: Proof Key for Code Exchange is required for
cross-origin authorization code redemption.
Surprisingly this should be solved by changing from SPA to Web type...:) So I am trapped...
My expected result
In ideal world, I want to connect MyReactApp to MyBlobStorage without popup and with some secret credentials, just to say something like this.blobSC = new BlobServiceClient(Constants.STORAGE_PATH, credentials);
and be able to work with blobs.
Is it possible to access blob storage from browser without errors of course and ideally without popup, which needs another log in for user?
My complementary questions
Can I use somehow the logging info from the user (from his "easy" AAD logging)? I can get his info with GET call to /.auth/me, maybe it can be utilized, so I can use his info to access the blobs?
The solution should be working on localhost too (I tried to add http://localhost:3000/ to redirect uri, but without success), can it be done?
Thank you all, who read the whole story!

Using Saml with Azure AD using Blazer Web assembly

I'm trying to use .NET core Blazer webAssembly client UI from main() and authenticate with Azure AD using SAML with the following code, but getting error. can't figure this out one issue below. any clue is appreciated
there was an error trying to log you in: 'Cannot read property 'redirectUri' of undefined'
OIDC works fine.
Below is my code called from Main in Program.cs
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("app");
builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
builder.Services.AddHttpClient("BlazorWASMAuthApp.ServerAPI", client => client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress))
.AddHttpMessageHandler<BaseAddressAuthorizationMessageHandler>();
builder.Services.AddScoped(sp => sp.GetRequiredService<IHttpClientFactory>()
.CreateClient("BlazorWASMAuthApp.ServerAPI"));
builder.Services.AddApiAuthorization(); builder.Services.AddAuthenticationCore(); builder.Services.AddAuthorizationCore();
builder.Services.AddAuthentication().AddSaml2(options =>
{
// builder.Configuration.Bind("AzureAd", options.SPOptions.AuthenticateRequestSigningBehavior);
//APP Registration keys Will be moved to Json in subsequent story
options.SPOptions.EntityId = new EntityId("https://localhost:5001/saml2");
//options.SPOptions..Add("https://localhost:5001/saml2/API.Access");
options.IdentityProviders.Add(
new IdentityProvider(
new EntityId("https://sts.windows.net/{Clientid}/"), options.SPOptions)
{
//SingleSignOnServiceUrl = signinURI,
MetadataLocation = ...federationdataxml?clientid={clientid}"
});
;
})
.AddCookie();
The most common errors as per ms docs are caused by incorrect configuration
Depending on the requirements of the scenario, a missing or incorrect
Authority, Instance, Tenant ID, Tenant domain, Client ID, or Redirect
URI prevents an app from authenticating clients.
Running the app at a different port than is configured in the Redirect
URI of the Identity Provider's app registration.
Please check if the cause is missing return url parameter in configuration in your code provided:
options.SPOptions.ReturnUrl = new Uri("https://localhost:5001/authentication/azurecallback"); which comes after
options.SPOptions.EntityId = new EntityId("https://localhost:5001/saml2");
else check Portal side configurations.
While registering API , redirect uri is set as web and its field is left empty and api is exposed from Expose api .
But When registering client app , redirect uri must be set ,hope you have done so.
client app > go active directory b2c >give name >select supported account>redirect uri >select SPA-give redirect ur like https://localhost:5001/authentication/login-callback
(format of uri : https://localhost:{PORT}/authentication/login-callback.)
This 'authentication/login-callback' must be present in your code configuration too.
From reference
NOTE: The default port for an app running on Kestrel is 5001. If the
app is run on a different Kestrel port, use the app's port. For IIS
Express, the randomly generated port for the app can be found in the
Server app's properties in the Debug panel. Since the app doesn't
exist at this point and the IIS Express port isn't known, return to
this step after the app is created and update the redirect URI. A
remark appears in the Create the app section to remind IIS Express
users to update the redirect URI.
So Check the port running and update the redirect uri if not done.
References:
Reference 1
Reference 2
Cors

Error "invalid_client" when trying to get a token from Microsoft API

I'm trying to develop a drive solution (Onedrive) in a windev program.
I created an application in Microsoft Azure and created a secret key.
When doing the first request https://login.live.com/oauth20_authorize.srf?client_id={client_id}&scope={scope} &response_type=code&redirect_uri={redirect_uri} I'm redirected on the connection page.
Once I'm connected I get a code back as https://login.live.com/oauth20_authorize.srf?code={code}.
But when I ask for a token posting this request : POST https://login.live.com/oauth20_token.srf Content-Type: application/x-www-form-urlencoded client_id={client_id}&redirect_uri={redirect_uri}&client_secret={client_secret} &code={code}&grant_type=authorization_code
I get this back
{ "error":"invalid_client", "error_description":"The client does not exist or is not enabled for consumers. If you are the application developer, configure a new application through the App Registrations in the Azure Portal at https:\/\/go.microsoft.com\/fwlink\/?linkid=2083908.", "correlation_id":"471e800c-69b4-43c6-a03f-a1f7e9512e6b" }
Thank you for your help.
This error means you are using a Microsoft Account to login your client app, but it is not enabled for that.
To change the setting for an existing AD App, navigate to the Manifest blade of it in the portal, find the signInAudience attribute, set it with AzureADandPersonalMicrosoftAccount or PersonalMicrosoftAccount.

How do I resolve this CORS error during Azure AD SSO post logout sequence?

I have a webforms web app in which I'm integrating Azure AD SSO. I have a login sequence working ok, but the post-logout redirect is giving me a CORS error.
In my call to app.UseOpenIdConnectAuthentication() in my startup class I've got the following (actually the the URI is not hard-coded but set up in the web.config)
.PostLogoutRedirectUri = "https://localhost:44370/LoggedOut.aspx"
The error is
SEC7120: [CORS] The origin 'https://localhost:44370' did not find
'https://localhost:44370' in the Access-Control-Allow-Origin response
header for cross-origin resource at
'https://login.microsoftonline.com/common/oauth2/v2.0/logout?post_logout_redirect_uri=https%3A%2F%2Flocalhost%3A44370%2FLoggedOut.aspx&x-client-SKU=ID_NET451&x-client-ver=5.2.1.0'.
I have tried calling HttpContext.Current.GetOwinContext().Response.Headers.Add("Access-Control-Allow-Origin", {"*"}) but no change.
edit: I have the URL configured in the RedirectURIs section for the app in Azure portal.
You say you have the URL configured in the RedirectURIs section for the app in the Azure portal but it should be configured under Properties in App Registrations > My App > Properties > Logout URL
The Reply URL section should just have whatever page you want the user to get redirected to after logging in.
]1

AADSTS50011: The reply url specified in the request does not match the reply urls configured for the application: '<AppId>'

I have a .NET Core 2 app template that is configured to use Azure AD out of the box.
The configuration is:
{
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"Domain": "lautaroarinolive.onmicrosoft.com",
"TenantId": "67cb2dfd-ebd5-40d8-829b-378340981a17",
"ClientId": "50819a7a-e018-4c1d-bf0a-18c8fce5c600",
"CallbackPath": "/signin-oidc"
},
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
}
}
In my portal, I have an Azure app registration with the same id as ClientId. It has the reply URL [APP-URL]/signin-oidc.
The localhost app works only if I set the reply URL to [LocalhostURL]/signin-oidc, even though I've learned that the configuration should not affect log in on localhost.
The Azure app does not work in any case.
In both apps when it doesn't work I get this error:
AADSTS50011: The reply url specified in the request does not match the
reply urls configured for the application:
'50819a7a-e018-4c1d-bf0a-18c8fce5c600'
Is it correct that a localhost app should not need a configured reply URL?
Why do I get the "reply url not configured" error?
You can refer to this Sample to rebuild your .NET core App and publish to the Azure.
There are some NOTES you need to pay attention to :
you need to change the port from 5000 to the effective one. Currently, it should be 61659. So, when you do a test in your localhost, you can set the reply URL in the AAD App with http://localhost:61659/signin-oidc
Update these URLs if you configure the app for production use or If you publish the App to Azure Web App, you should change the Reply URL in both App config file and AAD Application to be <AppURL>/signin-oidc
For example, https://www.contoso.com/signin-oidc or https://Myapp.azurewebsites.net/signout-oidc.
I had a similar problem with a .NET 4.6.1 web application.
I had to configure the Reply URL for my app in azure similar to the accepted answer, however the callback url was different.
Select Azure Active Directory -> App Registrations -> <your app>
Select Settings -> Reply URLs
Add your apps URL + '/.auth/login/aad/callback'
For Example:
https://somesite.azurewebsites.net/.auth/login/aad/callback
Check your redirect uri in your Microsoft sign in page
redirect_uri=https://localhost:8443/login&response_type=code&scope=openid%20profile&state=7GsiHb
And make sure that you have added the same URI to redirect URI list in your registered application (Active Directory -> App Registration -> Your Application). As mentioned in other answers may need to change supported account type as "Multiple Organizations".
Just got the same error. My app is a .NET 5 ASP.NET Core app running in a Linux docker container inside of a web app. Troubleshooting using Fiddler has shown that in calls to login.microsoft.com the value of a redirect_uri query string variable was starting with "http://" and not with "https://" as I would expect despite my attempts to enforce TLS-only on the web app itself. That led to URL mismatch and to the error AADSTS50011.
Setting the environment variable ASPNETCORE_FORWARDEDHEADERS_ENABLED=true on the web app has fixed the issue. Microsoft has documented it here: https://devblogs.microsoft.com/aspnet/forwarded-headers-middleware-updates-in-net-core-3-0-preview-6/
Make sure services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); must below the Authentication configuration.
services.AddAuthentication(options =>
{
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddOpenIdConnect(options =>
{
options.Authority = "";
options.ClientId = "";
options.ResponseType = OpenIdConnectResponseType.IdToken;
options.CallbackPath = "";
options.SignedOutRedirectUri = "";
options.TokenValidationParameters.NameClaimType = "name";
})
.AddCookie();
I was facing the same error due to having added AddMvc() before the AddAuthentication() extension method.
In some case, azure to use the 'www' on the url, even if you especific the url on the portal without 'www'. Use "https://www.mysite.co/signin-oidc" instead "https://mysite.co/signin-oidc" in your redirectUri variable.
Small thing, but at the Web Tenant, at custom domains settings HTTPS Only option should be turned on depending on URLs used by the site. I had the same problem, as at the login, the redrect_uri=http://sitename was concatenated instead of https. Enabling this option resolved my authentication issue.
If you are signing in from AAD you should use app-base-url/sigin-aad.
If you use React- Native. Able to check the web portal: https://portal.azure.com/.
iOS: {YOUR_BUNDLE_IDENTIFIER}://{YOUR_BUNDLE_IDENTIFIER}/ios/callback
Android: {YOUR_APP_PACKAGE_NAME}://{YOUR_APP_PACKAGE_NAME}/android/callback
pls refer with image below.
enter image description here
The only solution for me: in the Azure portal https://portal.azure.com, navigate to "app registrations" -> select your application -> "authentication" from the left sidebar menu -> "mobile and desktop applications" redirect URIs -> and click "Add URI" -> type the following
ms-appx-web://microsoft.aad.brokerplugin/{Your_Application's_Client_ID}
Example: ms-appx-web://microsoft.aad.brokerplugin/5r3257qe-7jci-3501-38k0-3791h90542m7

Resources