identityserver / identityserver4.accesstokenvalidation Goto Github PK
View Code? Open in Web Editor NEWIdentityServer Access Token Validation for ASP.NET Core
License: Apache License 2.0
IdentityServer Access Token Validation for ASP.NET Core
License: Apache License 2.0
I'm trying to set up IdentityServer4.AccessTokenValidation, but it's failing to validate the signature from a token generated by by IdentityServer.
Here's the error and stacktrace
info: Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerMiddleware[1]
Failed to validate the token eyJhbGciOiJSUzI1NiIsImtpZCI6IjEyQzExNDk2NEI3NDIyODQzMjJEMDBFQzczOUM3NjY4QjJEMzE0Q0MiLCJ0eXAiOiJKV1QiLCJ4NXQiOiJFc0VVbGt0MElvUXlMUURzYzV4MmFMTFRGTXcifQ.eyJuYmYiOjE0ODMyMDIzMTMsImV4cCI6MTQ4MzIwNTkxMywiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo1MDAwIiwiYXVkIjpbImh0dHA6Ly9sb2NhbGhvc3Q6NTAwMC9yZXNvdXJjZXMiLCJNaWRhaXJTZXJ2aWNlIl0sImNsaWVudF9pZCI6ImNsaWVudCIsInNjb3BlIjpbIk1pZGFpclNlcnZpY2UiXX0.WKIBanA3lSje-pq_RQ-AiJTM8x8t9almxeP_QY4rtyMdCRqARhHOv0syFVvEiUFfS9lES7oB-62c1NWXjgqy5rbr4XnLBb9HS-ZKmd5oM8Qwgic9NGaOFCUZUy1jPo35_Gn2sqFzACoGGToyQeCnQ5odrb1ZZEb3moRQMi4dqTCmEwdlMzO1KseyWfGddyZ7x7cq7c2ftVCinS6lXNdLdhpNG5JHH6VHxk3WGrpnZ03w1LGLshDPWPxotnBNTW3rGjtRU5sUgdudait-syiiHCdD5-abJgX1sLGinsi9SUnfOZ5pxxrebqXRSyKpBnVbOfhorHeP-IwDEq88CaSvEw.
Microsoft.IdentityModel.Tokens.SecurityTokenInvalidSignatureException: IDX10500: Signature validation failed. No security keys were provided to validate the signature.
at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateSignature(String token, TokenValidationParameters validationParameters)
at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateToken(String token, TokenValidationParameters validationParameters, SecurityToken& validatedToken)
at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.<HandleAuthenticateAsync>d__1.MoveNext()
The token I am using:
eyJhbGciOiJSUzI1NiIsImtpZCI6IjEyQzExNDk2NEI3NDIyODQzMjJEMDBFQzczOUM3NjY4QjJEMzE0Q0MiLCJ0eXAiOiJKV1QiLCJ4NXQiOiJFc0VVbGt0MElvUXlMUURzYzV4MmFMTFRGTXcifQ.eyJuYmYiOjE0ODMyMDIzMTMsImV4cCI6MTQ4MzIwNTkxMywiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo1MDAwIiwiYXVkIjpbImh0dHA6Ly9sb2NhbGhvc3Q6NTAwMC9yZXNvdXJjZXMiLCJNaWRhaXJTZXJ2aWNlIl0sImNsaWVudF9pZCI6ImNsaWVudCIsInNjb3BlIjpbIk1pZGFpclNlcnZpY2UiXX0.WKIBanA3lSje-pq_RQ-AiJTM8x8t9almxeP_QY4rtyMdCRqARhHOv0syFVvEiUFfS9lES7oB-62c1NWXjgqy5rbr4XnLBb9HS-ZKmd5oM8Qwgic9NGaOFCUZUy1jPo35_Gn2sqFzACoGGToyQeCnQ5odrb1ZZEb3moRQMi4dqTCmEwdlMzO1KseyWfGddyZ7x7cq7c2ftVCinS6lXNdLdhpNG5JHH6VHxk3WGrpnZ03w1LGLshDPWPxotnBNTW3rGjtRU5sUgdudait-syiiHCdD5-abJgX1sLGinsi9SUnfOZ5pxxrebqXRSyKpBnVbOfhorHeP-IwDEq88CaSvEw
I attempted using both an X509 cert and the temporary cert, but both fail with the same issue. I was able to manually set up the MS JWT Middleware with the X509 cert and get that working, but using the IS4 Middleware failed.
Here's an example of what I mean:
app.UseIdentityServer();
app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
{
RequireHttpsMetadata = false,
ApiName = "testapi"
});
app.UseJwtBearerAuthentication(new JwtBearerOptions
{
Audience = "testapi",
TokenValidationParameters = new TokenValidationParameters
{
ValidateActor = false,
ValidateIssuer = false,
IssuerSigningKey = new X509SecurityKey(_cert),
IssuerSigningKeyResolver = (string token, SecurityToken securityToken, string kid, TokenValidationParameters validationParameters) =>
new List<X509SecurityKey> { new X509SecurityKey(_cert) }
}
});
It will be ASP.NET 5 migration?
I'm trying to understand what is purpose of Scope and Additional Scope in IdentityServerAuthenticationOptions. Can someone please explain? As they are providing the same function I believe, why to have two different properties?
Hello! Maybe weird question but can't understand, if I want to validate access tokens from IdentityServer4 on resource server which uses .NET 4.5 (not .NET Core) how can I do it?
Since we could not fix that in the old version:
var options = new IdentityServerBearerTokenOptions
{
Authority = "https://...",
ScopeName = "api1",
ScopeSecret = "secret"
// optional
AdditionalScopes = new[] { "foo", "bar" }
}
Hi,
today I've updated my application with hte newest 1.1 and it seems something doesn't work.
All the requests, included the cookies authentication, are returning 401.
Here the console output:
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Request starting HTTP/1.1 GET https://www-dev.bmwucportal.it:5000/
info: IdentityServer4.AccessTokenValidation.Infrastructure.NopAuthenticationMiddleware[7]
Bearer was not authenticated. Failure message: No token found.
info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2]
Authorization failed for user: (null).
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1]
Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
info: Microsoft.AspNetCore.Mvc.ChallengeResult[1]
Executing ChallengeResult with authentication schemes ().
info: Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectMiddleware[12]
AuthenticationScheme: oidc was challenged.
info: IdentityServer4.AccessTokenValidation.Infrastructure.NopAuthenticationMiddleware[12]
AuthenticationScheme: Bearer was challenged.
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2]
Executed action Gaia.Bmw.Remarketing.Controllers.HomeController.Index (Gaia.Bmw.Remarketing) in 374.4128ms
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 799.5424ms 401
My security configuration is more or less like this:
app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
{
Authority = urlBuilderConfiguration.Auth.Url,
RequireHttpsMetadata = false,
ScopeName = "MyScope",
AutomaticAuthenticate = true,
AdditionalScopes = new[] { "MyScope" }
});
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationScheme = "Cookies",
CookieName = ".myCookieName.rmkt",
ExpireTimeSpan = idsrvConfiguration.Cookie.Expiration,
CookieSecure = CookieSecurePolicy.Always,
SlidingExpiration = true
});
var oidcOptions = new OpenIdConnectOptions
{
AuthenticationScheme = "oidc",
ClaimsIssuer = urlBuilderConfiguration.Auth.Url,
SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme,
Authority = idsrvConfiguration.IdentityServerEndpoint,
RequireHttpsMetadata = false,
PostLogoutRedirectUri = urlBuilder.Home,
ClientId = idsrvConfiguration.Clients.Remarketing.Id,
ClientSecret = idsrvConfiguration.Clients.Remarketing.Secret,
ResponseType = "code id_token",
GetClaimsFromUserInfoEndpoint = true,
SaveTokens = false, // https://auth0.com/docs/quickstart/webapp/aspnet-core/04-storing-tokens
Scope =
{
idsrvConfiguration.Scopes.Frontoffice,
"openid",
"profile",
"email",
"roles"
},
TokenValidationParameters = new TokenValidationParameters()
{
IssuerSigningKey = new X509SecurityKey(encryptingCertificate),
NameClaimType = JwtClaimTypes.Name,
RoleClaimType = JwtClaimTypes.Role,
},
Events = new OpenIdConnectEvents()
{
OnRedirectToIdentityProvider = ctx =>
{
// APIs must return 401 not 302
if (ctx.ProtocolMessage.RequestType == OpenIdConnectRequestType.Authentication)
{
var isAjax = ctx.Request.Headers["X-Requested-With"] == "XMLHttpRequest";
if (isAjax)
{
ctx.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
ctx.HandleResponse();
return Task.FromResult(0);
}
}
return Task.FromResult(0);
}
}
};
If I comment out the UseIdentityServerAuthentication (and remove the library) the cookie authentication works well otherwise not.
Any hint?
Hey,
I'm using JWTs.
I have a project using IdentityServer3.AccessTokenValidation and some newer ones using Version 4.
If a token expires, Version 3 complains in the exact amout of time that the token is invalid.
On the other hand, Version 4 accepts the token even some minutes after expiry.
Is this by design? Is there a setting to controle the "time padding"?
Hi,
I wonder if the function for saving token in the user context isn't implemented yet?
There is the property but I don't see any use of it.
Thanks
I've tried to replicate in numerous other ways (outside of IdentityServer) to isolate issue but cannot recreate it.
I have a .Net Core Application that has both IdentityServer4 and IdentityServer4.AccessTokenValidation applied to it. The access token validation middleware is used to lock down additional endpoints that I have written myself outside of IdentityServer4 itself.
The token validation apparently calls the .well-known/openid-configuration endpoint to get the discovery document, and this works when I run under HTTP alone. However, if I try to run my service under HTTPS, for some reason the call to get the discovery document fails.
I can retrieve this discovery document just fine from other services, Postman, and Chrome. The SSL cert is trusted, and in my Trusted Root Certification Authorities store, so the problem is not there.
It SEEMS to be something related to my service calling itself for the discovery document. But when I simplify this in a test app that calls itself (in the same way), without all the IS4 dependencies, it works fine.
Any thoughts on why there might be an issue with IS4 and IS4.AccessTokenValidation running in the same app being that it must call itself??
The two most inner errors say: "System.Security.Authentication.AuthenticationException: A call to SSPI failed, see inner exception." and then "The client and server cannot communicate, because they do not possess a common algorithm."
Hello,
Thank you for your work!
I have one question regarding "validation" of JWT that is encrypted with algorithm set to 'none'.
Currently, for development purpose encryption alg is set to 'none', but I'm finding the way how to properly handle this kind of scenario.
As I understand when JWT is encrypted with 'none' alg, then there is no signature in this JWT.
As a result of that I'm getting the Error when trying to verify it : ''IDX10504: Unable to validate signature, token does not have a signature".
So I'm wondering is this type of scenario is supported?
As I know, https://www.npmjs.com/package/jsonwebtoken is supporting this kind of scenario:
jwt.verify(bearerToken, null, { algorithms: ['none'] });
Thanks!
I updated to ASP.NET Core 1.0 RC2 yesterday but the last piece to have it compile is the current
"IdentityServer4.AccessTokenValidation": "1.0.0-beta3"
It won't find the extension app.UseIdentityServerAuthentication(options => {/*...*/});
and I guess it's because this project has not been updated yet to support RC2?
It seems to be an extension on Microsoft.AspNet.Builder
namespace but in RC2 this namespace is called Microsoft.AspNetCore.Builder
Is there any workaround for this other than waiting for the new compatible version or forking the project and adapt it to RC2 myself?
This whole transition to RC2 for us has been painful :) and it's not over yet!
I have successfully implemented an identity server and protected a .net core web app using the Authorize attribute on my controller. The problem I'm running into is that the web app fails to retrieve the configuration document from the authentication server (also a web app running on the same server) on startup, after a while I can issue the same http request (from Postman) and the request succeeds. The only authentication options I'm using are Authority and ApiName. Here is the error:
System.InvalidOperationException: IDX10803: Unable to obtain configuration from: 'https://<server name>/.well-known/openid-configuration'. ---> System.IO.IOException: IDX10804: Unable to retrieve document from: 'https://<server name>/.well-known/openid-configuration'. ---> System.Threading.Tasks.TaskCanceledException: A task was canceled.
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Net.Http.HttpClient.<FinishSendAsync>d__58.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.IdentityModel.Protocols.HttpDocumentRetriever.<GetDocumentAsync>d__8.MoveNext()
This is just a question. What's the advantage of using this instead of UseJwtBearerAuthentication for the resource server?
Greetings Damien
I'm using the 1.0.0-beta9 version of this project in a project running the RTM version of core and preview 2 of tooling, and my application crashes during startup.
It fails during the application builder call to UseIdentityServerAuthentication() with the following exception:
Exception thrown: 'System.IO.FileLoadException' in IdentityServer4.AccessTokenValidation.dll
Additional information: Could not load file or assembly 'Microsoft.IdentityModel.Tokens, Version=5.0.0.699, Culture=neutral, PublicKeyToken=31bf3856ad364e35'. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
Stack trace:
at Microsoft.AspNetCore.Builder.IdentityServerAuthenticationExtensions.ConfigureJwt(IdentityServerAuthenticationOptions options)
at Microsoft.AspNetCore.Builder.IdentityServerAuthenticationExtensions.UseIdentityServerAuthentication(IApplicationBuilder app, IdentityServerAuthenticationOptions options)
... (my code)
I have used the sample provided on https://github.com/IdentityServer/CrossVersionIntegrationTests to use IdentityServer4.AccessTokenValidation package validating the token issued by IdentityServer3. I noticed that for the client with AccessTokeType set to "Reference" type, the Scope needs to have ScopeSecrets set. Thus the API which validates the token is required to set ApiSecret. Why now the ScopeSecrets becomes mandatory for Reference type client?
when calling app.UseIdentityServerAuthentication(options) where options is of type IdentityServerAuthenticationOptions, there is sometimes a null reference exception. It seems to occur if options.ValidateScope = false because when it convert to the CombinedAuthenticationOptions the ScopeValidationOptions is null and the helper tries to use it
if (options.ScopeValidationOptions.AllowedScopes.Any())
{
app.AllowScopes(options.ScopeValidationOptions);
}
I am using Identity Server 4 with ASP.NET Core, self-signed certificate generated from IIS 10. I am using different certificates for https and for identity. I am using resource owner password grant. The Identity Server is in the same project with the application. I am trying to access the authorized action throw the angular 2 application. I can successfully get an access token and refresh token, but when I try to make a request to authorized endpoint, there is an error. I can view the metadata from my browser.
services.AddIdentityServer()
.AddSigningCredential(new X509Certificate2(...))
.AddInMemoryApiResources(Config.GetApiResources())
.AddInMemoryClients(Config.GetClients())
.AddResourceOwnerValidator<ResourceOwnerValidator>()
.AddProfileService<ProfileService>()
.AddCustomTokenRequestValidator<CustomTokenRequestValidator>();
I am using IdentityServerAuthentication from IdentityServer4.AccessTokenValidation:
var identityServerOptions = new IdentityServerAuthenticationOptions
{
Authority = "https://localhost/",
ApiName = "api1",
RequireHttpsMetadata = true,
AllowedScopes = new string[] { "api1", "offline_access" },
};
app.UseIdentityServerAuthentication(identityServerOptions);
- exception {System.InvalidOperationException: IDX10803: Unable to obtain configuration from: 'https://localhost/.well-known/openid-configuration'. ---> System.IO.IOException: IDX10804: Unable to retrieve document from: 'https://localhost/.well-known/openid-configuration'. ---> System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.Http.WinHttpException: A security error occurred
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Net.Http.WinHttpHandler.<StartRequest>d__105.MoveNext()
--- End of inner exception stack trace ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Net.Http.HttpClient.<FinishSendAsync>d__58.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 Microsoft.IdentityModel.Protocols.HttpDocumentRetriever.<GetDocumentAsync>d__8.MoveNext()
--- End of inner exception stack trace ---
at Microsoft.IdentityModel.Protocols.HttpDocumentRetriever.<GetDocumentAsync>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 Microsoft.IdentityModel.Protocols.OpenIdConnect.OpenIdConnectConfigurationRetriever.<GetAsync>d__3.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 Microsoft.IdentityModel.Protocols.ConfigurationManager`1.<GetConfigurationAsync>d__24.MoveNext()
--- End of inner exception stack trace ---
at Microsoft.IdentityModel.Protocols.ConfigurationManager`1.<GetConfigurationAsync>d__24.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 Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.<HandleAuthenticateAsync>d__1.MoveNext()} System.Exception {System.InvalidOperationException}
<PackageReference Include="IdentityServer4" Version="1.4.0" />
<PackageReference Include="IdentityServer4.AccessTokenValidation" Version="1.1.0" />
<PackageReference Include="Microsoft.AspNet.Tooling.Razor" Version="1.0.0-rc1-final" />
<PackageReference Include="Microsoft.AspNetCore" Version="1.1.1" />
<PackageReference Include="Microsoft.AspNetCore.Owin" Version="1.1.1" />
<PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="1.1.1" />
<PackageReference Include="Microsoft.Extensions.FileProviders.Embedded" Version="1.1.0" />
<PackageReference Include="Microsoft.AspNetCore.Routing" Version="1.1.1" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="1.1.1" />
<PackageReference Include="Serilog.Extensions.Logging.File" Version="1.0.1-dev-00008" />
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.1.2" />
<PackageReference Include="Microsoft.AspNetCore.Server.IISIntegration" Version="1.1.1" />
<PackageReference Include="Microsoft.AspNetCore.Server.Kestrel" Version="1.1.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="1.1.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="1.1.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="1.1.1" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="1.1.1" />
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="1.1.1" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="1.1.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="1.1.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="1.1.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer.Design" Version="1.1.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="1.1.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="1.1.1" />
<PackageReference Include="Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore" Version="1.1.1" />
<PackageReference Include="Microsoft.AspNetCore.SpaServices" Version="1.1.0" />
<PackageReference Include="Microsoft.NETCore.App" Version="1.1.1" />
I tried with different certificates.
I tried with different versions of Kestrel library.
I tried with to change algorithm from RS256 to HS256.
I tried with different configurations for identity server and some other things to solve the issue with the help with all of the issues in github and stackoverflow, but without a success.
DelayLoadMetadata is already the default options in Identity Server 4.
When I was looking and debugging Identity Server 4, IdentityServer4.AccessTokenValidation and Microsoft.AspNetCore.Authentication code, I realized that if I set a static OpenIdConnectConfiguration for JwtBearerOptions, the Authorization handler don't try to access the https://localhost/.well-known/openid-configuration. It works with static OpenIdConnectConfiguration, but...
public static IApplicationBuilder UseIdentityServerStaticAuthentication(this IApplicationBuilder app, IdentityServerAuthenticationOptions options)
{
var combinedOptions =
CombinedAuthenticationOptions.FromIdentityServerAuthenticationOptions(options);
combinedOptions.JwtBearerOptions.AutomaticAuthenticate = true;
combinedOptions.JwtBearerOptions.AutomaticChallenge = true;
combinedOptions.JwtBearerOptions.TokenValidationParameters.IssuerSigningKey = new X509SecurityKey(certificate);
combinedOptions.JwtBearerOptions.Configuration = new OpenIdConnectConfiguration
{
Issuer = "https://localhost",
JwksUri = "https://localhost/.well-known/openid-configuration/jwks",
AuthorizationEndpoint = "https://localhost/connect/authorize",
TokenEndpoint = "https://localhost/connect/token",
UserInfoEndpoint = "https://localhost/connect/userinfo",
EndSessionEndpoint = "https://localhost/connect/endsession",
CheckSessionIframe = "https://localhost/connect/checksession",
HttpLogoutSupported = true,
LogoutSessionSupported = true,
};
app.UseIdentityServerAuthentication(combinedOptions);
}
I don't like the workaround and I am trying to find a prettier way to solve the issue. I won't to set manually all of these endpoints. I won't to miss some configuration and broke something else. Can you suggest me a proper way to do it or how can I solve this.
Hi @leastprivilege and @ivanmariychuk
In relation to #25,
I tried to use IdentityServer3.AccessTokenValidation for a "Owin WebAPI 4.6" project but when it tries to validate the access token on the IdentityServer4 I see that the service
/connect/accesstokenvalidation
returns 404 error.
In IdentityServer Kestrel's log I notice these lines:
POST requests are not supported
Microsoft.Asp.Net.Core.Authentication.Cookies.CookieAuthetnicationMiddleware
AuthenticationScheme:Identity.Application was not Authenticated
For cleareance I'm using IdentityServer4 with ASP.NET Core Identity integration. Logging is enabled on the identityserver4.
Am I missing something? is the identityserver4 still providing the /connect/accesstokenvalidation endpoint?
To enable the validation of the access token I only added the IdentityServer3.AccessTokenValidation library to our OWIN WebApi 4.6 project and in the Startup.cs I added:
app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
{
Authority = "http://192.168.208.56:5000",
ValidationMode = ValidationMode.ValidationEndpoint
});
Then I added an [Authorize] filter to a WebApi and I'm testing it using postman. On postman I pass on the header the "Authorization : Bearer access_token_as_jwt". Is this correct for testing?
If is not so, is there any guide or documentation about implementing the token validation using the implicit flow?
I'm testing IdentityServer4 and AccessTokenValidation.
At my API's http pipeline I've got the following:
//CORS
app.UseCors(policy =>
{
var originUris = Configuration.GetSection("Cors:OriginUris").Get<List<string>>();
policy.WithOrigins(originUris.ToArray());
policy.AllowAnyHeader();
policy.AllowAnyMethod();
});
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
app.UseJwtBearerAuthentication(options =>
{
if (_hostEnv.IsDevelopment())
{
//for development it is not required https in Authority Uri
options.RequireHttpsMetadata = false;
}
options.Authority = Configuration["Authentication:AuthorityUri"];
options.Audience = Configuration["Authentication:AudienceUri"]; //should this be URL for the receiver of the token
options.AutomaticAuthenticate = true;
options.AutomaticChallenge = true;
});
var userScopes = Configuration.GetSection("Authentication:UserScopes").Get<List<string>>();
app.UseIdentityServerAuthentication(options =>
{
options.Authority = Configuration["Authentication:AuthorityUri"];
options.ScopeName = "api1";
options.AdditionalScopes = userScopes;
options.ScopeSecret = "secret";
options.AutomaticAuthenticate = true;
options.AutomaticChallenge = true;
});
I suppose there is no documentation ready yet on how this works, but as I understood this token validation only validates that the access_token has been issued by the AuthorityUri and later the UseIdentityServerAuthentication middleware checks whether it has the required scopes.
Is there any built in capability to detect whether an access token has been tampered?
I've replaced the last character of my access_token with a random one and the authentication/token validation seems to remain valid (and I think it shouldn't so I must do something about it if this is not supported)
Hello, I'm getting weird problems when validating the JWT token. The problem is that I can do several requests, then the error just occurs. As you can see there is first 2 logs that the token i successfully validated. then just the error. All these 3 request occur in a very tight time (under 5 seconds) between them with a freshly issued JWT token. So don't understand way it works at first , then just stopped working. and when I restart the app , it works for a while again.
I'm running the app in docker so it's running under Linux.
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Request starting HTTP/1.1 GET http://sameendpoint/1234
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Request starting HTTP/1.1 GET http://sameendpoint/1234
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Request starting HTTP/1.1 GET http://sameendpoint/1234
info: Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerMiddleware[2]
Successfully validated the token.
info: Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerMiddleware[2]
Successfully validated the token.
info: Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerMiddleware[1]
Failed to validate the token {token(removed)}.
Microsoft.IdentityModel.Tokens.SecurityTokenInvalidSignatureException: IDX10503: Signature validation failed. Keys tried: 'Microsoft.IdentityModel.Tokens.X509SecurityKey , KeyId: {keyId(removed)}
'.
Exceptions caught:
'System.ArgumentNullException: Value cannot be null.
Parameter name: SafeHandle cannot be null.
at System.StubHelpers.StubHelpers.SafeHandleAddRef(SafeHandle pHandle, Boolean& success)
at Interop.Crypto.RsaVerify(Int32 type, Byte[] m, Int32 m_len, Byte[] sigbuf, Int32 siglen, SafeRsaHandle rsa)
at System.Security.Cryptography.RSAOpenSsl.VerifyHash(Byte[] hash, Byte[] signature, HashAlgorithmName hashAlgorithmName)
at System.Security.Cryptography.RSAOpenSsl.VerifyHash(Byte[] hash, Byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)
at System.Security.Cryptography.RSA.VerifyData(Byte[] data, Int32 offset, Int32 count, Byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)
at System.Security.Cryptography.RSA.VerifyData(Byte[] data, Byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)
at Microsoft.IdentityModel.Tokens.AsymmetricSignatureProvider.Verify(Byte[] input, Byte[] signature)
at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateSignature(Byte[] encodedBytes, Byte[] signature, SecurityKey key, String algorithm)
at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateSignature(String token, TokenValidationParameters validationParameters)
'.
token: '{"alg":"RS256","typ":"JWT","kid":"{kid}"}.{"nbf":{nbf}"exp":1467013165,"iss":"http://authendpoint","aud":"http://authendpoint/resources","client_id":"twee.gateway","scope":"tempapi","sub":"1","auth_time":1467009565,"idp":"idsrv","email":"patrik","amr":["exchange_reference_token"]}'
at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateSignature(String token, TokenValidationParameters validationParameters)
at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateToken(String token, TokenValidationParameters validationParameters, SecurityToken& validatedToken)
at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.<HandleAuthenticateAsync>d__1.MoveNext()
info: Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerMiddleware[7]
Bearer was not authenticated. Failure message: IDX10503: Signature validation failed. Keys tried: 'Microsoft.IdentityModel.Tokens.X509SecurityKey , KeyId: {keyid}
'.
Exceptions caught:
'System.ArgumentNullException: Value cannot be null.
Parameter name: SafeHandle cannot be null.
at System.StubHelpers.StubHelpers.SafeHandleAddRef(SafeHandle pHandle, Boolean& success)
at Interop.Crypto.RsaVerify(Int32 type, Byte[] m, Int32 m_len, Byte[] sigbuf, Int32 siglen, SafeRsaHandle rsa)
at System.Security.Cryptography.RSAOpenSsl.VerifyHash(Byte[] hash, Byte[] signature, HashAlgorithmName hashAlgorithmName)
at System.Security.Cryptography.RSAOpenSsl.VerifyHash(Byte[] hash, Byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)
at System.Security.Cryptography.RSA.VerifyData(Byte[] data, Int32 offset, Int32 count, Byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)
at System.Security.Cryptography.RSA.VerifyData(Byte[] data, Byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)
at Microsoft.IdentityModel.Tokens.AsymmetricSignatureProvider.Verify(Byte[] input, Byte[] signature)
at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateSignature(Byte[] encodedBytes, Byte[] signature, SecurityKey key, String algorithm)
at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateSignature(String token, TokenValidationParameters validationParameters)
'.
token: '{"alg":"RS256","typ":"JWT","kid":"{kid}"}.{"nbf":{nbf},"exp":1467013165,"iss":"http://authendpoint","aud":"http://authendpoint/resources","client_id":"twee.gateway","scope":"tempapi","sub":"1","auth_time":1467009565,"idp":"idsrv","email":"patrik","amr":["exchange_reference_token"]}'
info: Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerMiddleware[3]
HttpContext.User merged via AutomaticAuthentication from authenticationScheme: Bearer.
info: Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerMiddleware[3]
HttpContext.User merged via AutomaticAuthentication from authenticationScheme: Bearer.
warn: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1]
Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
info: Microsoft.AspNetCore.Mvc.ChallengeResult[1]
Executing ChallengeResult with authentication schemes ().
info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[1]
Authorization was successful for user: 1.
info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[1]
Authorization was successful for user: 1.
fail: Microsoft.AspNetCore.Server.Kestrel, Version=1.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60[13]
Connection id "0HKSUAN465EK9": An unhandled exception was thrown by the application.
System.InvalidOperationException: No authentication handler is configured to handle the scheme: Automatic
at Microsoft.AspNetCore.Http.Authentication.Internal.DefaultAuthenticationManager.<ChallengeAsync>d__11.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Mvc.ChallengeResult.<ExecuteResultAsync>d__14.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Mvc.Internal.FilterActionInvoker.<InvokeResultAsync>d__44.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Mvc.Internal.FilterActionInvoker.<InvokeAsync>d__32.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Mvc.Internal.MvcRouteHandler.<InvokeActionAsync>d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Builder.RouterMiddleware.<Invoke>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
at twee.cloud.sync.HttpExceptionMiddleware.<Invoke>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1.<Invoke>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1.<Invoke>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at IdentityServer4.AccessTokenValidation.IdentityServerAuthenticationMiddleware.<Invoke>d__7.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Swashbuckle.SwaggerUi.Application.SwaggerUiMiddleware.<Invoke>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Swashbuckle.SwaggerUi.Application.RedirectMiddleware.<Invoke>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Swashbuckle.SwaggerGen.Application.SwaggerGenMiddleware.<Invoke>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Hosting.Internal.RequestServicesContainerMiddleware.<Invoke>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Server.Kestrel.Http.Frame`1.<RequestProcessingAsync>d__2.MoveNext()
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 1810.4348ms 200
Hi,
Since I switched to Reference tokens, the issuer field of claims does no longer have the actual value of my identity server URL, instead it has "LOCAL AUTHORITY" value.
Is there any setting that I am missing?
Error NU1002 The dependency IdentityServer4.AccessTokenValidation 1.0.1-beta1 does not support framework .NETFramework,Version=v4.5.1.
If so, how?
I cloned the samples repository and set up the Quickstarts/6_AspNetIdentity
solution.
The first time everything worked well and I exchanged the EFCore framework with a MongoDb provider. Still everything works.
After I deleted the whole repository and setup a new, cleaner version within the MongoDb provider, I got the problem that at the Consent
page I dont get redirect to the MvcClient.
Most time I run the projects with "Shift + F5" and test it in usual Google Chrome.
I found out, that if I run the same MvcClient project with F5 with the Debug Google Chrome it works. Also with Internet Explorer or MS Edge and MvcClient in combination with "Shift + F5".
So any old data from the usual Google Chrome disturbs the authentication/authorization process. On the IdentityServer each authentication request suceed.
The output of the MvcClient console:
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1] Request starting HTTP/1.1 GET http://localhost:5002/Home/Secure info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2] Authorization failed for user: (null). info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1] Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'. info: Microsoft.AspNetCore.Mvc.ChallengeResult[1] Executing ChallengeResult with authentication schemes (). info: Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectMiddleware[12] AuthenticationScheme: oidc was challenged. info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2] Executed action MvcClient.Controllers.HomeController.Secure (MvcClient) in 1.6528ms info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2] Request finished in 3.2216ms 302
Since IdSrv and API are in the same process in my project I would like to validate the token locally as was mentioned for IdSrv3 here
https://identityserver.github.io/Documentation/docsv2/consuming/options.html
However, I don't understand how to do this with IdentityServerAuthenticationOptions. There is for example no property SigningCertificate.
What am I missing?
If neither services.AddMvc or services.AddIdentity called in services config, app.UseIdentityServerAuthentication will throw the following exceptions:
System.InvalidOperationException: Unable to resolve service for type 'System.Text.Encodings.Web.UrlEncoder' while attempting to activate 'IdentityModel.AspNetCore.OAuth2Introspection.OAuth2IntrospectionMiddleware'.
[1] Microsoft.Extensions.Internal.ActivatorUtilities.ConstructorMatcher.CreateInstance(IServiceProvider provider)
[1] Microsoft.Extensions.Internal.ActivatorUtilities.CreateInstance(IServiceProvider provider, Type instanceType, Object[] parameters)
[1] Microsoft.AspNetCore.Builder.UseMiddlewareExtensions.<>c__DisplayClass3_0.b__0(RequestDelegate next)
[1] Microsoft.AspNetCore.Builder.Internal.ApplicationBuilder.Build()
[1] IdentityServer4.AccessTokenValidation.IdentityServerAuthenticationMiddleware..ctor(RequestDelegate next, IApplicationBuilder app, CombinedAuthenticationOptions options, ILogger`1 logger)
[1]
[1] Microsoft.Extensions.Internal.ActivatorUtilities.ConstructorMatcher.CreateInstance(IServiceProvider provider)
[1] Microsoft.Extensions.Internal.ActivatorUtilities.CreateInstance(IServiceProvider provider, Type instanceType, Object[] parameters)
[1] Microsoft.AspNetCore.Builder.UseMiddlewareExtensions.<>c__DisplayClass3_0.b__0(RequestDelegate next)
[1] Microsoft.AspNetCore.Builder.Internal.ApplicationBuilder.Build()
[1] Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()
[1] Microsoft.AspNetCore.Hosting.WebHostBuilder.Build()
[1] SourceTraceWeb.Program.Main(String[] args)
How to use IdentityServer4.AccessTokenValidation in net461 project?
Stacked overflow post - http://stackoverflow.com/questions/42556392/updated-system-net-http-dll-not-copied-into-bin-folder-identityserver4-acces
System.Net.Http DLL not put in bin folder when this nuget package is added
If you create a blank .net core API project change it to use .net461 clean your bin folder and build it you will see the System.Net.Http DLL within the folder "bin\Debug\net461\win7-x64".
Now add IdentityServer4 AccessTokenValidation to the dependencies
"IdentityServer4.AccessTokenValidation": "1.0.5"
Clear your bin folder again
Build project and you will see the System.Net.Http DLL is missing.
The project should still work when you run it but I am using a nuget package that needs that missing DLL
Hey guys,
as soon as I access an anonymous page (e.g. documentation) on the service, I get a wall of this log messages.
My Config:
IdentityServerAuthenticationOptions options = new IdentityServerAuthenticationOptions
{
Authority = stsUrl,
AutomaticAuthenticate = true,
AutomaticChallenge = true
}
and a policy with
policyBuilder.AddAuthenticationSchemes("Bearer");
Do I have to add a something or is it normal to have those messages for anonymous users?
Hi,
related Issue: #17
I have a similar problem like in the issue above. I am using IdSrv 3 with IdSrv-4-AccessTokenValidation.
I can authenticate with a resource client, a custom grant client but not with the access token from my implicit auth web site. Authentication works to a point but the result is 401.
The access token is validated successfully, the user is authenticated but the token gets lost somehow in the internal redirect.
My configuration:
`//JwtSecurityTokenHandler.DefaultInboundClaimTypeMap = new Dictionary<string, string>();
application.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions()
{
Authority =
((IOptions<IdentityServerSettings>)serviceProvider.GetService(typeof(IOptions<IdentityServerSettings>)))
.Value.IdentityServerBaseAddress,
ScopeName = "importserverapi",
RoleClaimType = "role",
NameClaimType = "name",
EnableCaching = false,
RequireHttpsMetadata = true
});`
Enabling the line
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap = new Dictionary<string, string>();
does not make any difference.
This ist the log from VS for one request (I replaced the real names):
The thread 0x2b98 has exited with code 0 (0x0).
The thread 0x418c has exited with code 0 (0x0).
The thread 0x2280 has exited with code 0 (0x0).
Microsoft.AspNetCore.Hosting.Internal.WebHost: Information: Request starting HTTP/1.1 GET http://localhost:44309/MYLINK
Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerMiddleware: Information: Successfully validated the token.
Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerMiddleware: Information: HttpContext.User merged via AutomaticAuthentication from authenticationScheme: Bearer.
Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerMiddleware: Information: AuthenticationScheme: Bearer was successfully authenticated.
IdentityModel.AspNetCore.ScopeValidation.ScopeValidationMiddleware: Information: Scopes found on current principal: scope: openid, scope: profile, scope: email, scope: roles, scope: MYSCOPE
Microsoft.AspNetCore.Authorization.DefaultAuthorizationService: Information: Authorization was successful for user: USERNAME.
Microsoft.AspNetCore.Mvc.Internal.RedirectResultExecutor: Information: Executing RedirectResult, redirecting to https://localhost:44309/MYLINK.
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker: Information: Executed action Import.Api.Controllers.MYCONTROLLER.MYACTION (Api) in 2.326ms
Microsoft.AspNetCore.Hosting.Internal.WebHost:_ Information: Request finished in 10.99ms 301
Microsoft.AspNetCore.Hosting.Internal.WebHost: Information: Request starting HTTP/1.1 GET http://localhost:44309/MYLINK
IdentityServer4.AccessTokenValidation.Infrastructure.NopAuthenticationMiddleware: Information: Bearer was not authenticated. Failure message: No token found.
Microsoft.AspNetCore.Authorization.DefaultAuthorizationService: Information: Authorization failed for user: .
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker: Warning: Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
Microsoft.AspNetCore.Mvc.ChallengeResult: Information: Executing ChallengeResult with authentication schemes ().
IdentityServer4.AccessTokenValidation.Infrastructure.NopAuthenticationMiddleware: Information: AuthenticationScheme: Bearer was challenged.
Microsoft.AspNetCore.Hosting.Internal.WebHost: Information: Request finished in 7.0371ms 401
What is happening here? I searched for days without any clue why the token is lost in the redirect.
I read the docs, read the issues and debugged but with no luck.
I am using UseJwtBearerAuthentication() in a api project, but always got http 403 when calling api.
code in Config() of the api project:
app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
{
Authority = "http://localhost:8000",
ScopeName = "api1",
RequireHttpsMetadata = false
});
debug info:
You an see there is no warning, but returned 403.
But it will pass if use UseJwtBearerAuthentication() like this:
app.UseJwtBearerAuthentication(new JwtBearerOptions
{
Authority = "http://localhost:8000",
Audience = "http://localhost:8000/resources",
AutomaticChallenge = true,
AutomaticAuthenticate = true,
RequireHttpsMetadata = false
});
Code in OP server's ConfigureServices():
services.AddIdentityServer()
.SetSigningCredential(cert)
.AddInMemoryStores()
.AddInMemoryScopes(IdentityServerConfig.GetScopes())
.AddInMemoryClients(IdentityServerConfig.GetClients())
.AddAspNetIdentity<ApplicationUser>();
Am i doing something wrong?
thanks.
Is there a way to use JwtBearer events?
For example i want to implement something like below :
app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions()
{
// ...
Events = new JwtBearerEvents()
{
OnAuthenticationFailed = async (context) =>
{
if (condition)
{
context.SkipToNextMiddleware();
}
}
}
});
This is my code to secure my api :
app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
{
Authority = "http://localhost:5000",
ScopeName = "api1",
RequireHttpsMetadata = false
});
but when call the api in an angular client with access token ('Authorization': 'Bearer ' + accesstoken
)
I get this error:
An item with the same key has already been added. Key: idsrv4:tokenvalidation:token
What causes to idsrv4:tokenvalidation:token
add more that one?
Currently, Microsoft.AspNet.Authentication.JwtBearer package targets dnx451 and dnxcore50. Not sure why but when it is fixed, we can change this project to target dotnet5.4 and net451.
Hello,
What's the difference between this nuget and "Microsoft.AspNetCore.Authentication.OpenIdConnect": "1.0.0-rc2-final" ?
Is there any correlation?
There is a method "app.UseOpenIdConnectAuthentication(options)" and it seems very similar and more production ready.
Get this error when validating access token against Identity server after upgrading package from "1.0.1-rc3" to "1.1.0". Currently we are using IdentityServer4 version "1.0.0-rc1-update2".
Is there any version of IdentityServer4 working with IdentityServer4.AccessTokenValidation version "1.1.0"?
We have a solution with following projects –
The issue is web service project does not compile with the class library one and hence our data access will not work. This is a blocker for our production release scheduled for April 2016
The MVC 6 project is using following nugget pkg –
"IdentityServer4.AccessTokenValidation": "1.0.0-beta3"
We are using open id connect and oauth2 security built with open source product - IdentityServer4
"frameworks": {
"dnx451": {
"dependencies": {
".Data": "1.0.0-",
"IdentityServer4.AccessTokenValidation": "1.0.0-beta3"
}
},
"net451": {
"dependencies": {
".Data": "1.0.0-"
}
}
},
I am Using dnx-clr-win-x86 1.0.0-rc1-update1 from Tuesday, December 1, 2015
dnvm list
Active Version Runtime Architecture Location Alias
1.0.0-rc1-final clr x86 C:\Users\<user name>\.dnx\runtimes
1.0.0-rc1-update1 clr x64 C:\Users\<user name>\.dnx\runtimes
dnu restore details –
PM> dnu restore
Microsoft .NET Development Utility Clr-x86-1.0.0-rc1-16231
CACHE https://api.nuget.org/v3/index.json
Restoring packages for .Api\project.json
Writing lock file .Api\project.lock.json
Restore complete, 386ms elapsed
Restoring packages for .\project.json
Writing lock file .Data\project.lock.json
Restore complete, 6ms elapsed
Total time 3780ms
NuGet Config files used:
C:\Users\AppData\Roaming\NuGet\nuget.config
Feeds used:
https://api.nuget.org/v3-flatcontainer/
PM>
Compile error –
1>------ Rebuild All started: Project: .Data, Configuration: Debug Any CPU ------
1> .Data -> .Data\bin\Debug.Data.dll
2>------ Rebuild All started: Project: .Api, Configuration: Debug Any CPU ------
2>\Startup.cs(7,14,7,27): .NET Framework 4.5.1 error CS0234: The type or nam
2>espace name 'IdentityModel' does not exist in the namespace 'System' (are you m
2>issing an assembly reference?)
2>\Startup.cs(48,13,48,36): .NET Framework 4.5.1 error CS0103: The name 'Jwt
2>SecurityTokenHandler' does not exist in the current context
2>\Startup.cs(49,17,49,48): .NET Framework 4.5.1 error CS1061: 'IApplication
2>Builder' does not contain a definition for 'UseIdentityServerAuthentication' an
2>d no extension method 'UseIdentityServerAuthentication' accepting a first argum
2>ent of type 'IApplicationBuilder' could be found (are you missing a using direc
2>tive or an assembly reference?)
2>
2> Build failed.
2> 0 Warning(s).
2> 3 Error(s).
2>
2> Time elapsed 00:00:00.4060406
2>
========== Rebuild All: 1 succeeded, 1 failed, 0 skipped ==========
Hi,
I'm writing Services with Asp.Net Core but we still have an Identity Server 3.
Can I use Token Validation in Core with the Identity Server 3?
Thanks..
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
IdentityServerAuthenticationOptions identityServerValidationOptions = new IdentityServerAuthenticationOptions
{
Authority = "https://localhost:44318/",
AllowedScopes = new List<string> {"dataEventRecords"},
ApiSecret = "dataEventRecordsSecret",
AutomaticAuthenticate = true,
SupportedTokens = SupportedTokens.Both,
// TokenRetriever = _tokenRetriever,
// required if you want to return a 403 and not a 401 for forbidden responses
AutomaticChallenge = true,
};
app.UseIdentityServerAuthentication(identityServerValidationOptions);
Hi,
Just wondering whether there are any plans to handle exceptions thrown due to bad tokens (I tried removing the first character) as 401 errors rather than the 500 error I currently seem to be getting.
I've been looking at the SampleApi project from the samples repository, and found that passing no token, or an expired token responds with a 401 error, passing a token for another scope returns a 403, but passing a token that cannot be parsed causes an unhandled exception which returns a 500.
I've managed to work around this for my own purposes by adding additional steps to the MVC pipeline to detect when an exception is thrown from the authentication part of the pipeline and handle that specially, but just wondered if there was a simpler way or if this is the expected behaviour.
Hello,
Got the same error in IdentityServer4.AccessTokenValidation: 1.0.0-beta9
when doing
app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions()
{
Authority = "authurl",
SupportedTokens = SupportedTokens.Jwt,
RequireHttpsMetadata = false,
AutomaticAuthenticate = true,
});
Guess it's the same issue as in IdentityServer/IdentityServer4#141
I have a MVC view that contains a list of items. any item has an angularjs component that call a secure api.
When the use is logged in all things work fine.
When the user not logged in :
for any list item(api call) one pair of the the following items add to the cookie.
so the cookie reaches the cookie size restriction .
Any reason this NuGet / repo name contains "IdentityServer4"? Are there really anything that ties the validation of access tokens to idsrv4 specifically?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.