Code Monkey home page Code Monkey logo

active-directory-b2c-dotnetcore-webapp's Introduction

ASP.NET Core MVC web application that performs identity management with Azure AD B2C

There's a newer version of this sample taking advantage of the Microsoft identity platform

Check it out the B2C variations of the ASP.NET Core web app incremental tutorial:

If you really need to access this sample, you can navigate to the master branch, but please know that it's no longer supported.

active-directory-b2c-dotnetcore-webapp's People

Contributors

acomsmpbot avatar adrianjsclark avatar aprilspeight avatar bgavrilms avatar danieldobalian avatar danroth27 avatar dstrockis avatar gsacavdm avatar himadrinath avatar jennyf19 avatar jmprieur avatar lmaslanka avatar parakhj avatar supernova-eng avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

active-directory-b2c-dotnetcore-webapp's Issues

Sample works in 1.1 branch but not 2.0 branch (null MSAL token)

The sample works perfectly in core 1.1 but in the 2.0 branch it doesn't.

The

public async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedContext context)

is never hit.

All I've been trying for the last year is to get a stupid token with MSAL. I thought we were close here.

How on earth can I get an MSAL token for my B2C API in .net core 2.0?

Error from RemoteAuthentication: Message contains error: 'redirect_uri_mismatch', error_description: 'AADB2C90006: The redirect URI 'http://b2.95e4700435c54427a457.northeurope.aksapp.io/signin-oidc' provided in the request is not registered for the client id 'eb201049-e7b1-4227-9a7c-5bb259261d37'. Correlation ID: 8f75359e-009f-44e3-b537-3f85f58cdd9c

Trying to run b2c app .net core 2.1 ,followed the guide.
but am keep getting the this error : Error from RemoteAuthentication: Message contains error: 'redirect_uri_mismatch', error_description: 'AADB2C90006: The redirect URI 'http://b2.95e4700435c54427a457.northeurope.aksapp.io/signin-oidc' provided in the request is not registered for the client id 'eb201049-e7b1-4227-9a7c-5bb259261d37'.
Correlation ID: 8f75359e-009f-44e3-b537-3f85f58cdd9c

seems like we are redirecting to http instead of https.

my reply url in AAD is : https://b2.95e4700435c54427a457.northeurope.aksapp.io/signin-oidc and not http

full debug log :

fail: Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler[12]
Message contains error: 'redirect_uri_mismatch', error_description: 'AADB2C90006: The redirect URI 'http://b2.95e4700435c54427a457.northeurope.aksapp.io/signin-oidc' provided in the request is not registered for the client id 'eb201049-e7b1-4227-9a7c-5bb259261d37'.
Correlation ID: 8f75359e-009f-44e3-b537-3f85f58cdd9c
Timestamp: 2019-01-01 12:23:03Z
', error_uri: 'error_uri is null'.
info: Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler[4]
Error from RemoteAuthentication: Message contains error: 'redirect_uri_mismatch', error_description: 'AADB2C90006: The redirect URI 'http://b2.95e4700435c54427a457.northeurope.aksapp.io/signin-oidc' provided in the request is not registered for the client id 'eb201049-e7b1-4227-9a7c-5bb259261d37'.
Correlation ID: 8f75359e-009f-44e3-b537-3f85f58cdd9c
Timestamp: 2019-01-01 12:23:03Z
', error_uri: 'error_uri is null'..
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 0.7341ms 302
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Request starting HTTP/1.1 GET http://b2.95e4700435c54427a457.northeurope.aksapp.io/AzureADB2C/Account/Error
info: Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker[3]
Route matched with {page = "/Account/Error", area = "AzureADB2C", action = "", controller = ""}. Executing page /Account/Error
info: Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker[101]
Executing handler method Microsoft.AspNetCore.Authentication.AzureADB2C.UI.Internal.ErrorModel.OnGet with arguments ((null)) - ModelState is Valid
info: Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker[102]
Executed handler method OnGet, returned result .
info: Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker[103]
Executing an implicit handler method - ModelState is Valid
info: Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker[104]
Executed an implicit handler method, returned result Microsoft.AspNetCore.Mvc.RazorPages.PageResult.
info: Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker[4]
Executed page /Account/Error in 0.737ms
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 0.9807ms 200 text/html; charset=utf-8
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Request starting HTTP/1.1 GET http://b2.95e4700435c54427a457.northeurope.aksapp.io/lib/bootstrap/dist/css/bootstrap.css
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Request starting HTTP/1.1 GET http://b2.95e4700435c54427a457.northeurope.aksapp.io/lib/jquery/dist/jquery.js
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Request starting HTTP/1.1 GET http://b2.95e4700435c54427a457.northeurope.aksapp.io/css/site.css
info: Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware[2]
Sending file. Request path: '/css/site.css'. Physical path: '/app/wwwroot/css/site.css'
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 0.2196ms 200 text/css
info: Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware[2]
Sending file. Request path: '/lib/bootstrap/dist/css/bootstrap.css'. Physical path: '/app/wwwroot/lib/bootstrap/dist/css/bootstrap.css'
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 3.5544ms 200 text/css
info: Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware[2]
Sending file. Request path: '/lib/jquery/dist/jquery.js'. Physical path: '/app/wwwroot/lib/jquery/dist/jquery.js'
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 5.816ms 200 application/javascript
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Request starting HTTP/1.1 GET http://b2.95e4700435c54427a457.northeurope.aksapp.io/lib/bootstrap/dist/js/bootstrap.js
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Request starting HTTP/1.1 GET http://b2.95e4700435c54427a457.northeurope.aksapp.io/js/site.js?v=dLGP40S79Xnx6GqUthRF6NWvjvhQ1nOvdVSwaNcgG18
info: Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware[2]
Sending file. Request path: '/js/site.js'. Physical path: '/app/wwwroot/js/site.js'
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 0.2069ms 200 application/javascript
info: Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware[2]
Sending file. Request path: '/lib/bootstrap/dist/js/bootstrap.js'. Physical path: '/app/wwwroot/lib/bootstrap/dist/js/bootstrap.js'
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 1.8534ms 200 application/javascript

