When I use Bearer token with an AspNetCore controller protected with [Authorize]
, I get the log message:
info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler[7]
Identity.Application was not authenticated. Failure message: Unprotect ticket failed
I'm trying to understand what this means and what can be causing this.
The Startup
class of the Api is has the following setup. Api uses AspNet Identity Core.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<UserAccountDbContext>(options => options.UseSqlServer(connectionString,
sql => sql.MigrationsAssembly(MigrationsAssembly)));
services.AddIdentity<UserAccount, IdentityRole>()
.AddEntityFrameworkStores<UserAccountDbContext>();
services.AddTransient<UserManager<UserAccount>>();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddAuthorization();
services.AddAuthentication("Bearer")
.AddJwtBearer("Bearer", options =>
{
options.Authority = _configuration.OAuth2.ServerUri;
options.RequireHttpsMetadata = false;
options.Audience = "api";
});
}
And:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseAuthentication();
app.UseMvc();
}
The response to the caller is Unauthorized (401) without any explanation.
EDIT:
I think this has something to do with cookies as the comment suggested. I see a cookie Identity.Application
. I cleared this and tried but didn't help. I think this may have something to do with the way my token server and the Api server are setup (both of which are using AspNet Identity).
I have one Mvc project running as the Idp on localhost:5000. Then my user manager Api which has the protected controller is hosted on localhost:5001. When I try to access the protected controller, I get redirected to the login page in the IdP project (which I think is what sets the cookie). Then I try to use the token with the controller I get the above mentioned error.
If I delete the cookies between getting the token and making the Api call, I get the following log:
2019-02-11 23:35:15.3711 [INFO] Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
info: Microsoft.AspNetCore.Mvc.ChallengeResult[1]
Executing ChallengeResult with authentication schemes ().
2019-02-11 23:35:15.3711 [INFO] Executing ChallengeResult with authentication schemes ().
info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler[12]
AuthenticationScheme: Identity.Application was challenged.
2019-02-11 23:35:15.3711 [INFO] AuthenticationScheme: Identity.Application was challenged.
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2]
When I spin up a development server on port 5000, I also got the "Unprotect ticket failed" error message. In Chrome I had a number of cookies lying around from another project which also ran at 5000. Deleted all cookies and error message gone.