I'm having trouble configuring an AspNet Core 2.1 website to use Azure AD B2C for authentication. I've got this example to work, but when I try to adapt it to my own AD B2C tenant I get an invalid operation exception in the following code:
private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedContext context)
{
var clientCredential = new ClientCredential(context.Options.ClientSecret);
var userId = context.Principal.FindFirst(ClaimTypes.NameIdentifier).Value;
var tokenCache = new SessionTokenCache(context.HttpContext, userId);
var confidentialClientApplication = new ConfidentialClientApplication(
context.Options.ClientId,
context.Options.Authority,
_options.RedirectUri,
clientCredential,
tokenCache.GetInstance(),
null);
try
{
// this next line throws the exception
var authenticationResult = await confidentialClientApplication.AcquireTokenByAuthorizationCodeAsync(context.ProtocolMessage.Code, _options.ApiScopes.Split(' '));
context.HandleCodeRedemption(authenticationResult.AccessToken, authenticationResult.IdToken);
}
catch (Exception ex)
{
// TODO: Handle
throw;
}
}
The exception detail is:
Microsoft.Identity.Client.MsalServiceException HResult=0x80131500
Message=AADSTS50049: Unknown or invalid instance. Trace ID:
1391c6be-c8f7-4c05-a575-b4998f79d800 Correlation ID:
8b83a695-000f-44c2-99c1-d779725342da Timestamp: 2018-09-27 02:05:02Z
Source=Microsoft.Identity.Client StackTrace: at
Microsoft.Identity.Client.Internal.OAuth2.OAuth2Client.CreateErrorResponse(HttpResponse
response, RequestContext requestContext) at
Microsoft.Identity.Client.Internal.OAuth2.OAuth2Client.CreateResponse[T](HttpResponse
response, RequestContext requestContext, Boolean addCorrelationId)
at
Microsoft.Identity.Client.Internal.OAuth2.OAuth2Client.d__91.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
Microsoft.Identity.Client.Internal.OAuth2.OAuth2Client.<DiscoverAadInstanceAsync>d__7.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
Microsoft.Identity.Client.Internal.Instance.AadAuthority.<GetOpenIdConfigurationEndpointAsync>d__4.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
Microsoft.Identity.Client.Internal.Instance.Authority.<ResolveEndpointsAsync>d__45.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
Microsoft.Identity.Client.Internal.Requests.RequestBase.<ResolveAuthorityEndpointsAsync>d__37.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
Microsoft.Identity.Client.Internal.Requests.RequestBase.<PreTokenRequestAsync>d__36.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
Microsoft.Identity.Client.Internal.Requests.RequestBase.<RunAsync>d__33.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
Microsoft.Identity.Client.ConfidentialClientApplication.<AcquireTokenByAuthorizationCodeCommonAsync>d__17.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
Microsoft.Identity.Client.ConfidentialClientApplication.<AcquireTokenByAuthorizationCodeAsync>d__4.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at System.Runtime.CompilerServices.TaskAwaiter1.GetResult()
at
RideMonitorSite.AzureADB2COpenIdConnectOptionsConfigurator.d__5.MoveNext()
in
C:\Programming\RideMonitorServer\RideMonitorSite\AzureADB2COpenIDConnectOptionsConfigurator.cs:line
58
From examining the arguments passed to the function that throws the exception, I noticed that _options.ApiScopes is set to:
https://ridemonitor.onmicrosoft.com/api/user.read
which is as I configured it in the app. The tenant app configuration has the api url set to the "folder" of that Url (i.e., everything excluding the user.read)...but I'm not sure what other configuration I should be doing in the tenant app. How does it know what user.read means?
If someone can point me to some introductory material on how AD B2C should be set up, that would be appreciated. The stuff I've found so far presumes a level of knowledge that I clearly don't have.
If you are using the your-tenant-name.b2clogin.com domain with MSAL, then (at the time of this writing) you must:
Ensure Authority contains the /tfp path because this is how MSAL infers it is interacting with an Azure AD B2C tenant.
Set the ValidateAuthority to false.
Related
I am trying to experiment with the Microsoft Azure Cognitive Services Face Detection. I am doing something wrong. I am trying to use the C# SDK for face detection. I am getting the error below. I have no idea how to even debug this or what the error message is telling me. Its almost like something I have set is not coming through, but I am just guessing.
Microsoft.Azure.CognitiveServices.Vision.Face.Models.APIErrorException
HResult=0x80131500
Message=Operation returned an invalid status code 'BadRequest'
Source=Microsoft.Azure.CognitiveServices.Vision.Face
StackTrace:
at Microsoft.Azure.CognitiveServices.Vision.Face.FaceOperations.<DetectWithUrlWithHttpMessagesAsync>d__9.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
at Microsoft.Azure.CognitiveServices.Vision.Face.FaceOperationsExtensions.<DetectWithUrlAsync>d__4.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at BWD.ASPNET.Core.Services.FaceDetection.<DoWork>d__5.MoveNext() in
My code for making this call is:
string faceEndpoint = "https://eastus.api.cognitive.microsoft.com";
FaceAttributeType[] faceAttributes =
{ FaceAttributeType.Age, FaceAttributeType.Gender, FaceAttributeType.Hair,
FaceAttributeType.Smile, FaceAttributeType.Gender, FaceAttributeType.Emotion, FaceAttributeType.FacialHair,
FaceAttributeType.Accessories };
FaceClient faceClient = new FaceClient( new ApiKeyServiceClientCredentials(connString), new System.Net.Http.DelegatingHandler[] { });
faceClient.Endpoint = faceEndpoint;
var ctx = new BWDContext();
var pics = await (from p in ctx.Picture where p.DateOfFacial == null select p).ToListAsync();
foreach(var pic in pics)
{
if(Uri.IsWellFormedUriString(pic.PicFileUrl, UriKind.Absolute))
{
IList<DetectedFace> faceList =
await faceClient.Face.DetectWithUrlAsync(pic.PicFileUrl, true, true, faceAttributes); // error occurs here
.....on and on .......
I also tried making a rest call with fiddler, which does work. On the fiddler call, I just do a post to this url: https://eastus.api.cognitive.microsoft.com/face/v1.0/detect?returnFaceId=true&returnFaceLandmarks=false&returnFaceAttributes=age,gender,headPose,smile,facialHair,glasses,emotion,hair,makeup,occlusion,accessories,blur,exposure,noise
My header is:
User-Agent: Fiddler
Ocp-Apim-Subscription-Key: ....subscription key......
Content-Type: application/json
Host: eastus.api.cognitive.microsoft.com
Content-Length: 107
My post body is:
{ 'url': 'https://bwdpictures.blob.core.windows.net/bwdpictures/d916acdd-ab9f-429e-8b75-6d5f9206a9b4.jpg' }
I get a result back from the rest call in fiddler.
I'm sure that the problem is something with my code, but I have no idea what the issue is. If you have some suggestions, I would appreciate it.
TIA,
Wally
Bingo. The problem was that I had the Gender attribute in the face attributes twice. I just noticed it. When I took the second one out, the problem was solved. Sorry for the post.
I'm developing a web site with backend web api ASP.NET CORE 2.1 and frontend angular 6.
In this site I'm integrating upload of large files through web api with microsoft.azure.storage 9.3.2. I'm doing this chunking by blocks, and sending them from FE to an endpoint. Inside I do the following logic:
var container = CloudStorageAccount.Parse(key).CreateCloudBlobClient().GetContainerReference(containerName);
var result = await container.CreateIfNotExistsAsync();
if (result)
{
await container.SetPermissionsAsync(new BlobContainerPermissions
{
PublicAccess = BlobContainerPublicAccessType.Blob
});
}
BlockBlob = container.GetBlockBlobReference(blobName);
await fileUploadSession.BlockBlob.PutBlockAsync(block.BlockId, chunkStream, null);
And I have an exception here that says " The value for one of the HTTP headers is not in the correct format."
the stackTrace is:
at Microsoft.WindowsAzure.Storage.Core.Executor.Executor.d__4`1.MoveNext() in C:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\WindowsRuntime\Core\Executor\Executor.cs:line 316
--- 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.WindowsAzure.Storage.Blob.CloudBlockBlob.d__62.MoveNext() in C:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\WindowsRuntime\Blob\CloudBlockBlob.cs:line 1020
--- 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 vidiwin2Api.Controllers.VideosController.d__18.MoveNext() in D:\repos\vidiwin2api\vidiwin2Api\Controllers\VideosController.cs:line 469
The most amazing is that I had the same functionality in an older version, with BE web api on Framework 4.6 and microsoft.azure.storage 6.0.0, and this works!!
I have tested all kind of params in PutBlockAsync and allways the same exception.
Can anyone helps me please?
I had the same error because i forgot to reset the stream position to 0 before calling PutBlockAsync(). Try
chunkStream.Position = 0;
await fileUploadSession.BlockBlob.PutBlockAsync(block.BlockId, chunkStream, null);
Otherwise inspect the ExtendedErrorInformation property on the Exception. There you will find additional information about the wrong HTTP header.
I have a WebAPI in .NET Core 2.1 e I have using the RestSharp to access the API. When I send a request (POST), I always receive the below message in the response:
{System.Net.WebException: Error getting response stream (ReadAsync): ReceiveFailure Value cannot be null.Parameter name: src ---> System.ArgumentNullException: Value cannot be null.Parameter name: src at System.Net.HttpWebRequest+d__2411[T].MoveNext () [0x000ba] in <b78695579ed9422b8bc80218eeda782c>:0 --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x0003e] in <43dbbdc147f2482093d8409abb04c233>:0 at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in <43dbbdc147f2482093d8409abb04c233>:0 at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in <43dbbdc147f2482093d8409abb04c233>:0 at System.Runtime.CompilerServices.ConfiguredTaskAwaitable1+ConfiguredTaskAwaiter[TResult].GetResult () [0x00000] in <43dbbdc147f2482093d8409abb04c233>:0 at System.Net.WebResponseStream+d__48.MoveNext () [0x00253] in :0 --- End of inner exception stack trace --- at System.Net.WebConnectionStream.Read (System.Byte[] buffer, System.Int32 offset, System.Int32 count) [0x00077] in :0 at RestSharp.Extensions.MiscExtensions.ReadAsBytes (System.IO.Stream input) [0x0001f] in <4b0c1fc6e5a94482990701acc6dec8b3>:0 at RestSharp.Http.ProcessResponseStream (System.IO.Stream webResponseStream, RestSharp.HttpResponse response) [0x0000e] in <4b0c1fc6e5a94482990701acc6dec8b3>:0 at RestSharp.Http.ExtractResponseData (RestSharp.HttpResponse response, System.Net.HttpWebResponse webResponse) [0x0004c] in <4b0c1fc6e5a94482990701acc6dec8b3>:0 at RestSharp.Http+<>c__DisplayClass20_0.b__0 (System.Net.HttpWebResponse webResponse) [0x00001] in <4b0c1fc6e5a94482990701acc6dec8b3>:0 at RestSharp.Http.GetRawResponseAsync (System.IAsyncResult result, System.Action1[T] callback) [0x00050] in <4b0c1fc6e5a94482990701acc6dec8b3>:0 at RestSharp.Http.ResponseCallback (System.IAsyncResult result, System.Action1[T] callback) [0x0005a] in <4b0c1fc6e5a94482990701acc6dec8b3>:0 }
The previous version of my service (.NET Framework 4.7) was working, but my new version is not. I checked the URL and that is okay, and the service is working on Swagger and Postman, and I have the SSL certificate configured on the server, but in the App I continue receiving such message.
My service is hosted on Microsoft Azure.
Does anyone any idea to help me?
Ok. I resolved.
I had the below code:
IRestRequest request = new RestRequest(method, Method.POST);
request.AddParameter("SampleKey", "SampleValue");
I donĀ“t know why it was working with a .Net Framework WebApi, but is not working with a .Net Core WebApi.
I could resolve using the below code:
IRestRequest request = new RestRequest(method, Method.POST);
request.AddJsonBody(objBody);
With the new method, the RestSharp is responsible to serialize my object.
It's working right now.
I have a .net core 2.0 app which uses IdentityServer 4. it works perfectly in development mode. then I published it for production mode and tested. when I click a (that action has a method to generated accesstoken) link I got an error like below,
An unhandled exception has occurred: Malformed URL
then error occurs here in production(Release) mode:
var disco = await IdentityModel.Client.DiscoveryClient.GetAsync(_configuration.GetSection("Settings").GetSection("DiscoveryClient").Value);
above DiscoveryClient is http not https
here is the full description of the error ..
Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware[0]
An unhandled exception has occurred: Malformed URL
System.InvalidOperationException: Malformed URL
at IdentityModel.Client.DiscoveryClient.ParseUrl(String input)
at IdentityModel.Client.DiscoveryClient..ctor(String authority, HttpMessageHandler innerHandler)
at IdentityModel.Client.DiscoveryClient.<GetAsync>d__1.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 System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
is this because 'https'. I have no idea what is happening.hope your help with this.
This is a pretty old post, but it still might help someone. I had this exact same issue, only that the URL that I was passing in was perfectly fine. The problem on my side was that the IdentityServer Authority URL was misconfigured, causing it to throw the same exception.
Here is code snippet from DiscoveryClient's ParseUrl showing when it throws that exception:
public static DiscoveryEndpoint ParseUrl(string input)
{
var success = Uri.TryCreate(input, UriKind.Absolute, out var uri);
if (success == false)
{
throw new InvalidOperationException("Malformed URL");
}
if (!DiscoveryEndpoint.IsValidScheme(uri))
{
throw new InvalidOperationException("Malformed URL");
}
Here is the code for DiscoveryEndpoint's IsValidScheme method:
public static bool IsValidScheme(Uri url)
{
if (string.Equals(url.Scheme, "http", StringComparison.OrdinalIgnoreCase) ||
string.Equals(url.Scheme, "https", StringComparison.OrdinalIgnoreCase))
{
return true;
}
return false;
}
Based on this the exception is not thrown because the url is using http.
Try calling
new Uri(_configuration.GetSection("Settings").GetSection("DiscoveryClient").Value, UriKind.Absolute)
before your call to 'IdentityModel.Client.DiscoveryClient.GetAsync' so that you can see what exception is thrown by the Uri constructor.
I am trying out the Azure Mobile app and the recently released SDKs
https://azure.microsoft.com/en-us/blog/azure-mobile-apps-november-2015-update/
I created the service and the starter Todo app was working fine. I then added facebook authentication and that worked too. I also wanted to get some additional FB info from the service , so based on a solution and the sample app on github , I added a new api
https://github.com/Azure/azure-mobile-apps-net-server/blob/2d2901ed5207f0ba6698660eb4ee568a63f18581/samples/SampleApp/Controllers/SecuredController.cs
Server side code
public class AuthenticationController : ApiController
{
[Authorize]
public async Task<JObject> GetIdentity()
{
FacebookCredentials fb = await this.User.GetAppServiceIdentityAsync<FacebookCredentials>(this.Request);
var result = new JObject();
if (fb != null)
{
var accessToken = fb.AccessToken;
result.Add("facebook", await GetProviderInfo("https://graph.facebook.com/me?access_token=" + accessToken));
}
return result;
}
private async Task<JToken> GetProviderInfo(string url)
{
var c = new HttpClient();
var resp = await c.GetAsync(url);
resp.EnsureSuccessStatusCode();
return JToken.Parse(await resp.Content.ReadAsStringAsync());
}
}
Client Side Code in Android project
var user = await TodoItemManager.Instance.ClientInstance.LoginAsync(Forms.Context, MobileServiceAuthenticationProvider.Facebook);
var info = await TodoItemManager.Instance.ClientInstance.InvokeApiAsync("GetIdentity", null, HttpMethod.Get, null);
The LoginAsync succeeds and I get the UserId and Token, but InvokeApiAsync fails with following exception
Microsoft.WindowsAzure.MobileServices.MobileServiceInvalidOperationException: The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.
at Microsoft.WindowsAzure.MobileServices.MobileServiceHttpClient+<ThrowInvalidResponse>d__18.MoveNext () [0x0022f] in <filename unknown>:0
--- End of stack trace from previous location where exception was thrown ---
11-26 19:09:10.897 I/mono-stdout( 3514): at Microsoft.WindowsAzure.MobileServices.MobileServiceHttpClient+<ThrowInvalidResponse>d__18.MoveNext () [0x0022f] in <filename unknown>:0
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in /Users/builder/data/lanes/2098/3efa14c4/source/mono/external/referencesource/mscorlib/system/runtime/exceptionservices/exceptionservicescommon.cs:143
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x00047] in /Users/builder/data/lanes/2098/3efa14c4/source/mono/external/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:201
11-26 19:09:10.898 I/mono-stdout( 3514): --- End of stack trace from previous location where exception was thrown ---
11-26 19:09:10.898 I/mono-stdout( 3514): at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in /Users/builder/data/lanes/2098/3efa14c4/source/mono/external/referencesource/mscorlib/system/runtime/exceptionservices/exceptionservicescommon.cs:143
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x0002e] in /Users/builder/data/lanes/2098/3efa14c4/source/mono/external/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:170
11-26 19:09:10.899 I/mono-stdout( 3514): at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x00047] in /Users/builder/data/lanes/2098/3efa14c4/source/mono/external/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:201
11-26 19:09:10.900 I/mono-stdout( 3514): at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x0002e] in /Users/builder/data/lanes/2098/3efa14c4/source/mono/external/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:170
at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x0000b] in /Users/builder/data/lanes/2098/3efa14c4/source/mono/external/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:142
at System.Runtime.CompilerServices.TaskAwaiter.GetResult () [0x00000] in /Users/builder/data/lanes/2098/3efa14c4/source/mono/external/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:124
at Microsoft.WindowsAzure.MobileServices.MobileServiceHttpClient+<SendRequestAsync>d__1d.MoveNext () [0x0010d] in <filename unknown>:0
What am I missing or doing wrong?
Thanks in advance..
I had a similar error in my project, using the new Azure App Service sample projects. I was simply trying to retrieve data from an Azure db using my own model classes, not doing authentication like you.
Here's the error:
Microsoft.WindowsAzure.MobileServices.MobileServiceInvalidOperationException:
The resource you are looking for has been removed, had its name
changed, or is temporarily unavailable.
Turns out, in my mobile server project, I had a model defined as CorporateEvent, and in my client project, I had the same model defined as CorporateEventModel. Once I renamed the model in my client project to CorporateEvent, the error went away and I was able to access the database.
Hope that helps.