help appriciated

context.failure.message

System.InvalidOperationException occurred
HResult=0x80131509
Message=Invalid non-ASCII or control character in header: 0x000A
Source=
StackTrace:
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 WebApp_OpenIDConnect_DotNet.OpenIdConnectOptionsSetup.OnRemoteFailure(FailureContext context) in C:\Users\paul\Dropbox\Visual Studio\Tests\active-directory-b2c-dotnetcore-webapp-master\WebApp-OpenIDConnect-DotNet\OpenIdConnectOptionsSetup.cs:line 67
at Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler`1.d__6.MoveNext()

"IDX10223: Lifetime validation failed. The token is expired.\nValidTo: '05/03/2017 03:12:15'\nCurrent time: '05/03/2017 13:23:11'."

Hangs during high request loads

Thank you for this great sample. Has this code been tested with production loads? It would be a good idea to update the sample code to include this kind of lock handling below so if something goes wrong with entering a lock the exiting of the lock does not get attempted, further degrading performance.

var lockIsHeld = false;
try {
try {
}
finally {
rwl.EnterReadLock();
lockIsHeld = true;
}

// Do work here
}
finally {
if (lockIsHeld) {
rwl.ExitReadLock();
}
}

Get access token

Hi, thanks for example - thats the only example of ASP Core and Azure B2C in the world)

While using MVC5 and OWIN there was an opportunity to get Access token using ClaimsPrincipal.Current.
Articles: 1, 2

According to this article, 2, we could

SaveSigninToken = true //important to save the token in boostrapcontext

and get access token

ClaimsPrincipal.Current.Identities.First().BootstrapContext as System.IdentityModel.Tokens.BootstrapContext;)

to use in in requests to some WebApis from MVC application.

Unfortunately, in your app (I use Core 1.0.1 version) ClaimsPrincipal.Current is null.

I know I can make a POST request using ClientSecret(3) to get AccessToken, but I am pretty sure this approach is wrong.

What is the correct way to get acces token from B2C in Core application so I could pass it as a bearer to some other web apis?

AcquireTokenSilent Returns Session Has Expired After Recompile

After recompiling the app the acquireTokenSilent function returns a session expired message. This is problematic during the development process because the session gets cleared after every recompile forcing me to login again. Is there a better way to handle this login session during the development cycle? Ideally, I would like to log in to the front end once, rebuild my app whenever I make a change to the server side code, and refresh my browser to see the changes without having to log in again.

Microsoft.Identity.Client

The Microsoft.Identity.Client package is a preview package and contains a number of classes that have duplicates in the Microsoft.IdentityModel.Client package/namespace; when/will this be corrected or is Microsoft.Identity.Client preview obsolete ?

Getting AADB2C90081 error

Hi,

I followed the steps and after successful authentication i am getting following error; i see ClientSecret specified in the application.json file
AADB2C90081: The specified client_secret does not match the expected value for this client. Please correct the client_secret and try again.
Correlation ID: e1d3a273-1e64-40ab-bcb2-53768f5f5d5b
Timestamp: 2017-05-22 17:45:45Z

Need help with Configuration

I can run the code from this sample and get everything working in chrome and firefox.. I try and use my azure b2c and web app and api and nothing works, even though the code is the same minus the appSettings. Can we get screen shots posted of all the actual Azure configuration and setup.. I have followed the steps in the read me and no luck. i have no clue what could be missing at this point. Any help would be great.. a simple azure b2c setup is now taking 5 days?? this can not be the case else no one would be using it.

Also how has anyone handled all the issues with Azure and self signed certs?

Authorization per policy

The sample should show how to use ASP.NET Core's authorization policies to work with B2C's journeys to specify that specific policies are required for certain authorization.

That will enable things like step-up to MFA by using an attribute like Authorize(Policy="mfa"), and have it automatically redirect to the MFA journey to do the step-up.

SignedOut Callback not invoked with exising samples

When using multiple policies and the non-default values for CallbackPath on the OIDC middlewhere, at least with version 1.1, it seems like you also need to specify overrides of SignedOutCallbackPath and RemoteSignOutPath for the post logout callbacks to be invoked correctly:

I currently have the following in my CreateOptionsFromPolicy, which seems to work.

                CallbackPath = new PathString($"/{policy}"),
                SignedOutCallbackPath = new PathString($"/signout-callback-{policy}"),
                RemoteSignOutPath = new PathString($"/signout-{policy}"),

Fail to invoke B2C workflow

Hi Folks,

No matter how I configure the cloned app (fabrikam) or my own tenancy, the sample fails to direct to the login.microsoft.com/[xxxxxxx] uri. Is there something in this sample that requires updating? I'd be glad to create a PR, but I'm not sure where to determine where the issue with this sample is. Thanks!

Asp.Net Core 2 - get these build errors when incorporating into my own Web API

hi

Does this need updating to work in ASP.NET Core 2.0 Web API, taking the code into my own solution to protect an API which will eventually be called by a Web App, the Azure B2C is all setup and correct. In the OpenIdConnectOptionsSetup class i get the following errors flagged up

image

Do i need to reference IdentityClient still ?

cheers

MSAL does not return a token

Hi, I've run the sample, exchanging my values into the settings.

Everything works fine, I can log in, see claims etc. my problem is I want to able to use the Graph API to add local accounts.

The only problem so far, that I've been banging my head against a wall with for the last 48 hours is I CANNOT get a token with MSAL.

Every single time it returns null, not an error btw and there is a value for the IdToken on line 95 of OpenIdConnectOptionsSetup.cs

context.HandleCodeRedemption(result.AccessToken, result.IdToken);

Whilst I am new to Azure, this makes no sense. I've tried varying scopes as I'm not 100% on those either and no combination gets me anywhere! I suspect it's with the setup.

I've created my B2C tenant, added the app with the reply url, created and added my secret and created my policys and updated VS with these and it does work like I said I can log in and access everything...

Any help would be greatly appreciated as the documentation for an Azure product is amazingly poor. Most guides use Azure AD not B2C and most assume you've been using this for years...

sample with my Azure Active Directory b2c tenant

I ran this example with below ones and it works fine
"ClientId": "90c0fe63-bcf2-44d5-8fb7-b8bbc0b29dc6",
"Tenant": "fabrikamb2c.onmicrosoft.com",

But I created my own b2c tenant, it doesn't work. I also try https://github.com/AzureADQuickStarts/B2C-WebApp-OpenIdConnect-DotNet with my own b2c tenant and it's ok. So are there any magic tips in Azure Active Directory b2c settings to fix in ASP.NET CORE? It's too wired. Does someone give hints?

Thank you.

Ark

Login page

Hi. I'm new to Azure and OpenIdConnect. I download the web app, run it from Visual Studio 2017 and got to the login page (https://login.microsoftonline.com/fabrikamb2c.onmicrosoft.com/B2C_1_SUSI/api....)

Then, I created an Azure AD B2C web app. I updated the web app's appsettings.json as shown below.
I published the web app to Azure. The web app's url is https://the-real-name.azurewebsites.net.
When I go to https://the-real-name.azurewebsites.net, it redirects me to https://login.microsoftonline.com/te/mytenantxyz.onmicrosoft.com/b2c_1_siupin/oauth2/v2.0/authorize?client_id=.......
But the browser window was then just blank. After some seconds, it redirects me back to https://the-real-name.azurewebsites.net. I did not see the login page. Somebody please help me.

appsettings.json
{
"Authentication": {
"AzureAdB2C": {
"ClientId": "my-client-id",
"Tenant": "mytenantxyz.onmicrosoft.com",
"SignUpSignInPolicyId": "B2C_1_SiUpIn",
"ResetPasswordPolicyId": "B2C_1_SSPR",
"EditProfilePolicyId": "B2C_1_SiPe",
"RedirectUri": "https://the-real-name.azurewebsites.net",
"ClientSecret": "my-clientSecret",
//"ApiUrl": "https://taskservice123456.azurewebsites.net/",
//"ApiScopes": "https://mytenantxyz.onmicrosoft.com/TaskServiceAPIDemo/user_impersonation"
}
},
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
}
}

Show how to execute additional policies once the user is already logged in

If you try to invoke any policy via the ChallengeAsync call after the user is already signed in, you might find that ASP.NET redirects to the "Forbidden" path of the underlying cookie middleware, instead of redirecting to Azure AD B2C.

To get the desired behavior, change the ChallengeAsync call to the following:

await HttpContext.Authentication.ChallengeAsync(Startup.ProfilePolicyId.ToLower(), authenticationProperties, Microsoft.AspNetCore.Http.Features.Authentication.ChallengeBehavior.Unauthorized);

See https://github.com/aspnet/Security/blob/dev/src/Microsoft.AspNetCore.Authentication/AuthenticationHandler.cs#L346 for detail.

I find about non-ASCII character bug

I use branch 2.0,I use Chinese operating system environment and get a error.
this is error in OpenIdConnectOptionsSetup.cs Line 98
context.Response.Redirect("/Home/Error?message=" + context.Failure.Message);

this is error message:

An unhandled exception occurred while processing the request.
InvalidOperationException: Invalid non-ASCII or control character in header: 0x000D
Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.FrameHeaders.ThrowInvalidHeaderCharacter(char ch)

This is the error details:

InvalidOperationException: Invalid non-ASCII or control character in header: 0x000D
Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.FrameHeaders.ThrowInvalidHeaderCharacter(char ch)
Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.FrameHeaders.ValidateHeaderCharacters(string headerCharacters)
Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.FrameHeaders.ValidateHeaderCharacters(StringValues headerValues)
Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.FrameResponseHeaders.SetValueFast(string key, StringValues value)
Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.FrameHeaders.Microsoft.AspNetCore.Http.IHeaderDictionary.set_Item(string key, StringValues value)
Microsoft.AspNetCore.Http.Internal.DefaultHttpResponse.Redirect(string location, bool permanent)
Microsoft.AspNetCore.Http.HttpResponse.Redirect(string location)
Zop.Web.AzureAdB2CAuthenticationBuilderExtensions+OpenIdConnectOptionsSetup.OnRemoteFailure(RemoteFailureContext context) in OpenIdConnectOptionsSetup.cs
+
context.Response.Redirect("/Home/Error?message=" + context.Failure.Message);
Microsoft.AspNetCore.Authentication.RemoteAuthenticationEvents.RemoteFailure(RemoteFailureContext context)
Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler+d__12.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter.GetResult()
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware+d__6.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Session.SessionMiddleware+d__9.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
Microsoft.AspNetCore.Session.SessionMiddleware+d__9.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware+d__7.MoveNext()

AzureAdB2COptions.RedirectUri not working

Is it the intent of this code forRedirectUri property on the AzureAdB2COptions class (set in my appsettings.json) to end up the redirect_uri= querystring parameter of the /te/[tenant]/[policy]/oauth2/v2.0/authorize? call?

Because it sure doesn't.
It's ignoring it.

My RedirectUri is set to http://localhost:3456/app/signin-oidc, but what gets sent in that call is &redirect_uri=http%3A%2F%2Flocalhost%3A3456%2Fsignin-oidc...
as in, conspicuously missing the /app part. Which is real important.

So I tried just putting random things into that property and confirmed it's not using it at all, it seems to just be sending the origin server + /signin-oidc no matter WHAT is in the RedirectUri!

Is there somewhere extra this needs to be assigned that this sample code is missing, or is it just not for what I thought it was?

And if the latter, does that mean that this sample just doesn't work if it's not serving at the server root?

PostLogoutRedirectUri / RedirectUri

RedirectUri = Configuration["AzureAD:RedirectUri"]; in Startup.cs refers to AzureAD:RedirectUri from config.json, however config.json does not contain AzureAD:RedirectUri. only a AzureAD:PostLogoutRedirectUri

Invalid non-ASCII or control character in header: 0x000D exception

Tested on: Visual Studio 2017 for Mac

The sample runs fine out of the box with the pre-configured settings. I can create accounts, call the API path, forget password, and sign out.

I then tried to configure my own app. The sign up page worked fine, my custom policy was picked up. However, I encounter the following exception when it tries to go back to http://localhost:5000/signin-oidc

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 WebApp_OpenIDConnect_DotNet.OpenIdConnectOptionsSetup.OnRemoteFailure(FailureContext context) in /Users/zemien/Projects/active-directory-b2c-dotnetcore-webapp/WebApp-OpenIDConnect-DotNet/OpenIdConnectOptionsSetup.cs:line 76
   at Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler`1.<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.RemoteAuthenticationHandler`1.<HandleRequestAsync>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.<HandleRequestAsync>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.AuthenticationMiddleware`1.<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.AuthenticationMiddleware`1.<Invoke>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.AuthenticationMiddleware`1.<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.AuthenticationMiddleware`1.<Invoke>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.<Invoke>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.<Invoke>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.DeveloperExceptionPageMiddleware.<Invoke>d__7.MoveNext()

Any advice? Thank you!

Is it possible to run this code on VS for Mac?

I have the code running fine on VS for Windows but have been trying it on VS for Mac, without altering the code, with no luck. Is Windows (IIS) a requirement?

The website loads fine but below is what I see when I click on 'sign in".

screen shot 2017-05-20 at 11 11 37 pm

It doesn't seem to redirect to the usual Microsoft login url.

screen shot 2017-05-20 at 11 12 04 pm

Error : InvalidOperationException: No authentication handler is configured to handle the scheme: b2c_1_org_b2c_global_signin

In this sample app there is a Sign-in button. I am able to Sign-in successfully by clicking Sign-In button by providing my Azure B2C Tenant and registering the application in the tenant.

In another app, I want to authenticate without the Sign-In button being clicked i.e. right when I open the URL, I get redirected first to the Azure B2C AD login page, and after successful validation of credentials, I should be able to see the home screen.

So, what I did was from the URL mentioned from the article, I copied the SiginIn() method as:

public async Task<IActionResult> Index()
{
    await SignIn();

    await GetDataAsync();
}

I get an error message on running the application as : InvalidOperationException: No authentication handler is configured to handle the scheme: b2c_1_org_b2c_global_signin

Please advise how can I authenticate directly without the signin button. Previously with MVC5, I have successfully done this where I used [Authorize] attribute on the Controller class.

Having Trouble Reproducing Demo

I've followed the steps as best I could but I'm having trouble with Step #4. I'm afraid my node.js just isn't good enough to translate. Is there an MVC version of the protected API somewhere?
It'd be real handy if there was a .net core version of the API part of this demo in the repository.

How to debug mis-configured setup?

I have a working ASP.NET MVC application that uses Azure B2C and I'm trying to make an ASP.NET Core app that uses the same tenant with no success.

The directory/policy information is likely to be correct since I copied it from the working setup but the problem I get is that I am not presented with my login screen.

What I notice is that the authentication urls are different in the MVC and .NET Core apps i.e. the MVC app (and the policy tryout) is pointing at

https://login.microsoftonline.com/{tenant}/oauth2/v2.0/authorize?p={Policy}...

whereas the .NET Core app goes to

https://login.microsoftonline.com/te/{tenant}/{policy}/oauth2/v2.0/authorize?...&x-client-ver=2.1.4.0

it comes back with a 200 from the MS site but doesn't present a login screen. I've tried adding handlers on all the other OpenIdConnect events but I receive no events.

I also get the same behaviour if I drop my tenant/policy information into the sample app, whereas the OOB I get a login screen

Ideas?

User.Identity.Name is null and HttpContext.User.Claims is empty

Hi,

I'm trying to implement this into my app (i.e. aspnetcore 2.2 and Azure AD). I can login to the app via Azure AD fine.

I have implemented OnSecurityTokenValidated so that i can check that I'm receiving token and claims correctly, which is the case.

However, for some reason, I'm receiving a blank User.Identity (although it is not null). This means there are no claims and Name property is null.

image

It looks to me that somehow the HttpContext is not being set correctly with this data. However, where should this be happening? I checked the code in this repository and it's not clear what copying the login data to the HttpContext.User

This object has claims:

image

IN the OnSecurityTokenValidated Method:

I have create two objects from the context:

image

the user principal is being set.
image

however, the context has no claims. Also User.Identity.Name thereefore is null:

image

I've also tried carrying out a manual signin, but that doesn't work either:
`
private async Task SignInUser(TokenValidatedContext tokenValidatedContext)
{
var httpContext = tokenValidatedContext.HttpContext;
var userPrincipal = tokenValidatedContext.Principal;

            await httpContext.SignOutAsync(AppSettings.CookieName);
             await httpContext.SignInAsync(AppSettings.CookieName, userPrincipal,
                new AuthenticationProperties
                {
                    ExpiresUtc = DateTime.UtcNow.AddDays(1),
                    IsPersistent = false,
                    AllowRefresh = false
                });
        }

