I have Asp.Core applicaton where I have configured OKTA authentication. Url of the application is mentioned in Sign-in redirect URIs and Sign-out redirect URIs. At the end of the url I am adding /signin-oidc
Now the problem is following, when user hits url he is challenged with OKTA authentication after he provides his credentials, he logs in but redirection does not work properly.
- url( https://webdataextract-app1-gtp27.installprogram.eu/WebDataExtract) which triggers OKTA authentication
- url to where user is redirected ( https://webdataextract-app1-gtp27.installprogram.eu).
As you can see endpoint is missing.
Startup.cs
public class Startup
{
private IOptionsMonitor _corsSettings;
private CorsSettings CorsSettings => _corsSettings.CurrentValue;
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
// Will configure okta and cors sections from appsettings.json
ServicesConfigureOptions(services);
ServicesConfigureDependencyInjection(services);
// main method which will pass information from appsettings.json to url once authorization of user needed
ServicesConfigureOpenIdConnect(services);
// specifies which urls can be used to interact with okta
//ServicesConfigureCors(services);
services.AddAuthorization();
services.AddControllersWithViews();
services.AddDbContext<JobsContext>(dbContextOption =>
dbContextOption.UseSqlServer(Configuration.GetConnectionString("HangfireConnection"),b=>b.MigrationsAssembly("WebDataExtract")));
services.AddAuthorization(options =>
{
var oktaRoles = Configuration["Okta:Groups"].Split(",").Select(x => x.Trim());
options.AddPolicy("RequireAdministratorRole",
policy => policy.RequireClaim("Groups", oktaRoles));
});
services.AddSingleton<IConfiguration>(Configuration);
services.AddTransient<IJobsRepo, JobsRepo>();
services.AddTransient<IHelper, Helper>();
services.AddTransient<IGameDataGetter, GameDataGetter>();
services.AddTransient<IJobsMonitor, JobsMonitor>();
services.AddTransient<IBackgroundJobs, BackgroundJobs>();
services.AddHangfire(configuration => configuration
.SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
.UseSimpleAssemblyNameTypeSerializer()
.UseRecommendedSerializerSettings()
.UseSqlServerStorage(Configuration.GetConnectionString("HangfireConnection"), new SqlServerStorageOptions
{
CommandBatchMaxTimeout = TimeSpan.FromMinutes(5),
SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5),
QueuePollInterval = TimeSpan.Zero,
UseRecommendedIsolationLevel = true,
DisableGlobalLocks = true
}));
services.AddHangfireServer();
services.AddApplicationInsightsTelemetry();
services.AddMvc()
.AddViewComponentsAsServices();
}
private void ServicesConfigureOpenIdConnect(IServiceCollection services)
{
services.ConfigureApplicationCookie(options =>
{
options.Cookie.HttpOnly = true;
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
});
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = OpenIdConnectDefaults.AuthenticationScheme;
options.DefaultSignInScheme = OpenIdConnectDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie(OpenIdConnectDefaults.AuthenticationScheme)
.AddOpenIdConnect("okta", options =>
{
options.ClientId = Configuration.GetValue<string>("Okta:ClientId");
options.ClientSecret = Configuration.GetValue<string>("Okta:ClientSecret");
options.Authority = Configuration.GetValue<string>("Okta:OktaDomain");
options.SignedOutRedirectUri = Configuration.GetValue<string>("Okta:SignedOutRedirectUri");
options.Scope.Add("openid");
options.Scope.Add("email");
options.Scope.Add("roles");
options.Scope.Add("groups");
options.GetClaimsFromUserInfoEndpoint = true;
options.TokenValidationParameters = new TokenValidationParameters
{
NameClaimType = "name"
};
options.ResponseType = OpenIdConnectResponseType.CodeIdToken;
options.Events = new OpenIdConnectEvents
{
OnAuthenticationFailed = OnAuthenticationFailedAsync,
OnAuthorizationCodeReceived = OnAuthorizationCodeReceivedAsync
};
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IAuthentication authentication, IOptionsMonitor<CorsSettings> corsSetings)
{
_corsSettings = corsSetings;
app.UseHangfireServer();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error/?statusCode={0}/?exceptionMessage={1}");
app.UseHsts();
}
app.UseHttpsRedirection();
if (!Convert.ToBoolean(Configuration["IISHosted"]))
{
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(AppDomain.CurrentDomain.BaseDirectory + "\\wwwroot")
});
}
else
{
app.UseStaticFiles();
}
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
// to make sure that user wont have access to dashboard before he signs in,
// also user only can read status of the job
app.UseHangfireDashboard("/jobs", new DashboardOptions
{
Authorization = new[] { new HangfireAuthorizationFilter() },
IsReadOnlyFunc = (DashboardContext context) => true
});
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Script}/{action=JobsProgress}");
});
}
private void ServicesConfigureOptions(IServiceCollection services)
{
services.Configure<OktaSettings>(Configuration.GetSection("Okta"));
}
private static void ServicesConfigureDependencyInjection(IServiceCollection services)
{
services.AddTransient<IAuthentication, Authentication>();
}
private void ServicesConfigureCors(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy", builder => builder
.WithOrigins(CorsSettings.AllowedOrigins)
.AllowAnyHeader()
.AllowCredentials()
.AllowAnyMethod());
});
}
private Task OnAuthorizationCodeReceivedAsync(AuthorizationCodeReceivedContext context)
{
var test = context.JwtSecurityToken;
return Task.CompletedTask;
}
private static Task OnAuthenticationFailedAsync(AuthenticationFailedContext context)
{
context.HandleResponse();
context.Response.Redirect("/Error?message=" + context.Exception.Message);
return Task.CompletedTask;
}
}
}