We are using the ADAL C# library to acquire tokens to Azure AD Applciations (including the Graph API).
We have AD Connect set up with our Azure AD using an on premises ADFS 3.0 server. So, when a native client application calls....
var ourDomain = "abc.com";
var authority = "https://login.microsoftonline.com/" + ourDomain;
var authenticationContext = new AuthenticationContext(authority);
var graphResourceUri = "https://graph.windows.net";
var azureADApplicationClientId = "7718c738-0000-0000-0000-4382476f1c65";
var result = authenticationContext.AcquireToken(
graphResourceUri,
azureADApplicationClientId, new Uri("https://localhost"),
PromptBehavior.RefreshSession,
new UserIdentifier($"jdoe#{ourDomain}", UserIdentifierType.RequiredDisplayableId),
$"domain_hint={ourDomain}");
An MSOnline login window pops up, immediately redirects to our ADFS server at
https://ouradfs.abc.com/adfs/ls/wia?username=.......................
And then immediately closes since NTLM (Windows Integrated) authentication occurs and succeeds...and result contains a valid access token for the logged in Windows user on our abc.com domain.
Although this process doesn't require any clicks...it is still "interactive". I'd like to be able to leverage Windows Integrated authentication to programmatically obtain such an access token in a non-interactive environment (such as a Windows Service or Scheduled Task). This way I wouldn't have to embed Client Secrets in our Windows Services or Scheduled Tasks.
Is this possible?
UPDATE:
This is the line of code
var authenticationContext = new AuthenticationContext("https://login.microsoftonline.com/mycorpdev.onmicrosoft.com");
AuthenticationResult result = authenticationContext.AcquireToken(
"https://graph.windows.net",
nativeApplicationClientId,
new Uri("https://localhost"),
PromptBehavior.Never,
new UserIdentifier("jsmith#mycorp.com"), UserIdentifierType.RequiredDisplayableId), $"domain_hint=mycorp.com");
and the exact error:
Microsoft.IdentityModel.Clients.ActiveDirectory.AdalException occurred
ErrorCode=user_interaction_required
HResult=-2146233088
Message=user_interaction_required: One of two conditions was encountered: 1. The PromptBehavior.Never flag was passed, but the constraint could not be honored, because user interaction was required. 2. An error occurred during a silent web authentication that prevented the http authentication flow from completing in a short enough time frame
Source=Microsoft.IdentityModel.Clients.ActiveDirectory
StackTrace:
at Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext.RunAsyncTask[T](Task`1 task)
ANOTHER UPDATE:
This works (where the client id and tenant are the same as the user's home tenant)
var authenticationContext = new AuthenticationContext("https://login.microsoftonline.com/mycorp.onmicrosoft.com");
AuthenticationResult result = authenticationContext.AcquireToken(
"https://graph.windows.net",
nativeApplicationClientIdFromHomeTenantNotOtherTenant,
new Uri("https://localhost"),
PromptBehavior.Never,
new UserIdentifier("jsmith#mycorp.com"), UserIdentifierType.RequiredDisplayableId), $"domain_hint=mycorp.com");
UPDATE - Here is the capture from Fiddler
GET https://login.microsoftonline.com/mycorpdev.onmicrosoft.com/oauth2/authorize?resource=https%3A%2F%2Fgraph.windows.net&client_id=78ebfdee-8144-48f8-9a96-1bd5418c0492&response_type=code&redirect_uri=https%3A%2F%2Flocalhost%2F&login_hint=jsmith%40mycorp.COM&client-request-id=7a8878d4-2762-4784-9d29-6f49b147d474&prompt=attempt_none&x-client-SKU=.NET&x-client-Ver=2.19.0.0&x-client-CPU=x64&x-client-OS=Microsoft+Windows+NT+6.1.7601+Service+Pack+1&domain_hint=mycorpdev.onmicrosoft.com HTTP/1.1
Accept: */*
Accept-Language: en-US
UA-CPU: AMD64
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; Win64; x64; Trident/7.0; .NET CLR 2.0.50727; SLCC2; Media Center PC 6.0; Tablet PC 2.0; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET4.0C; .NET4.0E)
Host: login.microsoftonline.com
Connection: Keep-Alive
Cookie: ESTSAUTHPERSISTENT=AAABAAEAiL9Kn2Z27UubvWFPbm0gLfZQz8hXb5bXR-iThmkV-FLuLx102LOLAWrogj3rvf40Xl0xjZntMo0Kzvbo0x38Z2CpfCjtOwyyVpp1DWlxyyRPBbl4Z4da5pFuYjfCLPqExGUvo5gBoMdeQ-0MobfbSV2GQCHgbL1CFRjOu6YJZUEgnk7Vyls4rOlHGaqEGpzm5OeFQj3acldcvD9C4PX1gGsV-2g5GU8Frx3co4YzqYHMbhp6fgzf18sfgWaaG9caWj756P2oDvqe9qAlehXk51cA2AUacM2h-k2rtN8F341p7tnOFkNBzCj_E4z3bTnwHodimoXLiDlDWjFWkzAANyAA
HTTP/1.1 302 Found
Cache-Control: no-cache, no-store
Pragma: no-cache
Content-Type: text/html; charset=utf-8
Content-Encoding: gzip
Expires: -1
Location: https://localhost/?error=login_required&error_description=AADSTS50058%3a+User+account+identifier+is+not+provided.%0d%0aTrace+ID%3a+133f0405-eb3d-452d-a8b6-b6ba6267af7c%0d%0aCorrelation+ID%3a+7a8878d4-2762-4784-9d29-6f49b147d474%0d%0aTimestamp%3a+2016-02-21+04%3a54%3a07Z
Vary: Accept-Encoding
Server: Microsoft-IIS/8.5
x-ms-request-id: 133f0405-eb3d-452d-a8b6-b6ba6267af7c
client-request-id: 7a8878d4-2762-4784-9d29-6f49b147d474
x-ms-gateway-service-instanceid: ESTSFE_IN_420
X-Content-Type-Options: nosniff
Strict-Transport-Security: max-age=31536000; includeSubDomains
P3P: CP="DSP CUR OTPi IND OTRi ONL FIN"
Set-Cookie: flight-uxoptin=true; path=/; secure; HttpOnly
Set-Cookie: x-ms-gateway-slice=productionb; path=/; secure; HttpOnly
Set-Cookie: stsservicecookie=ests; path=/; secure; HttpOnly
X-Powered-By: ASP.NET
Date: Sun, 21 Feb 2016 04:54:05 GMT
Content-Length: 0
One more update...
If I try to use integrated auth (note it DOES try to redirect to our ADFS correctly...):
var authenticationContext = new AuthenticationContext(""https://login.microsoftonline.com/" + UserPrincipal.Current.UserPrincipalName.Split('#')[1]), false);
var nativeClientId = "00000000-0f32-4c38-bdb9-4ea5bd732c69";
var token = authenticationContext.AcquireTokenAsync(Constants.ReportingApplicationUri, nativeClientId, new UserCredential()).Result;
System.AggregateException occurred
HResult=-2146233088
Message=One or more errors occurred.
Source=mscorlib
StackTrace:
at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
:line 68
InnerException:
ErrorCode=federated_service_returned_error
HResult=-2146233088
Message=Federated service at https://ds1.mycorp.com/adfs/services/trust/2005/windowstransport returned error: The message with Action 'http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Issue' cannot be processed at the receiver, due to a ContractFilter mismatch at the EndpointDispatcher. This may be because of either a contract mismatch (mismatched Actions between sender and receiver) or a binding/security mismatch between the sender and the receiver. Check that sender and receiver have the same contract and the same binding (including security requirements, e.g. Message, Transport, None).
Source=Microsoft.IdentityModel.Clients.ActiveDirectory
StatusCode=500
StackTrace:
at Microsoft.IdentityModel.Clients.ActiveDirectory.WsTrustRequest.<SendRequestAsync>d__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.IdentityModel.Clients.ActiveDirectory.AcquireTokenNonInteractiveHandler.<PreTokenRequest>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 Microsoft.IdentityModel.Clients.ActiveDirectory.AcquireTokenHandlerBase.<RunAsync>d__0.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.Clients.ActiveDirectory.AuthenticationContext.<AcquireTokenCommonAsync>d__0.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.Clients.ActiveDirectory.AuthenticationContext.<AcquireTokenAsync>d__14.MoveNext()
InnerException:
HResult=-2146233079
Message=The remote server returned an error: (500) Internal Server Error.
Source=System
StackTrace:
at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic(IAsyncResult iar, Func`2 endFunction, Action`1 endAction, Task`1 promise, Boolean requiresSynchronization)
--- 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.Clients.ActiveDirectory.HttpWebRequestWrapper.<GetResponseSyncOrAsync>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 Microsoft.IdentityModel.Clients.ActiveDirectory.WsTrustRequest.<SendRequestAsync>d__1.MoveNext()
InnerException:
Sure. You can do it in 2 alternative ways.
Pass PromptBehavior.Never. That will use an invisible browser, making the operation 100% non interactive. This works both with Kerberos and with any other session type (eg cookies).
Use the AcquireToken overload which accepts a UserCredential. Pass to it an empty UserCredential, as in new UserCredential(). That will force the use of Kerberos authentication.
Related
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.
In interface of IApplicationService I have decorated one of my method as [HttpOptions]
When I do ajax from another domain, the method will be fired from the server side but I have got the below exception in Client-Side:
Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.
As This link described how to enable CORS in MVC core or WebApi in ASPNetBoilerplate but I have neither app.UseCors("AllowAll") nor services.AddMvc(); in ASP.Net MVC with ABP.
I am using https://aspnetboilerplate.com/.
Is there a way to enable it in ABP ?
Sample:
abp.services.fep.user.ping().done(function (data) {
console.log(data);
});
but the result:
General
Request URL:http://xxxx/wado1/api/services/fep/user/Ping
Request Method:OPTIONS
Status Code:200 OK
Remote Address:192.168.16.201:80
Referrer Policy:no-referrer-when-downgrade
Response Headers:
Access-Control-Allow-Origin:*
Cache-Control:private
Content-Length:129
Content-Type:application/json; charset=utf-8
Date:Mon, 12 Feb 2018 10:06:41 GMT
Server:Microsoft-IIS/10.0
Set-Cookie:Abp.Localization.CultureName=en-US; expires=Tue, 12-Feb-2019
10:06:33 GMT; path=/WADO1
Set-Cookie:.ASPXANONYMOUS=jE6RBHsyANH3AuPkKFlnusuKGyqfdikCJ5cJSo38xg-
pCqe8JnUOX3t0o2V6s0_aT3N0PLnw2XG9PRzCPIse3uLC60vS8l-
3H8Z_UP1lqCIyDunM9oxhxqKJOca1B4Nv5eQwaQ2; expires=Sun, 22-Apr-2018 20:46:33
GMT; path=/; HttpOnly
X-AspNet-Version:4.0.30319
X-Powered-By:ASP.NET
X-StackifyID:V1|80000cf1-0001-f700-b63f-84710c7967bb|
Request Headers
Accept:*/*
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.9
Access-Control-Request-Headers:content-type
Access-Control-Request-Method:POST
Cache-Control:no-cache
Connection:keep-alive
Host:xxxx
Origin:http://localhost
Pragma:no-cache
User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML,
like Gecko) Chrome/64.0.3282.140 Safari/537.36
When I create a new template from https://aspnetboilerplate.com with ASP.Net Core frame work I can see something like below in Startup file:
// Configure CORS for angular2 UI
services.AddCors(
options => options.AddPolicy(
_defaultCorsPolicyName,
builder => builder
.WithOrigins(
// App:CorsOrigins in appsettings.json can contain more than one address separated by comma.
_appConfiguration["App:CorsOrigins"]
.Split(",", StringSplitOptions.RemoveEmptyEntries)
.Select(o => o.RemovePostFix("/"))
.ToArray()
)
.AllowAnyHeader()
.AllowAnyMethod()
)
);
UPDATE1:
I add the below webapi config to enable CORS:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.EnableCors();
}
}
and register it :
public override void Initialize()
{
WebApiConfig.Register(GlobalConfiguration.Configuration);
}
but in client-side I got Error 500, after enabling Failed Request Tracing, I see the log trace and buffer error like:
{"message":"An error has occurred.","exceptionMessage":"There is an action Ping defined for api controller fep/user but with a different HTTP Verb. Request verb is POST. It should be Options","exceptionType":"Abp.AbpException","stackTrace":" at Abp.WebApi.Controllers.Dynamic.Selectors.AbpApiControllerActionSelector.GetActionDescriptorByActionName(HttpControllerContext controllerContext, DynamicApiControllerInfo controllerInfo, String actionName)\r\n at Abp.WebApi.Controllers.Dynamic.Selectors.AbpApiControllerActionSelector.SelectAction(HttpControllerContext controllerContext)\r\n at System.Web.Http.Cors.AttributeBasedPolicyProviderFactory.SelectAction(HttpRequestMessage request, IHttpRouteData routeData, HttpConfiguration config)\r\n at System.Web.Http.Cors.AttributeBasedPolicyProviderFactory.GetCorsPolicyProvider(HttpRequestMessage request)\r\n at System.Web.Http.Cors.CorsMessageHandler.d__10.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Cors.CorsMessageHandler.d__b.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Cors.CorsMessageHandler.d__0.MoveNext()"}
UPDATE2:
I enabled CORS by :
var cors = new EnableCorsAttribute(
origins: "*",
headers: "*",
methods: "*");
config.EnableCors(cors);
and register it in application_start but by this ajax with contentType:application/x-www-form-urlencoded" as #AlperEbicoglu posted in his answer method get fired in Back-End but entered DTO be null because it is JSON...
Abp set contentType to application/json automatically in abp.jquery.js file, for this reason(application/json) when I want run below code:
abp.services.fep.user.authenticate(box_in).done(function (data) {
console.log(data);
});
I got that mentioned exception in UPDATE1 section.
Why it can be called with application/x-www-form-urlencoded but with application/json exception raised (I see this in XML Tacer file in IIS).
I think 1 step remained two resolve this, any help would be truly appreciated.
Thanks in advance.
updated my answer....
You already succeeded in enabling CORS. Now you have a problem with preflight requests. I think you need to decorate your method as POST verb. Browser automatically sends preflight request if it needs.
and if you insist on making it OPTIONS. so you need to execute it with custom ajax like you can use JQuery ajax.
something like this:
$.ajax({
url: .....,
type: 'OPTIONS',
contentType: "application/x-www-form-urlencoded",
data: .......,
success: function (data, status) {
console.log("Success!!");
console.log(data);
console.log(status);
},
error: function (xhr, desc, err) {
console.log(xhr);
console.log("Desc: " + desc + "\nErr:" + err);
}
});
pls read this: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
Last time i had a similar requirement with abp i have addressed it with custom attribute instead of enablecors method like below:
public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(HttpActionExecutedContext filterContext)
{
if (filterContext.Response != null)
if (filterContext.Response.Headers != null)
filterContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");
base.OnActionExecuted(filterContext);
}
}
and then in WebApiModule:
Configuration.Modules.AbpWebApi().DynamicApiControllerBuilder
.ForAll<IApplicationService>(typeof(WebsiteApplicationModule).Assembly, "api")
.WithConventionalVerbs()
.WithFilters(new AllowCrossSiteJsonAttribute())
.Build();
if you still getting error regarding Access-Control-Allow-Headers try to add it also in response headers
based on this thread: Setting Access-Control-Allow-Origin in ASP.Net MVC - simplest possible method
I'm creating an ASP.NET Core 1.1 MVC web site, with OpenID authentication to Azure AD.
Authentication works fine locally on my dev machine. However, when I deploy it to the server, it throws an error after logging into the microsoft login redirect.
I'be been researching online for about 2 days, and have found similar issues, but nothing exactly like this.
My local dev box is windows 10, visual studio 2017.
The server I am deploying to is Server 2008R2, with the .net core server hosting runtime installed.
Here are the errors:
ERROR 2017-07-27 10:38:05,667 [4 ] on.OpenIdConnect.OpenIdConnectMiddleware - Exception occurred while processing message.
Microsoft.IdentityModel.Tokens.SecurityTokenInvalidSignatureException: IDX10503: Signature validation failed.
ERROR 2017-07-27 10:38:05,680 [4 ] e.Diagnostics.ExceptionHandlerMiddleware - An unhandled exception has occurred: Invalid non-ASCII or control character in header: 0x000D
System.InvalidOperationException: Invalid non-ASCII or control character in header: 0x000D
at Microsoft.AspNetCore.Server.Kestrel.Internal.Http.FrameHeaders.ThrowInvalidHeaderCharacter(Char ch)
at Microsoft.AspNetCore.Server.Kestrel.Internal.Http.FrameHeaders.ValidateHeaderCharacters(String headerCharacters)
at Microsoft.AspNetCore.Server.Kestrel.Internal.Http.FrameHeaders.ValidateHeaderCharacters(StringValues headerValues)
at Microsoft.AspNetCore.Server.Kestrel.Internal.Http.FrameResponseHeaders.SetValueFast(String key, StringValues value)
at Microsoft.AspNetCore.Server.Kestrel.Internal.Http.FrameHeaders.Microsoft.AspNetCore.Http.IHeaderDictionary.set_Item(String key, StringValues value)
at Microsoft.AspNetCore.Http.Internal.DefaultHttpResponse.Redirect(String location, Boolean permanent)
at FastInfo.Web.Startup.Startup.OnAuthenticationFailed(FailureContext context) in C:\SourceCode\Fast\FastInfo\src\FastInfo.Web\Startup\Startup.cs:line 168
at Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler1.<HandleRemoteCallbackAsync>d__6.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.Authentication.RemoteAuthenticationHandler1.d__5.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.Authentication.OpenIdConnect.OpenIdConnectHandler.d__15.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.Authentication.AuthenticationMiddleware1.<Invoke>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware1.d__18.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.Authentication.AuthenticationMiddleware1.<Invoke>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware1.d__18.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.Session.SessionMiddleware.d__9.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.AspNetCore.Session.SessionMiddleware.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.Diagnostics.ExceptionHandlerMiddleware.d__6.MoveNext()
I am possibly missing some module or extension for OpenID tokens to work on IIS 7.5?
token header:
{
"typ": "JWT",
"alg": "RS256",
"x5t": "VWVIc1WD1Tksbb301sasM5kOq5Q",
"kid": "VWVIc1WD1Tksbb301sasM5kOq5Q"
}
payload (edited):
{
"aud": "b0337ae2-2097-4dd3-be43-983fee4217bd",
"iss": "https://sts.windows.net/{i removed guid}/",
"iat": 1501263956,
"nbf": 1501263956,
"exp": 1501267856,
"aio": "Y2ZgYDD9/5YpiT9XXmCDXMn/EzzPGa3nMbxfudOgpnfDsZk7/QMA",
"amr": [
"pwd"
],
"c_hash": "02fpZ5B7FecFoRVdeJi6Qw",
"family_name": "mylastname",
"given_name": "Joe",
"ipaddr": "##.###.###.##",
"name": "Joe mylastname",
"nonce": "636368610551942171.ZTU5ZGZmZmQtZDgzNS00MTEyLWExZjAtNWI3MTA2NGJlN2RkYzY0OTdkZjctZTZkMy00OTk2LWIxNjgtZTlhMDkxNmY0MzFh",
"oid": "26945208-7b3f-45ed-9b40-f33b9d767071",
"platf": "3",
"roles": [
"Admin"
],
"sub": "y-sRfJAMdidDOedJeyr7kLhH8BCfkV_YCdyT1p2mOmk",
"tid": "{i removed guid}",
"unique_name": "jwashek#fastsolutions.com",
"upn": "jwashek#fastsolutions.com",
"ver": "1.0"
}
Thanks for any help,
Joe
Since AADB2C will redirect to an HTTPS page, the headers are not well managed and you get this error. Enforce the https on any website using B2C and you may solve this issue
The problem was the identity running the application pool. It didn't have enough rights, from when I've read and am thinking, not enough rights to access the cert.
For me the error occurs when I want to debug and the visual studio configuration is set to Release
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
I am using ELMAH's default configuration that was setup by NuGet pacakge manager. However, ELMAH does not provide any information about the line number of the offending code in my project. Instead, it provides stack trace of all the DotNet Framework assembly that is not written by me. This is not helpful at all. Here is a message that was generated by ELMAH. I remember that previous version of ELMAH provides the offending line number. Am I not setting it up correctly? If yes, how to configure it so that it log more about my code instead of DotNetFramework assembly code. Thanks.
System.NullReferenceException: Object reference not set to an instance of an object.
Generated: Wed, 01 May 2013 17:02:01 GMT
System.Web.HttpException (0x80004005): Error executing child request for handler 'System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerWrapper'. ---> System.Web.HttpUnhandledException (0x80004005): Exception of type 'System.Web.HttpUnhandledException' was thrown. ---> System.NullReferenceException: Object reference not set to an instance of an object.
at CMT.Layout_Minimal.Page_Load(Object sender, EventArgs e)
at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e)
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.HandleError(Exception e)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest()
at System.Web.UI.Page.ProcessRequest(HttpContext context)
at System.Web.Mvc.ViewPage.ProcessRequest(HttpContext context)
at ASP.views_home_index_aspx.ProcessRequest(HttpContext context) in c:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files\cmt\ac6025a2\ff8bb1d1\App_Web_3rkpnltk.1.cs:line 0
at System.Web.Mvc.HttpHandlerUtil.ServerExecuteHttpHandlerWrapper.<>c__DisplayClass4.<Wrap>b__3()
at System.Web.Mvc.HttpHandlerUtil.ServerExecuteHttpHandlerWrapper.Wrap[TResult](Func`1 func)
at System.Web.HttpServerUtility.ExecuteInternal(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage, VirtualPath path, VirtualPath filePath, String physPath, Exception error, String queryStringOverride)
at System.Web.HttpServerUtility.ExecuteInternal(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage, VirtualPath path, VirtualPath filePath, String physPath, Exception error, String queryStringOverride)
at System.Web.HttpServerUtility.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage)
at System.Web.HttpServerUtilityWrapper.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm)
at System.Web.Mvc.ViewPage.RenderView(ViewContext viewContext)
at System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context)
at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass1a.<InvokeActionResultWithFilters>b__17()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult)
at System.Web.Mvc.Controller.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar)
at System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar)
at System.Web.Mvc.MvcHandler.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Server Variables
Name Value
ALL_HTTP HTTP_CONNECTION:Keep-Alive HTTP_ACCEPT:application/x-ms-application, image/jpeg, application/xaml+xml, image/gif, image/pjpeg, application/x-ms-xbap, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */* HTTP_ACCEPT_ENCODING:gzip, deflate HTTP_ACCEPT_LANGUAGE:en-US HTTP_AUTHORIZATION:Negotiate TlRMTVNTUAADAAAAGAAYAJIAAABsAWwBqgAAAAoACgBYAAAAGAAYAGIAAAAYABgAegAAABAAEAAWAgAAFYKI4gYBsR0AAAAPBgj6Q45dj8Kyb2sqnLxvylYASABBADIAMABWAEgAQQBQAE8AUgBZAEEATgBHAEoAMgBQAE8AUgAtAFcAUwAxADEAMwAyADQANgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAC7nNsl/caJIJPkzgxg5U+NAQEAAAAAAACGkJOYjUbOAeFZUa2rwexmAAAAAAIABgBSADAAMQABABYAUgAwADEAUABPAFIAVwBFAEIAMAA1AAQAHAByADAAMQAuAG0AZQBkAC4AdgBhAC4AZwBvAHYAAwA0AFIAMAAxAFAATwBSAFcARQBCADAANQAuAHIAMAAxAC4AbQBlAGQALgB2AGEALgBnAG8AdgAFAAwAdgBhAC4AZwBvAHYABwAIAIaQk5iNRs4BBgAEAAIAAAAIADAAMAAAAAAAAAABAAAAACAAABkcBXJIYj/+piQK47PXZvDBf1Ob0I9TzBXq717N16HQCgAQAAAAAAAAAAAAAAAAAAAAAAAJAEgASABUAFQAUAAvAHMAdABhAGcAaQBuAGcALgBjAGwAaQBuAGEAcABwAHMALgB2ADIAMAAuAG0AZQBkAC4AdgBhAC4AZwBvAHYAAAAAAAAAAAAAAAAAg170Qmrhcms8BZfrbsdJiA== HTTP_COOKIE:ASP.NET_SessionId=4jxcuwvdata3hsccv1awzqw1; ASP.NET_SessionId=na1xooefe0ha1m54qctikdpv HTTP_HOST:xxxxxxx HTTP_USER_AGENT:Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.3; MS-RTC LM 8; .NET4.0C; .NET4.0E)
ALL_RAW Connection: Keep-Alive Accept: application/x-ms-application, image/jpeg, application/xaml+xml, image/gif, image/pjpeg, application/x-ms-xbap, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */* Accept-Encoding: gzip, deflate Accept-Language: en-US Authorization: Negotiate TlRMTVNTUAADAAAAGAAYAJIAAABsAWwBqgAAAAoACgBYAAAAGAAYAGIAAAAYABgAegAAABAAEAAWAgAAFYKI4gYBsR0AAAAPBgj6Q45dj8Kyb2sqnLxvylYASABBADIAMABWAEgAQQBQAE8AUgBZAEEATgBHAEoAMgBQAE8AUgAtAFcAUwAxADEAMwAyADQANgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAC7nNsl/caJIJPkzgxg5U+NAQEAAAAAAACGkJOYjUbOAeFZUa2rwexmAAAAAAIABgBSADAAMQABABYAUgAwADEAUABPAFIAVwBFAEIAMAA1AAQAHAByADAAMQAuAG0AZQBkAC4AdgBhAC4AZwBvAHYAAwA0AFIAMAAxAFAATwBSAFcARQBCADAANQAuAHIAMAAxAC4AbQBlAGQALgB2AGEALgBnAG8AdgAFAAwAdgBhAC4AZwBvAHYABwAIAIaQk5iNRs4BBgAEAAIAAAAIADAAMAAAAAAAAAABAAAAACAAABkcBXJIYj/+piQK47PXZvDBf1Ob0I9TzBXq717N16HQCgAQAAAAAAAAAAAAAAAAAAAAAAAJAEgASABUAFQAUAAvAHMAdABhAGcAaQBuAGcALgBjAGwAaQBuAGEAcABwAHMALgB2ADIAMAAuAG0AZQBkAC4AdgBhAC4AZwBvAHYAAAAAAAAAAAAAAAAAg170Qmrhcms8BZfrbsdJiA== Cookie: ASP.NET_SessionId=4jxcuwvdata3hsccv1awzqw1; ASP.NET_SessionId=na1xooefe0ha1m54qctikdpv Host: xxxxxxx User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.3; MS-RTC LM 8; .NET4.0C; .NET4.0E)
APPL_MD_PATH /LM/W3SVC/3/ROOT/CMT
APPL_PHYSICAL_PATH E:\xxxxx\CMT\
AUTH_TYPE Negotiate
AUTH_USER xxxxxxx
AUTH_PASSWORD *****
LOGON_USER xxxxxxx
REMOTE_USER xxxxxxx
CERT_COOKIE
CERT_FLAGS
CERT_ISSUER
CERT_KEYSIZE
CERT_SECRETKEYSIZE
CERT_SERIALNUMBER
CERT_SERVER_ISSUER
CERT_SERVER_SUBJECT
CERT_SUBJECT
CONTENT_LENGTH 0
CONTENT_TYPE
GATEWAY_INTERFACE CGI/1.1
HTTPS off
HTTPS_KEYSIZE
HTTPS_SECRETKEYSIZE
HTTPS_SERVER_ISSUER
HTTPS_SERVER_SUBJECT
INSTANCE_ID 3
INSTANCE_META_PATH /LM/W3SVC/3
LOCAL_ADDR 10.165.50.180
PATH_INFO /cmt/
PATH_TRANSLATED E:\xxxxxxx\
QUERY_STRING
REMOTE_ADDR 10.165.57.90
REMOTE_HOST 10.165.57.90
REMOTE_PORT 30998
REQUEST_METHOD GET
SCRIPT_NAME /cmt/
SERVER_NAME xxxxxxx
SERVER_PORT 80
SERVER_PORT_SECURE 0
SERVER_PROTOCOL HTTP/1.1
SERVER_SOFTWARE Microsoft-IIS/7.5
URL /cmt/
HTTP_CONNECTION Keep-Alive
HTTP_ACCEPT application/x-ms-application, image/jpeg, application/xaml+xml, image/gif, image/pjpeg, application/x-ms-xbap, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*
HTTP_ACCEPT_ENCODING gzip, deflate
HTTP_ACCEPT_LANGUAGE en-US
HTTP_AUTHORIZATION Negotiate TlRMTVNTUAADAAAAGAAYAJIAAABsAWwBqgAAAAoACgBYAAAAGAAYAGIAAAAYABgAegAAABAAEAAWAgAAFYKI4gYBsR0AAAAPBgj6Q45dj8Kyb2sqnLxvylYASABBADIAMABWAEgAQQBQAE8AUgBZAEEATgBHAEoAMgBQAE8AUgAtAFcAUwAxADEAMwAyADQANgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAC7nNsl/caJIJPkzgxg5U+NAQEAAAAAAACGkJOYjUbOAeFZUa2rwexmAAAAAAIABgBSADAAMQABABYAUgAwADEAUABPAFIAVwBFAEIAMAA1AAQAHAByADAAMQAuAG0AZQBkAC4AdgBhAC4AZwBvAHYAAwA0AFIAMAAxAFAATwBSAFcARQBCADAANQAuAHIAMAAxAC4AbQBlAGQALgB2AGEALgBnAG8AdgAFAAwAdgBhAC4AZwBvAHYABwAIAIaQk5iNRs4BBgAEAAIAAAAIADAAMAAAAAAAAAABAAAAACAAABkcBXJIYj/+piQK47PXZvDBf1Ob0I9TzBXq717N16HQCgAQAAAAAAAAAAAAAAAAAAAAAAAJAEgASABUAFQAUAAvAHMAdABhAGcAaQBuAGcALgBjAGwAaQBuAGEAcABwAHMALgB2ADIAMAAuAG0AZQBkAC4AdgBhAC4AZwBvAHYAAAAAAAAAAAAAAAAAg170Qmrhcms8BZfrbsdJiA==
HTTP_COOKIE ASP.NET_SessionId=4jxcuwvdata3hsccv1awzqw1; ASP.NET_SessionId=na1xooefe0ha1m54qctikdpv
HTTP_HOST xxxxxxx
HTTP_USER_AGENT Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.3; MS-RTC LM 8; .NET4.0C; .NET4.0E)
Powered by ELMAH, version 1.2.14706.955. Copyright (c) 2004, Atif Aziz. All rights reserved. Licensed under Apache License, Version 2.0.
I was having the same problem. It turns out that my Package/Publish Web settings in Properties had Exclude generated debug symbols checked for Release configuration
More details on this here
Looks like you need to include the debug symbols in your output. Also you can make sure the .pdb files are with the ELMAH dlls
You can set your project to use the debug symbols on the project properties
I had this as well, turning off pre-compilation made the line numbers appear