diogodamiani / identityserver4.contrib.mongodb Goto Github PK
View Code? Open in Web Editor NEWMongoDB persistence layer for IdentityServer4
License: Apache License 2.0
MongoDB persistence layer for IdentityServer4
License: Apache License 2.0
How do you use this library exactly? Are there any examples?
The Client entity saved to Mongo contains the boolean PrefixClientClaims property. However, this is no longer recognized by the latest .net core 2.0 version of IdentityServer4 and the new ClientClaimsPrefix property is not persisted.
Hi!
Is there any update for the new version of .netcore?
hello, what the reases?
System.NotSupportedException: ToModel of type IdentityServer4.MongoDB.Mappers.ApiScopeMappers is not supported in the expression tree {document}.ToModel().
at MongoDB.Driver.Linq.Translators.AggregateLanguageTranslator.TranslateMethodCall(MethodCallExpression node)
at MongoDB.Driver.Linq.Translators.AggregateLanguageTranslator.TranslateValue(Expression node)
at MongoDB.Driver.Linq.Translators.AggregateLanguageTranslator.TranslateDocumentWrappedField(FieldAsDocumentExpression expression)
at MongoDB.Driver.Linq.Translators.AggregateLanguageTranslator.TranslateValue(Expression node)
at MongoDB.Driver.Linq.Translators.AggregateLanguageTranslator.Translate(Expression node, ExpressionTranslationOptions translationOptions)
at MongoDB.Driver.Linq.Translators.QueryableTranslator.TranslateProjectValue(Expression selector)
at MongoDB.Driver.Linq.Translators.QueryableTranslator.TranslateSelect(SelectExpression node)
at MongoDB.Driver.Linq.Translators.QueryableTranslator.TranslatePipeline(PipelineExpression node)
at MongoDB.Driver.Linq.Translators.QueryableTranslator.Translate(Expression node, IBsonSerializerRegistry serializerRegistry, ExpressionTranslationOptions translationOptions)
at MongoDB.Driver.Linq.MongoQueryProviderImpl1.Translate(Expression expression) at MongoDB.Driver.Linq.MongoQueryProviderImpl
1.Execute(Expression expression)
at MongoDB.Driver.Linq.MongoQueryableImpl2.GetEnumerator() at System.Linq.Enumerable.SelectEnumerableIterator
2.MoveNext()
at System.Linq.Lookup2.Create(IEnumerable
1 source, Func2 keySelector, IEqualityComparer
1 comparer)
at System.Linq.GroupedEnumerable2.GetEnumerator() at System.Linq.Enumerable.WhereSelectEnumerableIterator
2.ToArray()
at IdentityServer4.Stores.IResourceStoreExtensions.GetDuplicates(IEnumerable1 names) at IdentityServer4.Stores.IResourceStoreExtensions.Validate(IEnumerable
1 identity, IEnumerable1 apiResources, IEnumerable
1 apiScopes)
at IdentityServer4.Stores.IResourceStoreExtensions.FindResourcesByScopeAsync(IResourceStore store, IEnumerable1 scopeNames) at IdentityServer4.Stores.IResourceStoreExtensions.FindEnabledResourcesByScopeAsync(IResourceStore store, IEnumerable
1 scopeNames)
at IdentityServer4.Validation.DefaultResourceValidator.ValidateRequestedResourcesAsync(ResourceValidationRequest request)
at IdentityServer4.Validation.TokenRequestValidator.ValidateRequestedScopesAsync(NameValueCollection parameters, Boolean ignoreImplicitIdentityScopes, Boolean ignoreImplicitOfflineAccess)
at IdentityServer4.Validation.TokenRequestValidator.ValidateClientCredentialsRequestAsync(NameValueCollection parameters)
at IdentityServer4.Validation.TokenRequestValidator.RunValidationAsync(Func`2 validationFunc, NameValueCollection parameters)
at IdentityServer4.Validation.TokenRequestValidator.ValidateRequestAsync(NameValueCollection parameters, ClientSecretValidationResult clientValidationResult)
at IdentityServer4.Endpoints.TokenEndpoint.ProcessTokenRequestAsync(HttpContext context)
at IdentityServer4.Endpoints.TokenEndpoint.ProcessAsync(HttpContext context)
at IdentityServer4.Hosting.IdentityServerMiddleware.Invoke(HttpContext context, IEndpointRouter router, IUserSession session, IEventService events, IBackChannelLogoutService backChannelLogoutService)
at IdentityServer4.Hosting.IdentityServerMiddleware.Invoke(HttpContext context, IEndpointRouter router, IUserSession session, IEventService events, IBackChannelLogoutService backChannelLogoutService)
at IdentityServer4.Hosting.MutualTlsEndpointMiddleware.Invoke(HttpContext context, IAuthenticationSchemeProvider schemes)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at IdentityServer4.Hosting.BaseUrlMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
When I configure the identityserver appears the next error:
Method 'FindIdentityResourcesByScopeNameAsync' in type 'IdentityServer4.MongoDB.Stores.ResourceStore' from assembly 'IdentityServer4.Contrib.MongoDB, Version=2.3.4.0, Culture=neutral, PublicKeyToken=null' does not have an implementation
And if I add this DI:
builder.Services.AddTransient<IClientStore, IdentityServer4.MongoDB.Stores.ClientStore>();
The error is that I need the version 2.3.1.0 of Identityserver4.Storage
Thanks for all!
Dear @diogodamiani
Could you please push the newest version from Git to Nuget?
The latest version on nuget is from 2017
Kind regards,
Teun
How can I have identityserver to connect to MongoDB over TLS? AFAIK, MongoDB.Driver.SslSettings is not exposed.
Hi diogodamiani
Could you please help us in integrating user management like register page with identityserver4 and MongoDB.
Thanks
Any technical reason why this targets net461?
Hello
thanks for the great work
i have a issue on version 4.0.0-rc.2 due to automapper configuration
adding a client claim and store it runs perfectly
but fetching it fails because of a type mapping missing between claim client and securityclaim
code to reproduce
Client c= new Client()
{
ClientId = clientId,
AllowedScopes = new List(new string[] { "dsquad:public" }),
ClientSecrets = secrets,
AllowedGrantTypes = GrantTypes.ClientCredentials,
AccessTokenType = AccessTokenType.Jwt,
AccessTokenLifetime = int.MaxValue,
Enabled = true,
AlwaysSendClientClaims = true,
ClientClaimsPrefix = ""
};
c.Claims.Add(new ClientClaim("hello", ""world"));
c.ToEntity().ToModel(); // throw exception
Hi,
I'm getting and exception System.NotSupportedException in CorsPolicyService when calling the token endpoint directly from postman. This can be reproduced by starting the host project and call the token endpoint using this setup
POST /connect/token HTTP/1.1
Host: localhost:1941
Authorization: Basic Y2xpZW50OnNlY3JldA==
Origin: *
Content-Type: application/x-www-form-urlencoded
Cache-Control: no-cache
Postman-Token: c5627d4f-41bc-4b11-d9fd-82ecc3e78ebe
grant_type=client_credentials&scope=api1
And the exception details
An exception of type 'System.NotSupportedException' occurred in MongoDB.Driver.dll but was not handled in user code
Additional information: Unable to determine the serialization information for the collection selector in the tree: aggregate([]).SelectMany(x => x.AllowedCorsOrigins.Select(y => y.Origin))
When mapping from one of IdentityResource
, ApiResource
or ApiScope
entities to their corresponding models, the UserClaim
s will not be mapped correctly. Instead of containing a list of claims, the property will contain a single list entry with the claim type being its value.
E.g. IdentityResource
contains claims of type IdentityClaim
. When mapping it, the resulting model will contain a single entry with value "IdentityServer4.MongoDB.Entities.IdentityClaim".
I didn't understand it to all detail, but I think this is because AutoMapper neglects the Select(x => x.Type)
part of the expression determining what to map. Hence, it will try to map a UserClaim
object to string by calling its ToString
method. This results in its FQCN being mapped into the resulting collection.
There are two workarounds for this. Either implement a ToString
method for the claim types or configure AutoMapper to map UserClaim
objects to string by using its Type
property. In a small POC I've chosen the latter because I think this is a pure mapping issue and should be resolved there.
This issue exists for documenting purposes, a PR is already in the making.
Hi,How are you
After I released the code directly deployed to Centos environment, and then use the Client Demo connection, an error, required to HTTPS requests, but in the browser is HTTP and HTTPS can access this address
Error connecting to http://192.168.1.111/.well-known/openid-configuration: HTTPS required
What are the possible causes of this error?
Hello. After some load testing I've noticed that both PersistedGrantDbContext and ConfigurationDbContext call CreateIndexes/ CreateClientsIndexes in constructor which results in noticeable load. As I can see there is no way to skip this behavior. Maybe it will be more reasonable to create indexes on app start?
Thanks.
Hi,
I use your library In my project (.net core 3.1). I update it from 2.3.3 version to 2.3.4. In 2.3.4 in development mode this exception it is raised when the application start:
Exception thrown: 'System.TimeoutException' in MongoDB.Driver.Core.dll
An exception of type 'System.TimeoutException' occurred in MongoDB.Driver.Core.dll but was not handled in user code
A timeout occured after 30000ms selecting a server using CompositeServerSelector{ Selectors = MongoDB.Driver.MongoClient+AreSessionsSupportedServerSelector, LatencyLimitingServerSelector{ AllowedLatencyRange = 00:00:00.0150000 } }. Client view of cluster state is { ClusterId : "2", ConnectionMode : "Automatic", Type : "Unknown", State : "Disconnected", Servers : [{ ServerId: "{ ClusterId : 2, EndPoint : "Unspecified/s-my-server-mongo:27017" }", EndPoint: "Unspecified/s-my-server-mongo:27017", ReasonChanged: "Heartbeat", State: "Disconnected", ServerVersion: , TopologyVersion: , Type: "Unknown", HeartbeatException: "MongoDB.Driver.MongoConnectionException: An exception occurred while opening a connection to the server.
---> System.IO.IOException: Unable to read data from the transport connection: Connessione in corso interrotta forzatamente dall'host remoto..
---> System.Net.Sockets.SocketException (10054): Connessione in corso interrotta forzatamente dall'host remoto.
--- End of inner exception stack trace ---
at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.ThrowException(SocketError error, CancellationToken cancellationToken)
at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.GetResult(Int16 token)
at System.Net.FixedSizeReader.ReadPacketAsync(Stream transport, AsyncProtocolRequest request)
at System.Net.Security.SslStream.EndProcessAuthentication(IAsyncResult result)
at System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic(IAsyncResult iar, Func`2 endFunction, Action`1 endAction, Task`1 promise, Boolean requiresSynchronization)
--- End of stack trace from previous location where exception was thrown ---
at MongoDB.Driver.Core.Connections.SslStreamFactory.CreateStreamAsync(EndPoint endPoint, CancellationToken cancellationToken)
at MongoDB.Driver.Core.Connections.BinaryConnection.OpenHelperAsync(CancellationToken cancellationToken)
--- End of inner exception stack trace ---
at MongoDB.Driver.Core.Connections.BinaryConnection.OpenHelperAsync(CancellationToken cancellationToken)
at MongoDB.Driver.Core.Servers.ServerMonitor.InitializeConnectionAsync(CancellationToken cancellationToken)
at MongoDB.Driver.Core.Servers.ServerMonitor.HeartbeatAsync(CancellationToken cancellationToken)", LastHeartbeatTimestamp: "2021-04-14T09:22:13.1362689Z", LastUpdateTimestamp: "2021-04-14T09:22:13.1362690Z" }] }.
my connection string is:
mongodb://s-my-server-mongo:27017
It has no auth parameter (it's a server unreachable from outside).
I pass also the Database name
.AddOperationalStore(opt => {
opt.ConnectionString = "mongodb://s-my-server-mongo:27017";
opt.Database = "TestIdentityDb";
})
So I don't understand why there is this row:
EndPoint : "Unspecified/s-my-server-mongo:27017"
I revert to 2.3.3 at the moment. Note I also update the mongo.db.driver (i use the latest version available 2.12.2)
Using IS4 2.3.2 and getting FormatException: Element '_id' does not match any field or property of class IdentityServer4.MongoDB.Entities.PersistedGrant. I see that PersistedGrant model has Id property commented out, is this the reason for the error?
Full stack trace:
System.FormatException: Element '_id' does not match any field or property of class IdentityServer4.MongoDB.Entities.PersistedGrant.
at MongoDB.Driver.Linq.MongoQueryProviderImpl1.Execute(Expression expression) at MongoDB.Driver.Linq.MongoQueryProviderImpl
1.Execute[TResult](Expression expression)
at System.Linq.Queryable.FirstOrDefault[TSource](IQueryable1 source, Expression
1 predicate)
at IdentityServer4.MongoDB.Stores.PersistedGrantStore.GetAsync(String key) in I:\projects\git\IdentityServer4.Contrib.MongoDB\src\IdentityServer4.MongoDB\Stores\PersistedGrantStore.cs:line 45
at IdentityServer4.Stores.DefaultGrantStore1.GetItemAsync(String key) in C:\local\identity\server4\IdentityServer4\src\Stores\Default\DefaultGrantStore.cs:line 89 at IdentityServer4.Services.DefaultConsentService.RequiresConsentAsync(ClaimsPrincipal subject, Client client, IEnumerable
1 scopes) in C:\local\identity\server4\IdentityServer4\src\Services\Default\DefaultConsentService.cs:line 97
at IdentityServer4.ResponseHandling.AuthorizeInteractionResponseGenerator.ProcessConsentAsync(ValidatedAuthorizeRequest request, ConsentResponse consent) in C:\local\identity\server4\IdentityServer4\src\ResponseHandling\Default\AuthorizeInteractionResponseGenerator.cs:line 240
at IdentityServer4.ResponseHandling.AuthorizeInteractionResponseGenerator.ProcessInteractionAsync(ValidatedAuthorizeRequest request, ConsentResponse consent) in C:\local\identity\server4\IdentityServer4\src\ResponseHandling\Default\AuthorizeInteractionResponseGenerator.cs:line 89
at IdentityServer4.Endpoints.AuthorizeEndpointBase.ProcessAuthorizeRequestAsync(NameValueCollection parameters, ClaimsPrincipal user, ConsentResponse consent) in C:\local\identity\server4\IdentityServer4\src\Endpoints\AuthorizeEndpointBase.cs:line 81
at IdentityServer4.Endpoints.AuthorizeEndpoint.ProcessAsync(HttpContext context) in C:\local\identity\server4\IdentityServer4\src\Endpoints\AuthorizeEndpoint.cs:line 55
at IdentityServer4.Hosting.IdentityServerMiddleware.Invoke(HttpContext context, IEndpointRouter router, IUserSession session, IEventService events) in C:\local\identity\server4\IdentityServer4\src\Hosting\IdentityServerMiddleware.cs:line 54
at IdentityServer4.Hosting.IdentityServerMiddleware.Invoke(HttpContext context, IEndpointRouter router, IUserSession session, IEventService events) in C:\local\identity\server4\IdentityServer4\src\Hosting\IdentityServerMiddleware.cs:line 69
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Cors.Infrastructure.CorsMiddleware.Invoke(HttpContext context)
at IdentityServer4.Hosting.BaseUrlMiddleware.Invoke(HttpContext context) in C:\local\identity\server4\IdentityServer4\src\Hosting\BaseUrlMiddleware.cs:line 36
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
I updated automapper to latest version.
System.MissingMethodException: Method not found: '!!0 AutoMapper.IMapper.Map(System.Object)'.\r\n at IdentityServer4.MongoDB.Mappers.PersistedGrantMappers.ToEntity(PersistedGrant token)\r\n at IdentityServer4.MongoDB.Stores.PersistedGrantStore.StoreAsync(PersistedGrant token)\r\n at IdentityServer4.Stores.DefaultGrantStore1.StoreItemAsync(String key, T item, String clientId, String subjectId, DateTime created, Nullable
1 expiration)\r\n at IdentityServer4.Stores.DefaultGrantStore`1.CreateItemAsync(T item, String clientId, String subjectId, DateTime created, Int32 lifetime)\r\n at IdentityServer4.Stores.DefaultRefreshTokenStore.StoreRefreshTokenAsync(RefreshToken refreshToken)\r\n at IdentityServer4.Services.DefaultRefreshTokenService.CreateRefreshTokenAsync(ClaimsPrincipal subject, Token accessToken, Client client)\r\n at IdentityServer4.ResponseHandling.TokenResponseGenerator.CreateAccessTokenAsync(ValidatedTokenRequest request)\r\n at IdentityServer4.ResponseHandling.TokenResponseGenerator.ProcessTokenRequestAsync(TokenRequestValidationResult validationResult)\r\n at IdentityServer4.ResponseHandling.TokenResponseGenerator.ProcessAsync(TokenRequestValidationResult request)\r\n at IdentityServer4.Endpoints.TokenEndpoint.ProcessTokenRequestAsync(HttpContext context)\r\n at IdentityServer4.Endpoints.TokenEndpoint.ProcessAsync(HttpContext context)\r\n at IdentityServer4.Hosting.IdentityServerMiddleware.Invoke(HttpContext context, IEndpointRouter router, IUserSession session, IEventService events)\r\n at IdentityServer4.Hosting.IdentityServerMiddleware.Invoke(HttpContext context, IEndpointRouter router, IUserSession session, IEventService events)\r\n at IdentityServer4.Hosting.MutualTlsTokenEndpointMiddleware.Invoke(HttpContext context, IAuthenticationSchemeProvider schemes)\r\n at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)\r\n at IdentityServer4.Hosting.BaseUrlMiddleware.Invoke(HttpContext context)\r\n at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.g__Awaited|6_0(ExceptionHandlerMiddleware middleware, HttpContext context, Task task)
Hi! i'm facing this connection timeout error:
A timeout occured after 30000ms selecting a server using CompositeServerSelector{ Selectors = MongoDB.Driver.MongoClient+AreSessionsSupportedServerSelector, LatencyLimitingServerSelector{ AllowedLatencyRange = 00:00:00.0150000 } }. Client view of cluster state is { ClusterId : "1", ConnectionMode : "ReplicaSet", Type : "ReplicaSet", State : "Disconnected", Servers : [{ ServerId: "{ ClusterId : 1, EndPoint : "Unspecified/schedulesystem.02a5g.azure.mongodb.net:27017" }", EndPoint: "Unspecified/schedulesystem.02a5g.azure.mongodb.net:27017", State: "Disconnected", Type: "Unknown", HeartbeatException: "MongoDB.Driver.MongoConnectionException: An exception occurred while opening a connection to the server.
my connection string seems fine and works when i connect directly by MongoClient. Also i can operate with the collections.
HI, i am facing this error and I have no idea how to check this :(
System.TypeLoadException: 'Method 'FindIdentityResourcesByScopeNameAsync' in type 'IdentityServer4.MongoDB.Stores.ResourceStore' from assembly 'IdentityServer4.Contrib.MongoDB, Version=2.3.4.0, Culture=neutral, PublicKeyToken=null' does not have an implementation.'
The code:
_ = services.AddIdentityServer().AddDeveloperSigningCredential()
// this adds the operational data from DB (codes, tokens, consents)
.AddConfigurationStore(options =>
{
options.ConnectionString = "mongodb://localhost/myDB";
})
.AddOperationalStore(options =>
{
options.ConnectionString = "mongodb://localhost/myDB";
})
.AddInMemoryIdentityResources(Config.GetIdentityResources())
.AddInMemoryApiResources(Config.GetApiResources())
.AddInMemoryClients(Config.GetClients())
.AddAspNetIdentity();
I want to use this package for operational data in IdentityServer 4 (.Net Core 3).
But I get warning about applicationLifetime. It is obsolete.
app.UseIdentityServerMongoDBTokenCleanup(applicationLifetime);
More info: https://docs.microsoft.com/en-us/dotnet/api/microsoft.extensions.hosting.iapplicationlifetime?view=dotnet-plat-ext-3.0&viewFallbackFrom=aspnetcore-2.1
Can you help me?
Trying to use the extension method to AddConfigurationStore, I am getting the following error...
The type 'IIdentityServerBuilder' is defined in an assembly that is not referenced. You must add a reference to assembly 'IdentityServer4, Version=2.0.4.0, Culture=neutral, PublicKeyToken=null'. [CRM.Identity.Host]
Not sure if we need to upgrade to v2.3.2, or if there is a workaround to resolve this.
Would be interested in hearing feedback.
Version 2.3.0 has a stable release.
How can I query to db to check user credential in mongo database. I dont want to use in memory client to test.
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.