AuthorizationCodeReceived throws not found error

I have an application and I am trying to use the company active directory logins through okta. I am able to access the orgUri when I try to login and enter my credential but after it redirects back to my application it throws an exception as “Not Found”. (When I check the logs i can see the users logged successfully). Here is the Startup.cs

 public void Configuration(IAppBuilder app)
        {
            //ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                ClientId = clientId,
                ClientSecret = clientSecret,
                Authority = authority,
                RedirectUri = redirectUri,
                ResponseType = OpenIdConnectResponseType.CodeIdToken,
                Scope = OpenIdConnectScope.OpenIdProfile,
                PostLogoutRedirectUri = postLogoutRedirectUri,
                TokenValidationParameters = new TokenValidationParameters
                {
                    NameClaimType = "name"
                },

                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthorizationCodeReceived = async n =>
                    {
                        // Exchange code for access and ID tokens
                        var tokenClient = new TokenClient(authority + "/v1/token", clientId, clientSecret);
                        var tokenResponse = await tokenClient.RequestAuthorizationCodeAsync(n.Code, redirectUri);

                        if (tokenResponse.IsError)
                        {
                            **throw new Exception(tokenResponse.Error);**
                        }

                        var userInfoClient = new UserInfoClient(authority + "/v1/userinfo");
                        var userInfoResponse = await userInfoClient.GetAsync(tokenResponse.AccessToken);
                        var claims = new List<Claim>();
                        claims.AddRange(userInfoResponse.Claims);
                        claims.Add(new Claim("id_token", tokenResponse.IdentityToken));
                        claims.Add(new Claim("access_token", tokenResponse.AccessToken));

                        if (!string.IsNullOrEmpty(tokenResponse.RefreshToken))
                        {
                            claims.Add(new Claim("refresh_token", tokenResponse.RefreshToken));
                        }
                        foreach (var group in userInfoResponse.Claims.Where(x => x.Type == "groups"))
                        {
                            n.AuthenticationTicket.Identity.AddClaim(new Claim(ClaimTypes.Role, group.Value));
                        }
                        n.AuthenticationTicket.Identity.AddClaims(claims);

                        return;
                    },

                    RedirectToIdentityProvider = n =>
                    {
                        // If signing out, add the id_token_hint
                        if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.Logout)
                        {
                            var idTokenClaim = n.OwinContext.Authentication.User.FindFirst("id_token");

                            if (idTokenClaim != null)
                            {
                                n.ProtocolMessage.IdTokenHint = idTokenClaim.Value;
                            }

                        }

                        return Task.CompletedTask;
                    }
                },
            });
        }

Can you open your browser’s network panel, check “Preserve log” (or similar), and take a screenshot of the network trace? That will help determine where the browser is being redirected to.

I noticed this line was highlighted in your code:

**throw new Exception(tokenResponse.Error);**

Is that the line you’re getting an exception on?

Hi Nate,
Yes I highlighted the part that i received error in the code. I also used the latest startup.cs code from documentation page but this time i wasn’t able to access the login page
I have user assigned to okta login app as individual and the app is listed in API under Trusted Origins and CORS

here is the startup.cs
public void Configuration(IAppBuilder app)
{
//ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

        app.UseCookieAuthentication(new CookieAuthenticationOptions());

        app.UseOktaMvc(new OktaMvcOptions()
        {
            OktaDomain = ConfigurationManager.AppSettings["okta:OktaDomain"],
            ClientId = ConfigurationManager.AppSettings["okta:ClientId"],
            ClientSecret = ConfigurationManager.AppSettings["okta:ClientSecret"],
            RedirectUri = ConfigurationManager.AppSettings["okta:RedirectUri"],
            PostLogoutRedirectUri = ConfigurationManager.AppSettings["okta:PostLogoutRedirectUri"],
            GetClaimsFromUserInfoEndpoint = true,
            Scope = new List<string> { "openid", "profile", "email" },
        });
    }

and webconfig file as below




//I didnt use /oauth2/default since we have active directory server

Hi @Burak,

Not sure whether it matters, you have to use the entire path of token endpoint.

When I test the code with dev-xxx.oktapreview.com (by changing web config parameters) it worked ok but I wasn’t able to make it work with company okta domain. I believe the problem is more on the okta app configuration under company okta account. I actually have the same configuration selected on both app (Authorization Code and Allow ID Token with implicit grant type are enabled) The app was added under CORS/Trusted origins. The only difference, our company okta account has one more section called “OpenID Connect ID Token” which is I believe for the active directory group and filter management.
Any more suggestion?

Thanks

Did you ever find the solution for this? I’m getting the exact same error.

Thanks.

Mick