Local to Test/QA Server Application Testing

dotnet

#1

Hi! We are currently doing testing on using Okta for our future applications. We are currently developing in ASP.Net 4x (MVC). We followed the guide and instructions that can be found here: Okta Auth Quickstart and here: ASP.NET 4.x MVC + Okta example. All works well when running in the localhost environment, can sign-in, get claims, and redirects properly after signing in the Okta Sign-in Page.

But when we move our code to our Test Server and following the same steps in the guide/instruction, made it’s own Application in Okta, updated the client ID, secret, redirect, etc everything match how the localhost was made only difference is the base URL

(http://localhost:xxxxx/ vs http://webtest.company/apps/OktaAppHere).
OktaAppHere is application is placed.

Login works, goes to the Okta Sign-in Page but when it tries to go back it looks like it’s trying, the code in the URL is changing but then ends up giving a http 400 error. We did change the redirect to match the location of where the app is placed plus the “authorization-code/callback”.

Any Ideas? Appreciate the help!


Local to Test/QA server
#2

Hey @JDizonCK…

When you create an app via wizard, Okta automatically creates a Trusted Origin entry with the callback url host.

Something you can try:

  1. Go to API > Trusted Origins.
  2. See if you have an entry for your app and modify that entry with your new url.

PS: If you don’t have the entry, just create a new one with the url http://webtest.company.

Hope this helps… :smiley:


#3

Hi! @frederico.hakamine

We did that part, we updated / created a new one for the test server. When we look at the okta logs, it successfully logs the user, authenticates and everything but we did notice that it does that several times like it’s in a loop. it loops for a while then then just gives up and serve the error page not found.

Also due to the setup in our environment we do have to use a proxy to let the calls to Okta go through which works fine when running in localhost at which I also assume will be fine in our test server.

Thank you for the help / suggestion!


#4

Hey @JDizonCK, it sounds like aspnet might be stuck in a redirect loop. This can happen if the redirect back doesn’t work for some reason (and aspnet thinks it needs to redirect to the Okta sign-in page again, over and over).

Can you post your Startup.cs code and Application configuration in Okta?


#5

Sure here’s the startup code. This is using VS 2017. Did a few minor changes to the Using statements.

using System.IdentityModel.Tokens; -switched/replaced with Microsoft.IdentityModel.Tokens

using Microsoft.IdentityModel.Protocols; - switched/replaced with Microsoft.IdentityModel.Protocols.OpenIdConnect

Did that change because the “TokenValidationParameters” line and “OpenIdConnectRequestType” line were complaining that it can’t see / find those and give those using as a solution.

Thank you.

Blockquote
using System;
using System.Configuration;
using System.IdentityModel.Tokens;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using IdentityModel.Client;
using Microsoft.IdentityModel.Protocols;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.IdentityModel.Tokens;
using Microsoft.Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OpenIdConnect;
using Owin;

[assembly: OwinStartup(typeof(ProjOktaVS17.Startup))]

namespace ProjOktaVS17
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
SetDefaultWebProxy();
ConfigureAuth(app);
}

    private void SetDefaultWebProxy()
    {
      // Set the Default Proxy so that we can send data out to the external webservice
    }

    private void ConfigureAuth(IAppBuilder app)
    {
        app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = CookieAuthenticationDefaults.AuthenticationType,
        });

        var clientId = ConfigurationManager.AppSettings["okta:ClientId"].ToString();
        var clientSecret = ConfigurationManager.AppSettings["okta:ClientSecret"].ToString();
        var issuer = ConfigurationManager.AppSettings["okta:Issuer"].ToString();
        var redirectUri = ConfigurationManager.AppSettings["okta:RedirectUri"].ToString();

        app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
        {
            ClientId = clientId,
            ClientSecret = clientSecret,
            Authority = issuer,
            RedirectUri = redirectUri,
            ResponseType = "code id_token",
            UseTokenLifetime = false,
            Scope = "openid profile",
            PostLogoutRedirectUri = ConfigurationManager.AppSettings["okta:PostLogoutRedirectUri"].ToString(),
            TokenValidationParameters = new TokenValidationParameters
            {
                NameClaimType = "name"
            },
            Notifications = new OpenIdConnectAuthenticationNotifications
            {
                RedirectToIdentityProvider = context =>
                {
                    if (context.ProtocolMessage.RequestType == OpenIdConnectRequestType.Logout)
                    {
                        var idToken = context.OwinContext.Authentication.User.Claims
                            .FirstOrDefault(c => c.Type == "id_token")?.Value;
                        context.ProtocolMessage.IdTokenHint = idToken;
                    }

                    return Task.FromResult(true);
                },
                AuthorizationCodeReceived = async context =>
                {
                    // Exchange code for access and ID tokens
                    var tokenClient = new TokenClient(
                        issuer + "/v1/token", clientId, clientSecret);
                    var tokenResponse = await tokenClient.RequestAuthorizationCodeAsync(
                        context.ProtocolMessage.Code, redirectUri);

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

                    var userInfoClient = new UserInfoClient(issuer + "/v1/userinfo");
                    var userInfoResponse = await userInfoClient.GetAsync(tokenResponse.AccessToken);

                    var identity = new ClaimsIdentity();
                    identity.AddClaims(userInfoResponse.Claims);

                    identity.AddClaim(new Claim("id_token", tokenResponse.IdentityToken));
                    identity.AddClaim(new Claim("access_token", tokenResponse.AccessToken));
                    if (!string.IsNullOrEmpty(tokenResponse.RefreshToken))
                    {
                        identity.AddClaim(new Claim("refresh_token", tokenResponse.RefreshToken));
                    }

                    var nameClaim = new Claim(
                        ClaimTypes.Name,
                        userInfoResponse.Claims.FirstOrDefault(c => c.Type == "name")?.Value);
                    identity.AddClaim(nameClaim);


                    context.AuthenticationTicket = new AuthenticationTicket(
                        new ClaimsIdentity(identity.Claims, context.AuthenticationTicket.Identity.AuthenticationType),
                        context.AuthenticationTicket.Properties);
                }
            }
        });
    }

}

}


