Need windows Azure app to authenicate against Office 365 Active Directory - asp.net-mvc

I have an mvc web application that I've published to windows Azure. I would like to use our Office 365 Active Directory to authenticate on log-in. I've entered a ticket with window Azure and they have sent me here.
I feel like I'm close to figuring this out. When I select the to sign-in it takes me to the microsoft log-in page and looks to authenticate me,but on the trip back to my applicaton I get the following error. I have changed the client secret key a dozen time and recreated the azure publish profile and azure app.
Error:
The remote server returned an error: (401) Unauthorized.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Net.WebException: The remote server returned an error: (401) Unauthorized.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[WebException: The remote server returned an error: (401) Unauthorized.]
System.Net.HttpWebRequest.GetResponse() +1465
Microsoft.IdentityModel.Clients.ActiveDirectory.d__2.MoveNext() +378
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +99
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
Microsoft.IdentityModel.Clients.ActiveDirectory.d__0`1.MoveNext() +410
[AdalServiceException: AADSTS70002: Error validating credentials. AADSTS50012: **Invalid client secret is provided
Trace ID: fa6387cc-0e46-417d-a109-0d6f356b619b
Correlation ID: 5bf34f08-6b63-4845-b684-85ddc6d27e27
Timestamp: 2015-09-21 13:00:07Z]
Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext.RunAsyncTask(Task`1 task) +89
Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext.AcquireTokenByAuthorizationCode(String authorizationCode, Uri redirectUri, ClientCredential clientCredential, String resource) +64
NavPO.Startup.b__7_0(AuthorizationCodeReceivedNotification context) +279
Microsoft.Owin.Security.OpenIdConnect.d__1a.MoveNext() +4931
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +26
Microsoft.Owin.Security.OpenIdConnect.d__1a.MoveNext() +6453
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +99
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
Microsoft.Owin.Security.Infrastructure.d__0.MoveNext() +581
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +99
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
Microsoft.Owin.Security.Infrastructure.d__0.MoveNext() +225
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +99
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.d__5.MoveNext() +187
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +99
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
Microsoft.Owin.Security.Infrastructure.d__0.MoveNext() +561

From the error message:
AdalServiceException: AADSTS70002: Error validating credentials. AADSTS50012: **Invalid client secret is provided
There is Azure AD code running in your app that is trying to complete the login flow. It's failing to do so because the client secret that is configured in your web app (probably in your web.config) is incorrect - i.e. it doesn't match any secret that was configured in your Azure AD application.
Take a look at the following sample as a starting point and compare it to your app to see where things might be misconfigured:
https://github.com/AzureADSamples/WebApp-OpenIDConnect-DotNet

Related

Request time out error when getting access token using MSAL library "confidentialClientApplication.AcquireTokenForClient"

I'm trying to run a console application as a windows service which communicates with outlook exchange online using EWS. This has OAuth authentication and for that AppID is registered on the Azure portal. I am able to generate access token and communicate with exchange online successfully.
However when run from a remote server, it gives request timeout error. Request to the endpoint to get access token is timing out.
Can you please help me with this. I'm not able to identify the issue.
Below the access code:
var cca = ConfidentialClientApplicationBuilder
.Create(ConfigurationSettings.AppSettings["appId"])
.WithClientSecret(ConfigurationSettings.AppSettings["clientSecret"])
.WithTenantId(ConfigurationSettings.AppSettings["tenantId"])
.Build();
var ewsScopes = new string[] { ConfigurationSettings.AppSettings["EWSScope"] };
var accessTokenRequest = cca.AcquireTokenForClient(ewsScopes);
var accessToken = accessTokenRequest.ExecuteAsync().Result.AccessToken;
Below error
System.AggregateException: One or more errors occurred. ---> Microsoft.Identity.Client.MsalServiceException: Request to the endpoint timed out. ---> System.Threading.Tasks.TaskCanceledException: A task was canceled. at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.Identity.Client.Http.HttpManager.<ExecuteAsync>d__14.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.Identity.Client.Http.HttpManager.<ExecuteWithRetryAsync>d__12.MoveNext() --- End of inner exception stack trace --- at Microsoft.Identity.Client.Internal.Requests.RequestBase.<HandleTokenRefreshErrorAsync>d__27.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.Identity.Client.Internal.Requests.ClientCredentialRequest.<ExecuteAsync>d__2.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.Identity.Client.Internal.Requests.RequestBase.<RunAsync>d__12.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.Identity.Client.ApiConfig.Executors.ConfidentialClientExecutor.<ExecuteAsync>d__3.MoveNext() --- End of inner exception stack trace ---
Does the remote server have access to the authentication endpoint eg login.microsoftonline.com. Is there any proxying being used ? you could try running the ewseditor from that remote server https://github.com/dseph/EwsEditor/releases to see if you can authenticate using oAuth

