identityserver / identityserver3.accesstokenvalidation Goto Github PK
View Code? Open in Web Editor NEWOWIN Middleware to validate access tokens from IdentityServer3
License: Apache License 2.0
OWIN Middleware to validate access tokens from IdentityServer3
License: Apache License 2.0
Simple WebApi setup. We have a MVC client application which uses Identity Server 3 to authenticate clients. That portion works fine.
Now we're trying to implement a WebApi project which will use the Token received by clients of our MVC app to authenticate and authorize. I've dug around and I've looked at the Simplest OAuth2 walk through which seems straight forward.
So I created a console app to test and we use the HttpClient.
Here's a method we build the HttpClient and set the Bearer token.
public static HttpClient BuildIdentityHttpClient()
{
HttpClient _httpClient = new HttpClient();
//var _client = new OAuth2Client(
// new Uri("Https://localhost/IdentityApis/core/connect/token"),
// "SLWebApiSvcs_ClientId",
// "22ECC1D5-772B-472B-8EBB-2688FBBAEA12");
//var _token = _client.RequestClientCredentialsAsync("slwebapisvcs").Result;
var _client = new OAuth2Client(
// new Uri("https://localhost/IdSvr/core/connect/token")
new Uri("Https://localhost/IdentityApis/core/connect/token"),
"SmartLynxWcfSvcs-ResourceOwner_ClientId",
"B6E3037C-E8E0-4AEF-BAD0-33A42BA54207"
);
var _token = _client.RequestResourceOwnerPasswordAsync("testuser", "P@ssw0rd", "slwebapisvcs").Result;
_httpClient.SetBearerToken(_token.AccessToken);
return _httpClient;
}
After the client has the token, then we make a call like this.
var _result = _client.GetStringAsync("https://localhost/SLWebApi/TruckApi/Get").Result;
On the WebApi side,
We set the UseIdentityServerBearerTokenAuthentication like so.
app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
{
Authority = "https://localhost/IdentityApis/core",
RequiredScopes = new[] { "scope1" }
});
We set the AuthorizeAttribute filter.
Then we use a custom AuthorizeAttribute where we will override the IsAuthorized once we get this figured out.
However, the principal is always Windows principle and there are never claims which were passed over.
We're checking the identity server logs and the WebApi project isn't making calls to Identity server.
When I look at the request object in the customer AuthorizeAttribute class, I can see in the request that authentication is bearer and you see the token.
Why would UseIdentityServerBearerTokenAuthentication not initiate a call to identity server and try to authorize the token and build an ClaimsPrincipal object?
Thanks
I am getting this error at the end of a WebApi controller which is decorated with Authorize attribute. Why do I get it? It shows the file paths of @brockallen's computer I guess :)
Locating source for 'c:\etc\Dropbox\identity\IdentityServer3\AccessTokenValidation\source\AccessTokenValidation\ScopeRequirementMiddleware.cs'. Checksum: MD5 {20 5d 3d 8e 5b ac e4 7c 85 72 34 3b 64 9 ab d0}
The file 'c:\etc\Dropbox\identity\IdentityServer3\AccessTokenValidation\source\AccessTokenValidation\ScopeRequirementMiddleware.cs' does not exist.
Looking in script documents for 'c:\etc\Dropbox\identity\IdentityServer3\AccessTokenValidation\source\AccessTokenValidation\ScopeRequirementMiddleware.cs'...
Looking in the projects for 'c:\etc\Dropbox\identity\IdentityServer3\AccessTokenValidation\source\AccessTokenValidation\ScopeRequirementMiddleware.cs'.
The file was not found in a project.
Looking in directory 'C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\crt\src'...
Looking in directory 'C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\crt\src\vccorlib'...
Looking in directory 'C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\atlmfc\src\mfc'...
Looking in directory 'C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\atlmfc\src\atl'...
Looking in directory 'C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\atlmfc\include'...
The debug source files settings for the active solution indicate that the debugger will not ask the user to find the file: c:\etc\Dropbox\identity\IdentityServer3\AccessTokenValidation\source\AccessTokenValidation\ScopeRequirementMiddleware.cs.
The debugger could not locate the source file 'c:\etc\Dropbox\identity\IdentityServer3\AccessTokenValidation\source\AccessTokenValidation\ScopeRequirementMiddleware.cs'.
It just happens during debugging. If don't put a breakpoint in the controller, I don't get it. But the GET request to that controller gives an error anyway.
IOW, allow JWTs to be validated local, but reference tokens to be validated at AS.
It seems the middleware require Owin, but Asp.Net 5 don't use Owin.
How can I consume JWT from Web Api 1. In Web Api 2 I can use
app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
{
Authority = "https://localhost:44333",
ValidationMode = ValidationMode.ValidationEndpoint,
RequiredScopes = new[] { "api1" }
});
But how to do this in Web Api 1?
I was trying to use OWIN Cookie Authentication for MVC with Active AuthenticationMode and UseIdentityServerBearerTokenAuthentication middleware for WebAPI with Passive AuthenticationMode but this option is never set when using ValidationEndpoint (here)
internal static void UseValidationEndpoint(this IAppBuilder app, IdentityServerBearerTokenAuthenticationOptions options)
{
if (options.EnableValidationResultCache)
{
if (options.ValidationResultCache == null)
{
options.ValidationResultCache = new InMemoryValidationResultCache(options);
}
}
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
{
AccessTokenProvider = new ValidationEndpointTokenProvider(options),
Provider = options.Provider,
});
}
It would be nice to have this options so we could use this middleware on a passive authentication mode
Like issuer name, certificate etc.
Mainly for situations where producer and consumer are in the same application.
Trying to implement custom cache today I came across two classes that would be nice if they were no longer internal:
Clock (default clock implementation) of IClock
EpochTimeExtensions
There may be others but those two required a quick copy, paste and rename for clarity on my end.
It seems like passing the option AuthenticationType
is ignored and always results in "Bearer" being used.
I'm doing:
app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions()
{
AuthenticationType = "Whatever",
...
});
Then, I change the filter for the WebAPI to:
config.Filters.Add(new HostAuthenticationFilter("Whatever"));
and change the request header to:
Authorize: Whatever <token_here>
But this doesn't work, always getting 401 back from the WebAPI. If I revert the filter and request header to "Bearer" (leaving the options.AuthenticationType
set to Whatever
), it works again.
Any idea what I might be doing wrong or isn't it supposed to work this way?
It currently tries to connect to authority in several cases (I guess) and it blows up if the authority is not there at that time. This is especially a problem on the dev time like when you use docker compose to get your solution up and running and cannot guarantee which one will start before.
The solution would be to wrap the logic inside Lazy
and reach out to its value on first request.
2.0.0-2.2.0's TokenProvider does not get invoked with Authority and Local validation mode set:
app.UseIdentityServerBearerTokenAuthentication(
new IdentityServerBearerTokenAuthenticationOptions
{
Authority = ...,
ValidationMode = ValidationMode.Local, // JWT
TokenProvider = new OAuthBearerAuthenticationProvider()
{
OnValidateIdentity = ctx =>
{
//... HERE NOT CALLED
}
}
});
Rolling back to Thinktecture.IdentityServer3.AccessTokenValidation 1.2.2 and it is invoked:
app.UseIdentityServerBearerTokenAuthentication(
new IdentityServerBearerTokenAuthenticationOptions
{
Authority = ...,
ValidationMode = ValidationMode.Local, // JWT
Provider = new OAuthBearerAuthenticationProvider()
{
OnValidateIdentity = ctx =>
{
// ... ALL OK
}
}
});
What am I missing?
Are you planning to release an asp.net vnext version of this package?
Is it possible to use the new UseIdentityServerBearerTokenAuthentication with our existing implementation of IdentityServerV2?
I am looking at securing our Owin WebApi applications by requiring that they receive a token with certain claims required. I see that UseIdentityServerBearerTokenAuthentication allows you to specify the Authority but I don't see a similar endpoint in V2.
I also see that it can be configured for ValidationMode.Local but I am not finding any examples for this.
So I have an MVC6 application, with an Identity Server, and another web application that uses AccessTokenValidation for JWTs with local validation. (I tried Authority and it has the same problem).
On the secondary app I have a controller action with an Authorize attribute. When I invoke this action, I see that there is a first chance SecurityTokenExpiredException with a message of "Lifetime validation failed. The token is expired."
But the action is still called, with a principal that has no claims.
If I call the action without a token, I get a 401.
Is this the expected behavior? And if not, is this likely to be something specific to MVC6 that is just not supported yet? It seems to me that a 401 response would be more appropriate, but I may be mistaken about that :)
I'm using the following code to ensure my access token is correct
JwtSecurityTokenHandler.InboundClaimTypeMap = ClaimMappings.None;
app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
{
Authority = "https://localhost:44310/identity",
RequiredScopes = new[] { "csRA" },
});
I was expecting that any request that came through that did not have this scope would return a 404 and exit the pipeline, but instead it seems as though the pipeline continues with an unauthenticated user instead.
I'm using Owin and WebApi 2.2 and the above are the first lines in my startup class. Should I be adding this method to the end of my startup instead?
in OWIN not mapping to ctor of scope middleware.
Any chance/idea of/for multi tenancy support using the bearer token middleware?
Perhaps instead of taking a single set of options - take a discovery call back that would return a set of options at run-time (based on environment/url etc. - that's up to the callback)?
I've configured the logging in IdentityServer3 to record a correlation ID, if this is sent in a header.
When using the UseIdentityServerBearerTokenAuthentication
extension, I'd like to be able to add such a correlation header before the request is made in ValidationEndpointTokenProvider.ReceiveAsync
.
I can copy and paste the whole of `ValidationEndpointTokenProvider' and replace the line:
var response = await _client.GetAsync(url);
with something like:
var request = new HttpRequestMessage(HttpMethod.Get, url);
var correlationId = context.Request.GetCorrelationId();
request.SetCorrelationId(correlationId);
var response = await _client.SendAsync(request);
But I would then have to copy & paste IdentityServerAccessTokenValidationAppBuilderExtensions
as the ValidationEndpointTokenProvider
is hard-coded:
internal static void UseValidationEndpoint(this IAppBuilder app, IdentityServerBearerTokenAuthenticationOptions options)
{
if (options.EnableValidationResultCache)
{
if (options.ValidationResultCache == null)
{
options.ValidationResultCache = new InMemoryValidationResultCache(options);
}
}
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
{
AccessTokenProvider = new ValidationEndpointTokenProvider(options),
Provider = options.Provider
});
}
So I was wondering if one of the following might be possible:
public Action<AuthenticationTokenReceiveContext, HttpRequestMessage) PreReceiveCallback {get; set;}
PreReceiveCallback = (context, request) => {
var correlationId = context.Request.GetCorrelationId();
request.SetCorrelationId(correlationId);
}
Does this library support reading the access token from a cookie? (I.e. a HTTPS only cookie).
Regards,
Daníel
UseIdentityServerJwt currently derives the Audience from the issuer name by appending "/resources". When using OpenID Connect with Access Code and retrieving a JWT token via a call to /token the audience in the JWT token is set to the ClientId.
Scenario:
We use identity server to retrieve an access token (page redirect) and translate it to a JWT token (javascript). We then use that JWT token to access the web api endpoint. The web api endpoint is configured using discovery mode, but that does not work as the audiences do not match.
I understand that the audience is specific per client application and the discovery is identity-server wide, so the audience cannot be discovered for all client applications.
Could we make the audience configurable or am I completley missing something?
Hi, I'm not sure if I am just being dense but I try to install either version of IdentityServer3.AccessTokenValidation (2.3 or 1.2.2) and neither of them seem to get referenced correctly for me..
They both list dependency of:
Microsoft.AspNet.WebApi.Client (>5.2.2).
Does this work with MV6? If so what am I doing wrong? Or is the correct approach to use:
app.UseOAuthBearerAuthentication(options =>
{
options.Authority = “https://localhost:44300″;
options.Audience = “https://localhost:44300/resources”;
options.AutomaticAuthentication = true;
});
Hi,
I am using the UseIdentityServerBearerTokenAuthentication() OWIN middleware to protect APIs in a couple of applications.
In both cases, this seems to work fine for a while, but after a day or two the API returns "Unauthorized" for requests with valid access tokens. Restarting the API application in IIS temporarily resolves the issue. After a restart, valid tokens that were rejected by the API, are accepted again.
This indicates that there is likely an issue in the implementation of the IdentityServerBearerTokenAuthentication, or in the underlying JwtTokenAuthentication middleware.
The issue is somewhat difficult to debug because the middleware works to start with and seems to stop working at random. Perhaps the issues is linked to some sort of caching mechanism or something?
It's too painful to create the TokenValidationParameters
manually to get Name and Role claim type set on the ClaimsIdentity. Perhaps we can make that easier.
As noted here setting a custom provider or setting a custom function to the OnRequestToken of the default provider does not work. Here are my examples
app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
{
Authority = "https://localhost:44300/identity",
RequiredScopes = new[] {"csRA"},
Provider = new CustomOAuthBearerProvider("access_token")
});
or here
var options = new IdentityServerBearerTokenAuthenticationOptions
{
Authority = "https://login.codysoft.net/identity",
RequiredScopes = new[] {"csRA"},
Provider = new OAuthBearerAuthenticationProvider
{
OnRequestToken = context =>
{
var request = context.Request;
if (request.Headers.ContainsKey("Authorization"))
context.Token = request.Headers["Authorization"];
else if (request.Cookies["access_token"] != null)
context.Token = request.Cookies["access_token"];
else
{
var value = request.Query.Get("access_token");
if (!string.IsNullOrEmpty(value))
{
context.Token = value;
}
}
return Task.FromResult<object>(null);
}
},
};
app.UseIdentityServerBearerTokenAuthentication(options);
no break point is hit in either sample. It appears to be ignored completely.
Hello, I was using the app.UseIdentityServerJwt() extension method, but after updating to the latest release (1.0.0-beta3-2) the method no longer exists. Was it moved? What should be used instead for validation?
Thx
I have hosted my API and Identity Server v3 on the same website and deployed it on an Azure Web App.
Everything works fine when I only have one instance of my web application, but when I scale it to two or more instances, I may have an Unauthorized http response when calling the API (idsrv always return a token, so no problem with it).
This is the client code :
OAuth2Client client = new OAuth2Client(new Uri("https://<host>/idsrv/connect/token"), "clientId", "clientSecret");
TokenResponse response = client.RequestClientCredentialsAsync("scope").Result;
using (HttpClient webClient = new HttpClient())
{
webClient.SetBearerToken(response.AccessToken);
Uri webApiUri = new Uri("https://<host>" + string.Format(CultureInfo.InvariantCulture, "/account/user");
HttpResponseMessage httpResponse = webClient.GetAsync(webApiUri).Result;
}
The API is secured by using UseIdentityServerBearerTokenAuthentication.
The machine key is synchronized between all instances of the web application (It is set in the web.config).
Is there someone who already had this load-balancing issue ? I do not have any clue to solve it :/
Thanks in advance for your reply.
Best regards.
I have everything working with AccessTokenValidation 1.2.2, but when I upgrade the library to 2.2.0 I get the following NullReferenceException. I don't have this running on the same server as the IdentityServer.
at IdentityServer3.AccessTokenValidation.ValidationEndpointTokenProvider..ctor(IdentityServerBearerTokenAuthenticationOptions options, ILoggerFactory loggerFactory) in c:\etc\Dropbox\identity\IdentityServer3\AccessTokenValidation\source\AccessTokenValidation\Plumbing\ValidationEndpointTokenProvider.cs:line 39
at Owin.IdentityServerBearerTokenValidationAppBuilderExtensions.ConfigureEndpointValidation(IdentityServerBearerTokenAuthenticationOptions options, ILoggerFactory loggerFactory) in c:\etc\Dropbox\identity\IdentityServer3\AccessTokenValidation\source\AccessTokenValidation\IdentityServerBearerTokenValidationAppBuilderExtensions.cs:line 92
at Owin.IdentityServerBearerTokenValidationAppBuilderExtensions.UseIdentityServerBearerTokenAuthentication(IAppBuilder app, IdentityServerBearerTokenAuthenticationOptions options) in c:\etc\Dropbox\identity\IdentityServer3\AccessTokenValidation\source\AccessTokenValidation\IdentityServerBearerTokenValidationAppBuilderExtensions.cs:line 55
at MyProject.Startup.<>c__DisplayClass1_0.<Configure>b__2(IAppBuilder builder) in C:\MyApp\src\MyProject\Startup.cs:line 55
at MyProject.IApplicationBuilderExtensions.<>c__DisplayClass0_0.<UseAppBuilder>b__1(Func`2 next) in C:\MyApp\src\MyProject\IApplicationBuilderExtensions.cs:line 21
at Microsoft.AspNet.Builder.OwinExtensions.<>c__DisplayClass0_1.<UseOwin>b__1(RequestDelegate next1)
at Microsoft.AspNet.Builder.Internal.ApplicationBuilder.Build()
at Microsoft.AspNet.Hosting.Internal.HostingEngine.BuildApplication()
at Microsoft.AspNet.Hosting.Internal.HostingEngine.Start()
at Microsoft.AspNet.Loader.IIS.RuntimeHttpApplication.ApplicationStart(IHttpApplication application)
at Microsoft.AspNet.Loader.IIS.HttpApplicationBase.InvokeApplicationStart(IHttpApplication application)
It's erroring on the builder.UseIdentityServerBearerTokenAuthentication(options); part of my Startup.cs file:
public void Configure(IApplicationBuilder app, ILoggerFactory loggerfactory)
{
...
var options = new IdentityServerBearerTokenAuthenticationOptions
{
Authority = "http://my-identity-server/oauth",
RequiredScopes = new string[] { "my_api" },
IssuerName = "My Auth Server",
SigningCertificate = Certificate.Get()
};
app.UseAppBuilder(builder => { builder.UseIdentityServerBearerTokenAuthentication(options); }, "WebApi");
app.UseMvc();
}
And here is the IApplicationBuilderExtensions class:
public static class IApplicationBuilderExtensions
{
public static IApplicationBuilder UseAppBuilder(this IApplicationBuilder app, Action<IAppBuilder> configure, string owinHostAppName)
{
app.UseOwin(addToPipeline =>
{
addToPipeline(next =>
{
var builder = new Microsoft.Owin.Builder.AppBuilder();
builder.Properties["builder.DefaultApp"] = next;
builder.Properties["host.AppName"] = owinHostAppName;
configure(builder);
var appFunc = builder.Build(typeof(Func<IDictionary<string, object>, Task>)) as Func<IDictionary<string, object>, Task>;
return appFunc;
});
});
return app;
}
}
Hi,
i have a question. What is the best approach for downloading files from SPA. Because i'm using bearer token authentication, i'm not able to simply open new window with url for download. Also i don't want to handle cookies in my SPA or downloading with AJAX. Is it good idea to open new window with authorization endpoint with post redirect to download URL? If so, can be used the endpoint/local validation to retrieve claims from the POST request exactly as for token in "Authorization" header?
Thanks alot for your advice
When using a ValidationModel.Local
or ValidationMode.Both
. Per the docs the discovery endpoint is hit to look up the IssuerName
and SigningCertificate
.
However, when hosting IDS3 in the same Katana app the discovery endpoint (obviously) isn't available. UseIdentityServerBearerTokenAuthentication
throws:
An exception of type 'System.InvalidOperationException' occurred in IdentityServer3.AccessTokenValidation.dll but was not handled in user code
Additional information: IDX10803: Unable to create to obtain configuration from: 'http://localhost:14869/identity/.well-known/openid-configuration'.
I understand this probably isn't a common use-case, but is a valid one? Small repro (modified Simplest OAuth2 Walkthrough sample): https://gist.github.com/zsims/f15b11de7b96c61f2ef5
saves the token as a claim. probably on by default.
Would it be a good idea to add the ability to pass an instance of IOAuthBearerAuthenticationProvider to be set as the Provider in SelfContainedTokenValidationExtensions. ConfigureMiddleware. That way you can utilize the UserInfoClient to get user info claims. Thoughts or better idea?
for idsrv v2
I don't think the middleware is currently checking the token expiration if the token is found in the cache. It might make sense to do so.
Error CS0433: The type 'JwtSecurityTokenHandler' exists in both 'System.IdentityModel.Tokens.Jwt, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' and 'System.IdentityModel.Tokens, Version=5.0.0.0, Culture=neutral, PublicKeyToken=null'.
Steps:
Dependency conflict:
Thinktecture.IdentityServer.v3.AccessTokenValidation (1.0.0-rc) >
Microsoft.Owin.Security.Jwt (3.0.0) >
System.IdentityModel.Tokens.Jwt (4.0.0)
And
Thinktecture.IdentityServer.v3.AccessTokenValidation (1.0.0-rc) >
Microsoft.IdentityModel.Protocol.Extensions (2.0.0-beta1-01112054-1) >
System.IdentityModel.Tokens (5.0.0-beta1-01112054-1)
I have an Id server from examples:
app.Map("/id", idsrvApp => {
var factory = new IdentityServerServiceFactory();
var scopeStore = new InMemoryScopeStore(Scopes.Get());
factory.ScopeStore = new IdentityServer3.Core.Configuration.Registration<IScopeStore>(scopeStore);
var clientStore = new InMemoryClientStore(Clients.Get());
factory.ClientStore = new IdentityServer3.Core.Configuration.Registration<IClientStore>(clientStore);
var userStore = new InMemoryUserService(Users.Get());
factory.UserService = new IdentityServer3.Core.Configuration.Registration<IUserService>(userStore);
idsrvApp.UseIdentityServer(new IdentityServerOptions {
IssuerUri = "https://localhost:44333",
PublicOrigin = "https://localhost:44333",
SiteName = "Embedded IdentityServer",
SigningCertificate = Certificate.Get(),
RequireSsl = false,
Factory = factory
});
});
When I add this to either top-level pipeline or just to app.Map("/api", appApi => {
I have an error "IDX10803: Unable to create to obtain configuration from... "
app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions {
Authority = "https://localhost:44333/id",
//RequiredScopes = new[] { "api" },
});
I looked into existing issues about bad SSL etc., but after I added all source code to my project I realized that UseIdentityServerBearerTokenAuthentication
calls RetrieveMetadata()
synchronously, but this is not possible because we are in the Startup and IdSrv is not yet working until we finish the entire startup config. So there is a deadlock.
In the MVC example I see that API in a separate project, but this is less convenient. I have a project based on the standard MVC5 template. I have WebAPI controllers in a separate assembly, but they are all hosted together with a couple of MVC controllers in a WebHost project.
Is there a way to use bearer tokens in a setup with a single host? Or how to configure the existing MVC5 bearer token support to use IdSrv3 tokens?
// Enable the application to use bearer tokens to authenticate users
app.UseOAuthBearerTokens(OAuthOptions);
Hi,
I'm using UseIdentityServerBearerTokenAuthentication to validate access token in my WebApi2 backend.
Is there some Notification or Event to call the User information Endpoint after validation?
I searched code but no success.
Thanks in advance
V
If i have an api endpoint that looks like this
[Authorize]
[HttpGet]
public async Task GetSensitiveData(string userId)
validating the jwt token validate the issuer and audience , but where and how do i check the subject claim in the access token matches the user id requested?
should it just be part of the endpoint logic? or is there a more elegant way? some kind of middleware?
also, if my endpoint looked like this:
public async Task GetSensitiveData(string someResourceId)
what would be the best way to make sure the user requesting the resouce has access to it?
where should this permission (user to resouce) be saved? in the identity server or api?
Thanks!
Will this work with SignalR or should we go the route of app.UseJsonWebToken as specified here: IdentityServer/IdentityServer3#357
You have an inconsistency in your code:
This means that you expect to assign an array of strings (string[]) with an IEnumerable... which I don't think you will succeed :)... (only the other way around is possible)
Getting back to your code
var authOptions =
new IdentityServerBearerTokenAuthenticationOptions
{
Authority = "https://localhost:44333",
RequiredScopes = new[] { "api1" }
});
app.UseIdentityServerBearerTokenAuthentication(authOptions);
This will work due to the fact that even though RequiredScopes is an IEnumerable, you instantiate it with an array of strings; this means that
typeof(string[]).IsInstanceOf(authOptions.RequiredScopes) = TRUE
var authOptions = new IdentityServerBearerTokenAuthenticationOptions
{
Authority = "https://localhost:44333",
RequiredScopes = GetScopes()
});
app.UseIdentityServerBearerTokenAuthentication(authOptions);
private static IEnumerable<string> GetScopes()
{
yield return "api1";
}
typeof(string[]).IsInstanceOf(authOptions.RequiredScopes) = FALSE -> thus no ctor matching
PS: Owin casts the params of the middleware to an object array
Im trying to add an users API in my identityserver (IdentityServer3 2.x) solution.
Im getting this error when adding the UseIdentityServerBearerTokenAuthentication to startup. Is there a conflict with the other mappings of "core" or? Thanks in advance.
Some code from Startup:
// API Config
app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
{
Authority = Settings.Default.Authority,
RequiredScopes = new[] { "idmgr" }
});
// web api configuration
var config = new HttpConfiguration();
config.Formatters.Remove(config.Formatters.XmlFormatter);
config.MapHttpAttributeRoutes();
app.UseWebApi(config);
The error:
[NullReferenceException: Object reference not set to an instance of an object.]
IdentityServer3.AccessTokenValidation.DiscoveryDocumentIssuerSecurityTokenProvider..ctor(String discoveryEndpoint, IdentityServerBearerTokenAuthenticationOptions options, ILoggerFactory loggerFactory) in c:\Dropbox\identity\IdentityServer3\AccessTokenValidation\source\AccessTokenValidation\Plumbing\DiscoveryDocumentIssuerSecurityTokenProvider.cs:43
Owin.IdentityServerBearerTokenValidationAppBuilderExtensions.ConfigureLocalValidation(IdentityServerBearerTokenAuthenticationOptions options, ILoggerFactory loggerFactory) in c:\Dropbox\identity\IdentityServer3\AccessTokenValidation\source\AccessTokenValidation\IdentityServerBearerTokenValidationAppBuilderExtensions.cs:105
Owin.IdentityServerBearerTokenValidationAppBuilderExtensions.UseIdentityServerBearerTokenAuthentication(IAppBuilder app, IdentityServerBearerTokenAuthenticationOptions options) in c:\Dropbox\identity\IdentityServer3\AccessTokenValidation\source\AccessTokenValidation\IdentityServerBearerTokenValidationAppBuilderExtensions.cs:50
Identity.Jeded.Web.Startup.Configuration(IAppBuilder app) in ..\Source\Workspaces\Jeded\Identity.Jeded\Identity.Jeded.Web\Startup.cs:120
[TargetInvocationException: Exception has been thrown by the target of an invocation.]
System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) +0
System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments) +128
System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +146
Owin.Loader.<>c__DisplayClass12.<MakeDelegate>b__b(IAppBuilder builder) +93
Owin.Loader.<>c__DisplayClass1.<LoadImplementation>b__0(IAppBuilder builder) +209
Microsoft.Owin.Host.SystemWeb.OwinAppContext.Initialize(Action`1 startup) +843
Microsoft.Owin.Host.SystemWeb.OwinBuilder.Build(Action`1 startup) +51
Microsoft.Owin.Host.SystemWeb.OwinHttpModule.InitializeBlueprint() +101
System.Threading.LazyInitializer.EnsureInitializedCore(T& target, Boolean& initialized, Object& syncLock, Func`1 valueFactory) +141
Microsoft.Owin.Host.SystemWeb.OwinHttpModule.Init(HttpApplication context) +172
System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers) +619
System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context) +175
System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context) +441
System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext) +360
[HttpException (0x80004005): Exception has been thrown by the target of an invocation.]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +579
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +112
System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +726
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.