I have decided to create a simple project to test Keycloak integration to ASP.Net Core 6 MVC, so I used the following setup.
The last time I posted with ASP.NET MVC 4, I did not get any answers and luck so I decided to create a unit test with a simple project in ASP.NET Core 6 MVC and see if i can make it work, but unfortunately, same problem. I am already stuck for two weeks on this.
Please help.
services.AddAuthentication(options =>
{
//Sets cookie authentication scheme
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie(cookie =>
{
//Sets the cookie name and maxage, so the cookie is invalidated.
cookie.Cookie.Name = "keycloak.cookie";
cookie.Cookie.MaxAge = TimeSpan.FromMinutes(60);
cookie.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
cookie.SlidingExpiration = true;
})
.AddOpenIdConnect(options =>
{
//Use default signin scheme
options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
//Keycloak server
options.Authority = Configuration.GetSection("Keycloak")["ServerRealm"];
//Keycloak client ID
options.ClientId = Configuration.GetSection("Keycloak")["ClientId"];
//Keycloak client secret
options.ClientSecret = Configuration.GetSection("Keycloak")["ClientSecret"];
//Keycloak .wellknown config origin to fetch config
// options.MetadataAddress = Configuration.GetSection("Keycloak")["Metadata"];
//Require keycloak to use SSL
options.RequireHttpsMetadata = false;
options.GetClaimsFromUserInfoEndpoint = true;
options.Scope.Add("openid");
options.Scope.Add("profile");
options.Scope.Add("email");
//Save the token
options.SaveTokens = true;
//Token response type, will sometimes need to be changed to IdToken, depending on config.
options.ResponseType = OpenIdConnectResponseType.Code;
//SameSite is needed for Chrome/Firefox, as they will give http error 500 back, if not set to unspecified.
options.NonceCookie.SameSite = SameSiteMode.None;
options.CorrelationCookie.SameSite = SameSiteMode.None;
options.TokenValidationParameters = new TokenValidationParameters
{
NameClaimType = "name",
RoleClaimType = "https://schemas.scopic.com/roles"
};
Configuration.Bind("<Json Config Filter>", options);
options.Events.OnRedirectToIdentityProvider = async context =>
{
context.ProtocolMessage.RedirectUri = "http://localhost:13636/home";
await Task.FromResult(0);
};
});
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
and a simple HomeController like this
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
public IActionResult Index()
{
bool value = User.Identity.IsAuthenticated;
return View();
}
[Authorize]
public IActionResult Privacy()
{
return View();
}
}
As seen from above, my redirect URL is localhost:13636/home, my keycloak is hosted somewhere remote with address like https://auth.ourcompany.com/realms/OurRealm
when i access localhost:13636/Privacy to test, the Keycloak login page is triggered as usual, but after succesful login and redirects to /home, User.Identity.IsAuthenticated is false and when viewed in debugging console, it seems like cookies is not passed (I am not sure).
Please help understand what is happening here and how to investigate moving forward, i am really stuck on this. the realm and app is setup without any other things like tokens, jwt, roles, etc. other application is working properly, its just ASP.NET integration is really having problem.
How do I and what are the things I need to solve this?
I already disabled the browser cross site cookies setting (allow All in chrome) as I thought that there is a problem when recieving cookies from our remote Keycloak server, but no luck. What else am I missing here?
Update: it doesnt seem to be related to cross site cookies as I have tested running a local keycloak (thru docker) with my localhost ASP.NET core application, the result is the same, isAuthenticated is false and there seem to be no cookies sent in redirect url.