ASP.Net MVC to ASFS Call Throwing Remote Certificate Error

I configured an ADFS service in one of my Azure VMs. I created a free
certificate using this tool, https://github.com/Crypt32/PSPKI, and
configured it under Trusted Root in that VM. I also able to run and
login inside that VN using /adfs/ls/idpinitiatedSignOn.aspx. I also
added "https://localhost:44360/" as a trusted inside ADFS. Then I
created a local ASP.NET application which is running as
https://localhost:44360/ and using
"https://adfsvm.centralus.cloudapp.azure.com/FederationMetadata/2007-06/FederationMetadata.xml"
as a metadata Ref. I could able to download this metadata file in my
machine, once skipped the security warning.
My issue is that Once running the application, screen throws the error
as "The remote certificate is invalid according to the validation
procedure.".
I confirmed that on ADFS server, it didn't hit and no logs. But in my
local machine some logs are there like below.
IDX20804: Unable to retrieve document from: '[PII is hidden by default. Set the 'ShowPII' flag in IdentityModelEventSource.cs to true to reveal it.]'. at Microsoft.IdentityModel.Protocols.HttpDocumentRetriever.d__8.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.IdentityModel.Protocols.WsFederation.WsFederationConfigurationRetriever.d__4.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task) at Microsoft.IdentityModel.Protocols.ConfigurationManager`1.d__24.MoveNext() An error occurred while sending the request. at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.IdentityModel.Protocols.HttpDocumentRetriever.d__8.MoveNext() The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel. at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult) at System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar) The remote certificate is invalid according to the validation procedure. at System.Net.TlsStream.EndWrite(IAsyncResult asyncResult) at System.Net.PooledStream.EndWrite(IAsyncResult asyncResult) at System.Net.ConnectStream.WriteHeadersCallback(IAsyncResult ar)
https://localhost:44360/
Any lead here to troubleshoot more would be appreciated.

error The antiforgery token could not be decrypted. The key {guid} was not found in the key ring

We're running an ASP.NET MVC Core 1.1 application on a web farm with 2 servers and ran into these exceptions, when a user is attempting to upload a file. We believe this is happening because the get request is from one server and their post may be going to the other web server, leading to the keys being not matched?
Is there a way to get around this issue?
Error 1:
The antiforgery token could not be decrypted.
at Microsoft.AspNetCore.Antiforgery.Internal.DefaultAntiforgeryTokenSerializer.Deserialize(String
serializedToken) at
Microsoft.AspNetCore.Antiforgery.Internal.DefaultAntiforgery.DeserializeTokens(HttpContext
httpContext, AntiforgeryTokenSet antiforgeryTokenSet,
AntiforgeryToken& cookieToken, AntiforgeryToken& requestToken) at
Microsoft.AspNetCore.Antiforgery.Internal.DefaultAntiforgery.ValidateTokens(HttpContext
httpContext, AntiforgeryTokenSet antiforgeryTokenSet) at
Microsoft.AspNetCore.Antiforgery.Internal.DefaultAntiforgery.d__9.MoveNext()
--- End of stack trace from previous location where exception was thrown --- at
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.ValidateAntiforgeryTokenAuthorizationFilter.d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown --- at
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__20.MoveNext()
--- End of stack trace from previous location where exception was thrown --- at
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at Microsoft.AspNetCore.Builder.RouterMiddleware.d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown --- at
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
Microsoft.AspNetCore.HttpOverrides.HttpMethodOverrideMiddleware.d__4.MoveNext()
--- End of stack trace from previous location where exce
Error 2: The antiforgery token could not be decrypted.
at
Microsoft.AspNetCore.Antiforgery.Internal.DefaultAntiforgeryTokenSerializer.Deserialize(String
serializedToken) at
Microsoft.AspNetCore.Antiforgery.Internal.DefaultAntiforgery.DeserializeTokens(HttpContext
httpContext, AntiforgeryTokenSet antiforgeryTokenSet,
AntiforgeryToken& cookieToken, AntiforgeryToken& requestToken) at
Microsoft.AspNetCore.Antiforgery.Internal.DefaultAntiforgery.ValidateTokens(HttpContext
httpContext, AntiforgeryTokenSet antiforgeryTokenSet) at
Microsoft.AspNetCore.Antiforgery.Internal.DefaultAntiforgery.d__9.MoveNext()
--- End of stack trace from previous location where exception was thrown --- at
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.ValidateAntiforgeryTokenAuthorizationFilter.d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown --- at
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__20.MoveNext()
--- End of stack trace from previous location where exception was thrown --- at
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at Microsoft.AspNetCore.Builder.RouterMiddleware.d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown --- at
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
Microsoft.AspNetCore.HttpOverrides.HttpMethodOverrideMiddleware.d__4.MoveNext()
--- End of stack trace from previous location where exce
Do you have a machine key defined (see this: Adding machineKey to web.config on web-farm sites)? Both servers should have the same machineKey config entry (can be generated within IIS or via online tools).
<machineKey
validationKey="GENERATED VALUE"
decryptionKey="GENERATED VALUE"
validation="SHA1"
decryption="AES" />
For DotNetCore Apps running on IIS, if your application pool is set to use AppPoolIdentity, then you need to make sure "Load User Profile" is set to "True" in the Application Pool Advanced Settings.
See: https://learn.microsoft.com/en-us/aspnet/core/security/data-protection/configuration/default-settings?view=aspnetcore-2.1
If the user profile is available, keys are persisted to the %LOCALAPPDATA%\ASP.NET\DataProtection-Keys folder. If the operating
system is Windows, the keys are encrypted at rest using DPAPI.

Access all user drives as Admin

I am building a native application that uses Microsoft Graph.
I want to read all the files in OneDrive of all the users in the organization, via admin account.
I am using the (Azure AD 2.0) OAUTH authorization workflow to get the authorization code. After which I get the access token and refresh token.
However when I try to access the drive of any user :
graphClient.Drives["amit#csys.onmicrosoft.com"].Root.Request().GetAsync();
// where graphClient is instance of GraphServiceClient
I get:
generalException
Message: Unexpected exception returned from the service.
With call stack :
at Microsoft.Graph.HttpProvider.<SendAsync>d__19.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
at Microsoft.Graph.BaseRequest.<SendRequestAsync>d__34.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
at Microsoft.Graph.BaseRequest.<SendAsync>d__32`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
at Microsoft.Graph.DriveItemRequest.<GetAsync>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at OneDrive_Writer.OneDriveWriter.<loadRootDriveFolder>d__9d.MoveNext()
Is there a way an admin can access all other users drives files?
NOTE: I am able to access the Admin's OneDrive account when I login as Admin.
The Drives indexer in your example expects a driveId, not a upn.
Assuming that your permissions are properly set, and you have a valid access token,
you'll do something like this.
// Access the users in the org.
var users = await graphClient.Users.Request().GetAsync();
// Get the drives for a user.
var drives = await graphClient.Users[users[0].Id].Drives.Request().GetAsync();
// Get the specific drive metadata for a user
var drive = await graphClient.Drives[drives[0].Id].Request().GetASync();

