Giter Site home page Giter Site logo

diogodamiani / identityserver4.contrib.mongodb Goto Github PK

View Code? Open in Web Editor NEW
111.0 14.0 58.0 580 KB

MongoDB persistence layer for IdentityServer4

License: Apache License 2.0

C# 82.65% CSS 0.84% PowerShell 3.60% Shell 1.74% JavaScript 0.10% HTML 9.97% Less 1.09%
identityserver identityserver4 mongodb

identityserver4.contrib.mongodb's Introduction

IdentityServer4.Contrib.MongoDB

Build status NuGet

MongoDB persistence layer for IdentityServer4 based on the Official EntityFramework persistence layer.

identityserver4.contrib.mongodb's People

Contributors

delepster avatar diogodamiani avatar gekiss avatar gizmohd avatar luizbon avatar repko-artem avatar tbureck avatar tioma18 avatar tortocan avatar vitrudchenko avatar xhevatibraimi avatar yan-oreshchenkov avatar yawnston avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

identityserver4.contrib.mongodb's Issues

System.NotSupportedException: ToModel of type IdentityServer4.MongoDB.Mappers.ApiScopeMappers is not supported in the expression tree {document}.ToModel().

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.MongoQueryProviderImpl1.Execute(Expression expression)
at MongoDB.Driver.Linq.MongoQueryableImpl2.GetEnumerator() at System.Linq.Enumerable.SelectEnumerableIterator2.MoveNext()
at System.Linq.Lookup2.Create(IEnumerable1 source, Func2 keySelector, IEqualityComparer1 comparer)
at System.Linq.GroupedEnumerable2.GetEnumerator() at System.Linq.Enumerable.WhereSelectEnumerableIterator2.ToArray()
at IdentityServer4.Stores.IResourceStoreExtensions.GetDuplicates(IEnumerable1 names) at IdentityServer4.Stores.IResourceStoreExtensions.Validate(IEnumerable1 identity, IEnumerable1 apiResources, IEnumerable1 apiScopes)
at IdentityServer4.Stores.IResourceStoreExtensions.FindResourcesByScopeAsync(IResourceStore store, IEnumerable1 scopeNames) at IdentityServer4.Stores.IResourceStoreExtensions.FindEnabledResourcesByScopeAsync(IResourceStore store, IEnumerable1 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)

Connection timeout

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.

.NetCore 2

Hi!

Is there any update for the new version of .netcore?

Faulty mapping of UserClaims in IdentityResource, ApiResource and ApiScope

When mapping from one of IdentityResource, ApiResource or ApiScope entities to their corresponding models, the UserClaims 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.

Method 'FindIdentityResourcesByScopeNameAsync' no implemented

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();

Thanks

Fails to work with v2.3.2 of IdentityServer.

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.

TimeOut connection in version 2.3.4 (2.3.3 have no problem)

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)

CreateIndexes call in DbContext constructor

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?
image
image

Thanks.

System.NotSupportedException exception in CorsPolicyService

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))

net461, why?

Any technical reason why this targets net461?

User Management

Hi diogodamiani
Could you please help us in integrating user management like register page with identityserver4 and MongoDB.

Thanks

mapper throw exception on clientclaims on 4.0.0-rc.2

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

IdentityServer4.Storage version

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!

PersistedGrant is missing Id

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.MongoQueryProviderImpl1.Execute[TResult](Expression expression)
at System.Linq.Queryable.FirstOrDefault[TSource](IQueryable1 source, Expression1 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, IEnumerable1 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)

.net core and last automapper.

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, Nullable1 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)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.