Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

OpenId Authentication callback/event after login #479

Open
3 of 17 tasks
mesteves opened this issue Apr 7, 2021 · 8 comments
Open
3 of 17 tasks

OpenId Authentication callback/event after login #479

mesteves opened this issue Apr 7, 2021 · 8 comments
Assignees
Labels
Answered question Further information is requested

Comments

@mesteves
Copy link

mesteves commented Apr 7, 2021

Please provide us with the following information:

This issue is for a: (mark with an x)

- [ ] bug report -> please search issues before submitting
- [ ] feature request
- [x] documentation issue or request
- [ ] regression (a behavior that used to work and stopped in a new release)

The issue was found for the following scenario:

Please add an 'x' for the scenario(s) where you found an issue

  1. Web app that signs in users
    1. with a work and school account in your organization: 1-WebApp-OIDC/1-1-MyOrg
    2. with any work and school account: /1-WebApp-OIDC/1-2-AnyOrg
    3. with any work or school account or Microsoft personal account: 1-WebApp-OIDC/1-3-AnyOrgOrPersonal
    4. with users in National or sovereign clouds 1-WebApp-OIDC/1-4-Sovereign
    5. with B2C users 1-WebApp-OIDC/1-5-B2C
  2. Web app that calls Microsoft Graph
    1. Calling graph with the Microsoft Graph SDK: 2-WebApp-graph-user/2-1-Call-MSGraph
    2. With specific token caches: 2-WebApp-graph-user/2-2-TokenCache
    3. Calling Microsoft Graph in national clouds: 2-WebApp-graph-user/2-4-Sovereign-Call-MSGraph
  3. Web app calling several APIs 3-WebApp-multi-APIs
  4. Web app calling your own Web API
    1. with a work and school account in your organization: 4-WebApp-your-API/4-1-MyOrg
    2. with B2C users: 4-WebApp-your-API/4-2-B2C
    3. with any work and school account: 4-WebApp-your-API/4-3-AnyOrg
  5. Web app restricting users
    1. by Roles: 5-WebApp-AuthZ/5-1-Roles
    2. by Groups: 5-WebApp-AuthZ/5-2-Groups
  6. Deployment to Azure
  7. Other (please describe)

Repro-ing the issue

Repro steps

services.Configure<OpenIdConnectOptions>(OpenIdConnectDefaults.AuthenticationScheme, options =>
            {
                options.Events = new OpenIdConnectEvents
                {
                    OnRedirectToIdentityProvider = (context) =>
                    {
                        if (context.Request.Headers.ContainsKey("X-Forwarded-Host"))
                        {
                            context.ProtocolMessage.RedirectUri =
                                "https://" + context.Request.Headers["X-Forwarded-Host"] +
                                Configuration.GetSection("AzureAd").GetValue<string>("CallbackPath");
                        }

                        return Task.FromResult(0);
                    }
                    ,OnMessageReceived = context =>
                    {
                        Debugger.Break();
                        return Task.CompletedTask;
                    }};
            });

services
                .AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)      // Use OpenId authentication
                .AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"))    // Specify this is a web app and needs auth code flow
                .EnableTokenAcquisitionToCallDownstreamApi(new string[] { "user.read" })         // Add ability to call web API (Graph) and get access tokens
                .AddMicrosoftGraph(Configuration.GetSection("Graph"))             // Add a GraphServiceClient via dependency injection
                .AddInMemoryTokenCaches(cacheOptions =>
                {
                    //cacheOptions.AbsoluteExpirationRelativeToNow = TimeSpan.FromDays(90);
                }); // Use in-memory token cache-See https://github.com/AzureAD/microsoft-identity-web/wiki/token-cache-serialization

Expected behavior
I would expect an event to be exposed, to when the user performs authentication, using the AD login page, and when he returns to the application. This because I need to perform some actions right after a successful login.

Actual behavior

No event discovered :( , I've read several articles and MSFT documentation and found nothing. Is there a way yo do it ?

Possible Solution

??

Additional context/ Error codes / Screenshots

Any log messages given by the failure

Add any other context about the problem here, such as logs.

OS and Version?

Windows 7, 8 or 10. Linux (which distribution). macOS (Yosemite? El Capitan? Sierra?)

Versions

of ASP.NET Core, of MSAL.NET

ASP.NET Core 5

Attempting to troubleshooting yourself:

Mention any other details that might be useful


Thanks! We'll be in touch soon.

@Shama-K
Copy link
Contributor

Shama-K commented Apr 7, 2021

@mesteves, You can subscribe to OnTokenValidated event in AddMicrosoftIdentityWebApp as shown in this link: Using delegate events.
OnTokenValidated is invoked when user has signed-in and the token is validated.

@dbman86
Copy link

dbman86 commented Apr 10, 2021

How can you do this with AddMicrosoftIdentityWebAppAuthentication?
services.AddMicrosoftIdentityWebAppAuthentication(Configuration, "Authentication:AzureAdB2C")
.EnableTokenAcquisitionToCallDownstreamApi(new[] {Configuration["Authentication:AzureAdB2C:ApiScopes"]})
.AddInMemoryTokenCaches();

@jmprieur
Copy link
Contributor

There are two ways:

@jmprieur jmprieur added Answered question Further information is requested labels Apr 12, 2021
@dbman86
Copy link

dbman86 commented Apr 12, 2021

Thank you for the reply. In the OnTokenValidated event I want to do some custom permission checks and if they don't pass then I want to redirect to a nice error screen. How can I do this? I tried to do:

arg.HttpContext.Response.Redirect("/somepage");

but it didn't work. I see in the example it throws an UnauthorizedAccessException but how can I show a nice descriptive error page ? if i throw that exception than the URL goes to /MicrosoftIdentity/Account/Error and I found this page to scafford but I don't see the option for /MicrosoftIdentity/Account/Error or even /Account/Error ..?

https://docs.microsoft.com/en-us/aspnet/core/security/authentication/scaffold-identity?view=aspnetcore-5.0&tabs=visual-studio

image

@dbman86
Copy link

dbman86 commented Apr 12, 2021

also - how can I easily query ms graph in OnTokenReceived to get additional info about the user? note I added new issue: #482 thank you

@jmprieur
Copy link
Contributor

@dbman86 : maybe "somepage" has the [Authorize] attribute? you'd want to remove it for the error message page ...

@dbman86
Copy link

dbman86 commented Apr 13, 2021

@jmprieur thanks for reply but no it has [AllowAnonymous] . other ideas?

@kalyankrishna1
Copy link
Contributor

Please let us know if this issue is still relevant after all the updates the samples have gone through. Or, we'd go ahead and close this issue

@kalyankrishna1 kalyankrishna1 self-assigned this Nov 29, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Answered question Further information is requested
Projects
None yet
Development

No branches or pull requests

5 participants