OneDrive Search throws UnknownError when search contains "*"

This is a copy paste from my original posted github issue
I'm working on a prototype application leveraging the Microsoft.Graph SDK. I noticed that if I run the following code on my "Live" / Personal OneDrive account it works just fine and returns the files I expect. However, if I run the same code against my OneDrive for Business, it throws an internal exception within Microsoft.Graph.Core. I suspect the reason is that my search Url contains a * as mentioned in the error, but why does it work when searching a Live account and break when searching a Work account?
Sample Code Snippet:
var graphserviceClient = new GraphServiceClient(
new DelegateAuthenticationProvider(
(requestMessage) =>
{
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", ADALAuth.CurrentAccessToken);
return Task.FromResult(0);
}));
var drive = graphserviceClient.Me.Drive.Request().GetAsync().Result;
var collection = graphserviceClient.Me.Drive.Search("*.xyz").Request().GetAsync().GetAwaiter().GetResult();
The error message returned is:
Code: UnknownError
Message: A potentially dangerous Request.Path value was detected from the client (*).
Inner error
Stack Trace:
at Microsoft.Graph.HttpProvider.<SendAsync>d__19.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Graph.BaseRequest.<SendRequestAsync>d__36.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Graph.BaseRequest.<SendAsync>d__32`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Graph.DriveSearchRequest.<GetAsync>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at _Default.Page_Load(Object sender, EventArgs e) in e:\Profile\Documents\Visual Studio 2015\WebSites\AzureWebApp\Default.aspx.cs:line 33
at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e)
at System.Web.UI.Control.OnLoad(EventArgs e)
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
Behind the scenes, Graph is routing your request to two different systems depending on your account type. Because of these, there are some subtle differences between the two systems.
Regardless, you shouldn't need the * as Search is already searching for the string you passed within other strings. In other words both *.xyz and .xyz get translated into *.xyz*. It will match this query in this way across several fields including filename, metadata, and file content.

Resources