IdentityServer4 and ASP.NET Core Identity in seperate hosts
- [x] I read and understood how to enable logging
Hi,
I'm trying to use ASP.NET Core Identity with IdentityServer4 in seperate hosts. I can get everything working just fine in the sample QuickStart project. For my app however I would want to seperate the token service from the identity service in seperate hosts as I'm planning on moving away from ASP.NET Core identity somewhere in the future and would like to keep the IdentityServer4 implementation as clean as possible. I'm using implicit grant with a JavaScript client, but am unable to have IdentityServer4 validate the login at ASP.NET Core Identity. The problem I'm facing I don't understand the internals of IdentityServer4 enough to know how it should work and where to look for the issue. Best guess is that it uses cookies under the cover and because I'm using different hosts cookies are not sent, or because both apps cannot validate each others responses as I haven't provided any shared signing config.
Any pointers are greatly appreciated!
Issue / Steps to reproduce the problem
I basically created a very simple asp.net core webapp with core identity and use a SQL lite database to store all the relevant user and role tables. I registered a couple of users and then hooked up the IdentityServer4 webapp to the same SQL lite database.
When using the JavaScript client in the QuickStarts I can make a call to the authorize endpoint just fine. I get redirected to an Login action on my identity service that just logs in to an existing user without waiting for any user interaction for testing purposes. The login is successful and I get redirected back to the token service authorize endpoint again.
It is there where it fails as you can see from the logs below.
Please also see the code blocks below the logs for some additional information.
Relevant parts of the log file
Log of the ASP.NET Core Identity implementation
info: Microsoft.Extensions.DependencyInjection.DataProtectionServices[0]
User profile is available. Using 'C:\Users\markp\AppData\Local\ASP.NET\DataProtection-Keys' as key repository and Windows DPAPI to encrypt keys at rest.
Hosting environment: Development
Content root path: C:\Code\NovaSec\IdentityService
Now listening on: http://localhost:5001
Application started. Press Ctrl+C to shut down.
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Request starting HTTP/1.1 GET http://localhost:5001/api/Login?returnUrl=http%3A%2F%2Flocalhost%3A5000%2Fconnect%2Fauthorize%2Flogin%3Fclient_id%3Dclient.js%26redirect_uri%3Dhttp%253A%252F%252Flocalhost%253A5003%252Fcallback.html%26response_type%3Did_token%2520token%26scope%3Dopenid%2520profile%2520deathstar.destroy%26state%3De07d5a52995a45eaa4989c3922f631a2%26nonce%3Db743132becb345938309d0883f20b0fb
info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware[3]
HttpContext.User merged via AutomaticAuthentication from authenticationScheme: Identity.Application.
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1]
Executing action method NovaSec.IdentityService.Controllers.LoginController.Login (NovaSec.IdentityService) with arguments (http://localhost:5000/connect/authorize/login?client_id=client.js&redirect_uri=http%3A%2F%2Flocalhost%3A5003%2Fcallback.html&response_type=id_token%20token&scope=openid%20profile%20deathstar.destroy&state=e07d5a52995a45eaa4989c3922f631a2&nonce=b743132becb345938309d0883f20b0fb) - ModelState is Valid
info: Microsoft.EntityFrameworkCore.Storage.IRelationalCommandBuilderFactory[1]
Executed DbCommand (8ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
PRAGMA foreign_keys=ON;
info: Microsoft.EntityFrameworkCore.Storage.IRelationalCommandBuilderFactory[1]
Executed DbCommand (10ms) [Parameters=[@__normalizedUserName_0='?'], CommandType='Text', CommandTimeout='30']
SELECT "u"."Id", "u"."AccessFailedCount", "u"."BirthDate", "u"."City", "u"."ConcurrencyStamp", "u"."Country", "u"."Email", "u"."EmailConfirmed", "u"."FirstName", "u"."Gender", "u"."LastName", "u"."LockoutEnabled", "u"."LockoutEnd", "u"."NormalizedEmail", "u"."NormalizedUserName", "u"."PasswordHash", "u"."PhoneNumber", "u"."PhoneNumberConfirmed", "u"."SecurityStamp", "u"."TwoFactorEnabled", "u"."UserName"
FROM "AspNetUsers" AS "u"
WHERE "u"."NormalizedUserName" = @__normalizedUserName_0
LIMIT 1
info: Microsoft.EntityFrameworkCore.Storage.IRelationalCommandBuilderFactory[1]
Executed DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
PRAGMA foreign_keys=ON;
info: Microsoft.EntityFrameworkCore.Storage.IRelationalCommandBuilderFactory[1]
Executed DbCommand (0ms) [Parameters=[@__userId_0='?'], CommandType='Text', CommandTimeout='30']
SELECT "role"."Name"
FROM "AspNetUserRoles" AS "userRole"
INNER JOIN "AspNetRoles" AS "role" ON "userRole"."RoleId" = "role"."Id"
WHERE "userRole"."UserId" = @__userId_0
info: Microsoft.EntityFrameworkCore.Storage.IRelationalCommandBuilderFactory[1]
Executed DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
PRAGMA foreign_keys=ON;
info: Microsoft.EntityFrameworkCore.Storage.IRelationalCommandBuilderFactory[1]
Executed DbCommand (0ms) [Parameters=[@__user_Id_0='?'], CommandType='Text', CommandTimeout='30']
SELECT "uc"."Id", "uc"."ClaimType", "uc"."ClaimValue", "uc"."UserId"
FROM "AspNetUserClaims" AS "uc"
WHERE "uc"."UserId" = @__user_Id_0
info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware[10]
AuthenticationScheme: Identity.Application signed in.
info: NovaSec.IdentityService.Controllers.RoleController[1]
User logged in.
info: Microsoft.AspNetCore.Mvc.Internal.RedirectResultExecutor[1]
Executing RedirectResult, redirecting to http://localhost:5000/connect/authorize/login?client_id=client.js&redirect_uri=http%3A%2F%2Flocalhost%3A5003%2Fcallback.html&response_type=id_token%20token&scope=openid%20profile%20deathstar.destroy&state=e07d5a52995a45eaa4989c3922f631a2&nonce=b743132becb345938309d0883f20b0fb.
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2]
Executed action NovaSec.IdentityService.Controllers.LoginController.Login (NovaSec.IdentityService) in 2298.7326ms
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 3085.5275ms 302
Log of the IdentityServer4 implementation
info: IdentityServer4.Startup[0]
You are using the in-memory version of the persisted grant store. This will store consent decisions, authorization codes, refresh and reference tokens in memory only. If you are using any of those features in production, you want to switch to a different store implementation.
info: Microsoft.Extensions.DependencyInjection.DataProtectionServices[0]
User profile is available. Using 'C:\Users\markp\AppData\Local\ASP.NET\DataProtection-Keys' as key repository and Windows DPAPI to encrypt keys at rest.
Hosting environment: Development
Content root path: C:\Code\NovaSec\TokenService
Now listening on: http://localhost:5000
Application started. Press Ctrl+C to shut down.
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Request starting HTTP/1.1 GET http://localhost:5000/.well-known/openid-configuration
info: IdentityServer4.Hosting.IdentityServerMiddleware[0]
Invoking IdentityServer endpoint: IdentityServer4.Endpoints.DiscoveryEndpoint for /.well-known/openid-configuration
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Request starting HTTP/1.1 GET http://localhost:5000/connect/authorize?client_id=client.js&redirect_uri=http%3A%2F%2Flocalhost%3A5003%2Fcallback.html&response_type=id_token%20token&scope=openid%20profile%20deathstar.destroy&state=e07d5a52995a45eaa4989c3922f631a2&nonce=b743132becb345938309d0883f20b0fb
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 695.9417ms 200 application/json
info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware[7]
Identity.Application was not authenticated. Failure message: Unprotect ticket failed
info: IdentityServer4.Hosting.IdentityServerMiddleware[0]
Invoking IdentityServer endpoint: IdentityServer4.Endpoints.AuthorizeEndpoint for /connect/authorize
info: IdentityServer4.Endpoints.AuthorizeEndpoint[0]
ValidatedAuthorizeRequest
{
"ClientId": "client.js",
"ClientName": "JavaScript Client",
"RedirectUri": "http://localhost:5003/callback.html",
"AllowedRedirectUris": [
"http://localhost:5003/callback.html"
],
"SubjectId": "anonymous",
"ResponseType": "id_token token",
"ResponseMode": "fragment",
"GrantType": "implicit",
"RequestedScopes": "openid profile deathstar.destroy",
"State": "e07d5a52995a45eaa4989c3922f631a2",
"Nonce": "b743132becb345938309d0883f20b0fb",
"Raw": {
"client_id": "client.js",
"redirect_uri": "http://localhost:5003/callback.html",
"response_type": "id_token token",
"scope": "openid profile deathstar.destroy",
"state": "e07d5a52995a45eaa4989c3922f631a2",
"nonce": "b743132becb345938309d0883f20b0fb"
}
}
info: IdentityServer4.ResponseHandling.AuthorizeInteractionResponseGenerator[0]
Showing login: User is not authenticated
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 381.1543ms 302
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Request starting HTTP/1.1 GET http://localhost:5000/connect/authorize/login?client_id=client.js&redirect_uri=http%3A%2F%2Flocalhost%3A5003%2Fcallback.html&response_type=id_token%20token&scope=openid%20profile%20deathstar.destroy&state=e07d5a52995a45eaa4989c3922f631a2&nonce=b743132becb345938309d0883f20b0fb
info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware[7]
Identity.Application was not authenticated. Failure message: Unprotect ticket failed
info: IdentityServer4.Hosting.IdentityServerMiddleware[0]
Invoking IdentityServer endpoint: IdentityServer4.Endpoints.AuthorizeEndpoint for /connect/authorize/login
fail: IdentityServer4.Endpoints.AuthorizeEndpoint[0]
User is not authenticated
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 127.0469ms 302
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Request starting HTTP/1.1 GET http://localhost:5000/home/error?errorId=c6400428d7cd10806d7430ee225a227c
info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware[7]
Identity.Application was not authenticated. Failure message: Unprotect ticket failed
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 20.4649ms 404
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Request starting HTTP/1.1 GET http://localhost:5000/favicon.ico
info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware[7]
Identity.Application was not authenticated. Failure message: Unprotect ticket failed
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 41.2476ms 404
Relevant parts of the code
startup class identity service:
public class Startup
{
public IConfigurationRoot Configuration { get; set; }
public ConfigManager ConfigManager { get; set; }
public AppConfig Config { get; set; }
public Startup()
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.AddEnvironmentVariables();
this.Configuration = builder.Build();
this.Config = new AppConfig();
this.Configuration.Bind(this.Config);
this.ConfigManager = new ConfigManager(this.Config);
}
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IConfigManager, ConfigManager>(provider => this.ConfigManager );
services.AddMvc();
services.AddDbContext<CustomDbContext>();
services.AddIdentity<CustomIdentity, CustomRole>(config => {
config.SignIn.RequireConfirmedEmail = true;
})
.AddEntityFrameworkStores<CustomDbContext>()
.AddDefaultTokenProviders();
services.AddSingleton<CustomIdentityManager>();
services.AddSingleton<CustomRoleManager>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseIdentity();
app.UseMvcWithDefaultRoute();
}
startup class token service:
public class Startup
{
public IConfigurationRoot Configuration { get; set; }
public ConfigManager ConfigManager { get; set; }
public AppConfig Config { get; set; }
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.AddEnvironmentVariables();
this.Configuration = builder.Build();
this.Config = new AppConfig();
this.Configuration.Bind(this.Config);
this.ConfigManager = new ConfigManager(this.Config);
}
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IConfigManager, ConfigManager>(provider => this.ConfigManager);
services.AddDbContext<CustomDbContext>();
services.AddIdentity<CustomIdentity, CustomRole>(config => {
config.SignIn.RequireConfirmedEmail = true;
})
.AddEntityFrameworkStores<CustomDbContext>()
.AddDefaultTokenProviders();
services.AddIdentityServer(config => {
config.UserInteraction.LoginUrl = "http://localhost:5001/api/Login";
})
.AddInMemoryClients(this.ConfigManager.GetClients())
.AddInMemoryIdentityResources(this.ConfigManager.GetIdentityResources())
.AddInMemoryApiResources(this.ConfigManager.GetApiResources())
.AddTemporarySigningCredential()
.AddAspNetIdentity<CustomIdentity>();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseIdentity();
app.UseIdentityServer();
}
}
Login action on the controller
[HttpGet]
public async Task<IActionResult> Login(string returnUrl)
{
var result = await _signInManager.PasswordSignInAsync("[email protected]", "P@ssw0rd!", true, lockoutOnFailure: false);
if (result.Succeeded)
{
_logger.LogInformation(1, "User logged in.");
return Redirect(returnUrl);
}
else
{
return Unauthorized();
}
}
JavaScript client:
/// <reference path="oidc-client.js" />
function log() {
document.getElementById('results').innerText = '';
Array.prototype.forEach.call(arguments, function (msg) {
if (msg instanceof Error) {
msg = "Error: " + msg.message;
}
else if (typeof msg !== 'string') {
msg = JSON.stringify(msg, null, 2);
}
document.getElementById('results').innerHTML += msg + '\r\n';
});
}
document.getElementById("login").addEventListener("click", login, false);
document.getElementById("api").addEventListener("click", api, false);
document.getElementById("logout").addEventListener("click", logout, false);
var config = {
authority: "http://localhost:5000",
client_id: "client.js",
redirect_uri: "http://localhost:5003/callback.html",
response_type: "id_token token",
scope:"openid profile deathstar.destroy",
post_logout_redirect_uri : "http://localhost:5003/index.html",
};
var mgr = new Oidc.UserManager(config);
mgr.getUser().then(function (user) {
if (user) {
log("User logged in", user.profile);
}
else {
log("User not logged in");
}
});
function login() {
mgr.signinRedirect();
}
function api() {
mgr.getUser().then(function (user) {
var url = "http://localhost:5001/identity";
var xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.onload = function () {
log(xhr.status, JSON.parse(xhr.responseText));
}
xhr.setRequestHeader("Authorization", "Bearer " + user.access_token);
xhr.send();
});
}
I'm trying to use ASP.NET Core Identity with IdentityServer4 in seperate hosts. I can get everything working just fine in the sample QuickStart project. For my app however I would want to seperate the token service from the identity service in seperate hosts as I'm planning on moving away from ASP.NET Core identity somewhere in the future and would like to keep the IdentityServer4 implementation as clean as possible.
This is fine -- use a Web API to call the identity layer from the IdentityServer UI code.
As for the rest of the code you posted -- that's too much for us to look/debug thru. If you have a specific error, can you narrow your question to that?
Thanks for the reply Brock. I think my issue is that I'm trying to take the UI away from the IdentityServer project. It's currently in the identity layer. So the identity layer posts to the token layer in a seperate project & host process. The flow seems to complete but - and this is where I struggle to understand how it works exactly - but the token layer says the user is not authenticated.
info: IdentityServer4.Hosting.IdentityServerMiddleware[0]
Invoking IdentityServer endpoint: IdentityServer4.Endpoints.AuthorizeEndpoint for /connect/authorize/login
fail: IdentityServer4.Endpoints.AuthorizeEndpoint[0]
User is not authenticated
info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware[7]
Identity.Application was not authenticated. Failure message: Unprotect ticket failed
Ok so I seem to be either one step further or one step worse :)
I ensured that both my login app as well as the token app were using the same DPAPI keys. Now the login info seems to be accepted by IdentityServer but is now says its missing claims.
Unhandled exception: System.InvalidOperationException: sub claim is missing
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Request starting HTTP/1.1 GET http://localhost:5000/connect/authorize?client_id=client.js&redirect_uri=http%3A%2F%2Flocalhost%3A5003%2Fcallback.html&response_type=id_token%20token&scope=openid%20profile%20deathstar.destroy&state=785e6e8cdcc2460e97835e6e2fbe05de&nonce=9e6b15812df74317b4a4913832afa4ec
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 1256.3863ms 200 application/json
dbug: Microsoft.AspNetCore.DataProtection.Repositories.FileSystemXmlRepository[37]
Reading data from file 'C:\Users\markp\AppData\Local\ASP.NET\DataProtection-Keys\key-8ee29929-84b8-4066-919e-acebfc4da0bc.xml'.
dbug: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[18]
Found key {8ee29929-84b8-4066-919e-acebfc4da0bc}.
dbug: Microsoft.AspNetCore.DataProtection.KeyManagement.DefaultKeyResolver[13]
Considering key {8ee29929-84b8-4066-919e-acebfc4da0bc} with expiration date 2017-11-17 07:09:31Z as default key.
dbug: Microsoft.AspNetCore.DataProtection.XmlEncryption.DpapiXmlDecryptor[51]
Decrypting secret element using Windows DPAPI.
dbug: Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel.CngCbcAuthenticatedEncryptorDescriptor[4]
Opening CNG algorithm 'AES' from provider '(null)' with chaining mode CBC.
dbug: Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel.CngCbcAuthenticatedEncryptorDescriptor[3]
Opening CNG algorithm 'SHA256' from provider '(null)' with HMAC.
dbug: Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingProvider[2]
Using key {8ee29929-84b8-4066-919e-acebfc4da0bc} as the default key.
info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware[3]
HttpContext.User merged via AutomaticAuthentication from authenticationScheme: Identity.Application.
info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware[8]
AuthenticationScheme: Identity.Application was successfully authenticated.
dbug: IdentityServer4.Hosting.EndpointRouter[0]
Request path /connect/authorize matched to endpoint type Authorize
dbug: IdentityServer4.Hosting.EndpointRouter[0]
Mapping found for endpoint: Authorize, creating handler: IdentityServer4.Endpoints.AuthorizeEndpoint
info: IdentityServer4.Hosting.IdentityServerMiddleware[0]
Invoking IdentityServer endpoint: IdentityServer4.Endpoints.AuthorizeEndpoint for /connect/authorize
dbug: IdentityServer4.Endpoints.AuthorizeEndpoint[0]
Start authorize request
info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware[8]
AuthenticationScheme: Identity.Application was successfully authenticated.
crit: IdentityServer4.Hosting.IdentityServerMiddleware[0]
Unhandled exception: System.InvalidOperationException: sub claim is missing
at IdentityServer4.Extensions.PrincipalExtensions.GetSubjectId(IIdentity identity)
at IdentityServer4.Endpoints.AuthorizeEndpoint.<ProcessAuthorizeRequestAsync>d__11.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at IdentityServer4.Endpoints.AuthorizeEndpoint.<ProcessAuthorizeAsync>d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at IdentityServer4.Endpoints.AuthorizeEndpoint.<ProcessAsync>d__7.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at IdentityServer4.Hosting.IdentityServerMiddleware.<Invoke>d__4.MoveNext()
Any update on the issue? closing for now - feel free to re-open if it needs further discussion.
I am having same issue
|System.InvalidOperationException: sub claim is missing
at IdentityServer4.Extensions.PrincipalExtensions.GetSubjectId(IIdentity identity)
@mpriem hi there, i have exact same scenario for my project. did you found any workaround for this problem??
This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.