`

Any ideas what I am doing wrong?

ERROR Account username: Missing from the token response environment login.microsoftonline.com home account id: AccountId: XXXX

Hello,

I receive this message in the API sample code as below:

image

and on further inspection, it shows the Username value to be Missing from the token response:

image

Couldn't find any workarounds but did find the issue documented here at microsoft-authentication-library-for-dotnet:

B2C notes
ADAL does not support B2C and there are no plans to add B2C support. As such, MSAL will not write B2C tokens to the ADAL token cache. In B2C, currently, the displayName (aka username aka preferred username) is null. This is a "bug" in B2C as they should provide a scope for the username. DisplayName should never be null - it would be a schema violation for it to be null. We have code that adds a constant (smth like "Missing from the token response") in these cases.

Not sure there is much that can be done about this for now... any suggestions? Thanks.

Single-Sign Out AD B2C

I have a 2 application using a single AD B2C tenant. I want to logout the user from both websites when the user signs out to either one of them. I'm using email for local accounts.

In AAD, there is a LogoutUrl registered on each application which receives a GET request to users currently signed in to. Source

I wonder if there is workaround for AD B2C like in AAD.

How essential is SessionState?

I've not dug into the code fully yet, however can see a few references to SessionState

I'd like to use Azure AD B2C, however I'm a bit reluctant of bringing in SessionState into my current application.

Are there any other samples which don't rely on SessionState, or is SessionState essential to run Azure AD B2C??

Thanks
Ryan

NullReferenceException in MSALSessionCache constructor

In the latest version from the master branch, MSALSessionCache is no longer used but has been replaced by MSALStaticCache. However, if I modify the code to switch back to MSALSessionCache, there is a NullReferenceException in the Load() method called from the constructor, because the "cache" variable is null at this point:

        public void Load()
        {
            SessionLock.EnterReadLock();
            byte[] blob = httpContext.Session.Get(CacheId);
            if(blob != null)
            {
                cache.DeserializeMsalV3(blob);
            }
            SessionLock.ExitReadLock();
        }

This is how I create the MSALSessionCache (instead of MSALStaticCache):

new MSALSessionCache(signedInUserID, this.HttpContext).EnablePersistence(cca.UserTokenCache);

If I use MSALStaticCache as a reference, I see Load() should not be called from the constructor, but should be called from EnablePersistence instead

Suggestion: Always Provide and DIY Get-Started Intro

Samples are GREAT. But then we have to build our own project. Nobody seems to think that we need to know how to start up using the VS tools with an MVC targeting a Microsoft technology. There are a bunch of options - which do we use?

Policies should be lowercase only

I copied the policy names from the portal, where they are cased. I changed the line

context.ProtocolMessage.IssuerAddress = context.ProtocolMessage.IssuerAddress.Replace(defaultPolicy, policy);

to

context.ProtocolMessage.IssuerAddress = context.ProtocolMessage.IssuerAddress.ToLower().Replace(defaultPolicy.ToLower(), policy.ToLower());

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.