#6

@nate.barbettini and @frederico.hakamine - Figured out the issue. Looks like the problem is with a security setting with our test server. Tested it with a different test server and it looks like its working on that one. Thank for the responses and suggestions!


#7

Ok I take that back, sorry., after I tried on a different test server that’s on a different location/network it worked once, then tried again now getting a HTTP 400 Bad Request after log-in. Same issue.


#8

@nate.barbettini @frederico.hakamine Updated Code based on the Github update (3-21-18), Updated Startup.cs and web.config. Run locally (LocalHost) works great, gets to the Okta sign-in, logs in and returns to the application. Deployed code to test server, created new application with same setting as local except the URI’s. Able to get to the Okta sign-in, can log-in and Okta logs shows success in log-in, but still fails to do the redirect back to the application. Loops/ tries several times as to redirect (monitors via Fiddler) then just fails to a HTTP 400. Even tried setting the redirect URI to the base uri or uri that I know exists and yet still unable to redirect.

And to make sure my code is not the problem, I used the code from GitHub, works locally but once on the test server it fails to do the redirect after log-in.

Appreciate the help. Trying / testing Okta for our company as a SSO solution but if it’s only working locally, is not a great solution.


Login is stuck in an endless redirect loop, using Asp.NET MVC
#9

We solved the infinite loop issue on our end. @nate.barbettini pointed me to an article https://github.com/IdentityServer/IdentityServer3/issues/542#issuecomment-76750192 and did the solution of adding a dummy “Session_Start” method in the Global.asax.cs

The fix is a code to be added in your MVC global.asax.cs

void Session_Start(object sender, EventArgs e)
{
  // place holder to solve endless loop issue
}