Giter VIP home page Giter VIP logo

aspnet-identity-mongo's Introduction

Microsoft.AspNetCore.Identity.MongoDB

This is a MongoDB provider for the ASP.NET Core Identity framework. This was ported from the v2 Identity framework that was a part of ASP.NET (AspNet.Identity.Mongo NuGet package)

I've released a new package for the ASP.NET Core Identity framework for the following reasons:

  • Discoverability - named AspNetCore.
  • ASP.NET Core is a rewrite of ASP.NET, this Core Identity framework won't run on traditional ASP.NET.
  • Migrating isn't a matter of updating dependencies.

This project has extensive test coverage.

If you want something easy to setup, this adapter is for you. I do not intend to cover every possible desirable configuration, if you don't like my decisions, write your own adapter. Use this as a learning tool to make your own adapter. These adapters are not complicated, but trying to make them configurable would become a complicated mess. And would confuse the majority of people that want something simple to use. So I'm favoring simplicity over making every last person happy.

Usage

  • Reference this package in project.json: Microsoft.AspNetCore.Identity.MongoDB
  • Then, in ConfigureServices--or wherever you are registering services--include the following to register both the Identity services and MongoDB stores:
services.AddIdentityWithMongoStores("mongodb://localhost/myDB");
  • If you want to customize what is registered, refer to the tests for further options (CoreTests/MongoIdentityBuilderExtensionsTests.cs)
  • Remember with the Identity framework, the whole point is that both a UserManager and RoleManager are provided for you to use, here's how you can resolve instances manually. Of course, constructor injection is also available.
var userManager = provider.GetService<UserManager<IdentityUser>>();
var roleManager = provider.GetService<RoleManager<IdentityRole>>();
  • The following methods help create indexes that will boost lookups by UserName, Email and role Name. These have changed since Identity v2 to refer to Normalized fields. I dislike this aspect of Core Identity, but it is what it is. Basically these three fields are stored in uppercase format for case insensitive searches.
	IndexChecks.EnsureUniqueIndexOnNormalizedUserName(users);
	IndexChecks.EnsureUniqueIndexOnNormalizedEmail(users);
	IndexChecks.EnsureUniqueIndexOnNormalizedRoleName(roles);
  • Here is a sample project, review the commit log for the steps taken to port the default template from EntityFramework MSSQL to MongoDB. aspnet-identity-mongo-sample.

What frameworks are targeted, with rationale:

  • Microsoft.AspNetCore.Identity - supports net451 and netstandard1.3
  • MongoDB.Driver v2.3 - supports net45 and netstandard1.5
  • Thus, the lowest common denominators are net451 (of net45 and net451) and netstandard1.5 (of netstandard1.3 and netstandard1.5)
  • FYI net451 supports netstandard1.2, that's obviously too low for a single target

Building instructions

run commands in

Migrating from ASP.NET Identity 2.0

  • Roles names need to be normalized as follows
    • On IdentityRole documents, create a NormalizedName field = uppercase(Name). Leave Name as is.
    • On IdentityUser documents, convert the values in the Roles array to uppercase
  • User names need to be normalized as follows
    • On IdentityUser documents, create a NormalizedUserName field = uppercase(UserName) and create a NormalizedEmail field = uppercase(Email). Leave UserName and Email as is.

aspnet-identity-mongo's People

Contributors

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

aspnet-identity-mongo's Issues

New driver issue, easy fix.

I downloaded your package today and got it to work, but boy did I struggle having never done a custom identity before :)

There's a bugfix implemented in the mongo 2.1.1 drivers that stop your code from working, the fix is easy, just replaced [BsonRepresentation(BsonType.ObjectID)] with [BsonId] in both places it existed in the IdentityUser and IdentityRole, recompiled, and everything seems to be working for me.

Here's the two lines

    [BsonId]
    public string Id { get; private set; }

Seems kind of silly to do a fork and pull request for something this simple, but I certainly will if you wish, just let me know.

Thanks for doing this, I'm using it over at www.joshuaaustill.com, which is my little sandbox. I'll let you know if I run into anymore issues.

Have a great day!
Joshua Austill

Timeout at MongoDb connection

I tried to connect your sample https://github.com/g0t4/aspnet-identity-mongo-sample/tree/master/AspNetCore.WebApp.MongoDB with my MongoDb v3.4 Windows.
My ConnectionString is mongodb://admin:abc123@localhost/TestDb and with another ASP.NET Core app it works.
The log from MongoDb shows the following:
2017-04-25T09:56:49.102+0200 I NETWORK [thread1] connection accepted from 127.0.0.1:59254 #626 (7 connections now open) 2017-04-25T09:56:49.104+0200 I ACCESS [conn626] SCRAM-SHA-1 authentication failed for someadmin on ErpDb from client 127.0.0.1:59254 ; UserNotFound: Could not find user someadmin@ErpDb 2017-04-25T09:56:49.106+0200 I - [conn626] end connection 127.0.0.1:59254 (7 connections now open)

Implement IRoleStore

I'll add storage for this in a separate collection. It's just a list of names unless someone wants to extend the model in their own application.

Your simple example does not work

There's an issue with your example code:

var users = database.GetCollection<IdentityUser>("users");
var store = new UserStore<IdentityUser>(users);

This causes the following compile-time error:

"Argument 1: cannot convert from 'MongoDB.Driver.MongoCollection<IdentityUser>' to 'MongoDB.Driver.IMongoCollection<IdentityUser>'"

This is the first time I have tried using this nuget package. Perhaps something changed and you are working with an older version of the mongo driver? My nuget packages are as follows:

<package id="AspNet.Identity.MongoDB" version="2.0.8" targetFramework="net451" />
<package id="Microsoft.AspNet.Identity.Core" version="2.2.1" targetFramework="net451" />
<package id="Microsoft.AspNet.Identity.Owin" version="2.1.0" targetFramework="net451" />
<package id="mongocsharpdriver" version="2.2.3" targetFramework="net451" />
<package id="MongoDB.Bson" version="2.2.3" targetFramework="net451" />
<package id="MongoDB.Driver" version="2.2.3" targetFramework="net451" />
<package id="MongoDB.Driver.Core" version="2.2.3" targetFramework="net451" />

'45db8e65-d2de-44bc-b512-12750256dcb5' is not a valid 24 digit hex string.

Thanks for the library.
I have installed the nuget and followed the instruction as given in sample.
But whenever I am trying to run the project but I am getting '45db8e65-d2de-44bc-b512-12750256dcb5' is not a valid 24 digit hex string. this error. I am not able to figure out how to fix. I have the latest version of MVC "aspnet-identity-mongo". I am not using core.

Remove Index Checking from IdentityContext constructor

The intent was to have this checked once on application startup. However, consumers can't always control when the IdentityContext needs to be created to be used by the Identity framework.

Therefore, let's leave it up to consumers to decide when to check, if at all, for the unique indexes on user names and role names.

AddIdentityWithMongoStoresUsingCustomTypes with IdentityOptions

Is there a way to use the AddIdentityWithMongoStoresUsingCustomTypes with IdentityOptions like the sample code below?

services.AddIdentity<ApplicationUser, IdentityRole>(options => { options.Cookies.ApplicationCookie.AuthenticationScheme = "ApplicationCookie"; options.Cookies.ApplicationCookie.CookieName = "Interop"; options.Cookies.ApplicationCookie.DataProtectionProvider = DataProtectionProvider.Create(new DirectoryInfo("C:\\Github\\Identity\\artifacts")); })

Store does not implement IQueryableUserStore<TUser>

Hi There,

Thanks for the project. Great help.

I was unable to use it at first due to the error (also with IQueryableRoleStore):
Store does not implement IQueryableUserStore

I was able to extend the Stores to implement the missing features. This was kinda hacked together since I havent been able to look at the new MongoDB driver.
public virtual System.Linq.IQueryable Users
{
get
{
return _Users.Find(new BsonDocumentFilterDefinition(new BsonDocument())).ToListAsync().Result.AsQueryable();
}
}
Could you suggest what Ive done wrong with your original implementation?

Hope this helps!
Michael

Unhandled exception when receiving old EntityFramework cookies with guids

When converting a site from EntityFramework Identity, clients submitting old cookies will crash aspnet.identity.mongo. I can't see a way to filter this at a higher level. Can we add a more graceful way of handling this so asp.net will just fail to authenticate and redirect to login?

See error output below.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.FormatException: '5ab35807-cbe1-408e-b214-a11088b08163' is not a valid 24 digit hex string.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[FormatException: '5ab35807-cbe1-408e-b214-a11088b08163' is not a valid 24 digit hex string.]
MongoDB.Bson.ObjectId.Parse(String s) +216
MongoDB.Bson.Serialization.Serializers.StringSerializer.SerializeValue(BsonSerializationContext context, BsonSerializationArgs args, String value) +106
MongoDB.Bson.Serialization.Serializers.SealedClassSerializerBase1.Serialize(BsonSerializationContext context, BsonSerializationArgs args, TValue value) +45 MongoDB.Bson.Serialization.Serializers.SerializerBase1.MongoDB.Bson.Serialization.IBsonSerializer.Serialize(BsonSerializationContext context, BsonSerializationArgs args, Object value) +81
MongoDB.Bson.Serialization.IBsonSerializerExtensions.Serialize(IBsonSerializer serializer, BsonSerializationContext context, Object value) +116
MongoDB.Driver.Linq.Expressions.ISerializationExpressionExtensions.SerializeValue(ISerializationExpression field, Object value) +335
MongoDB.Driver.Linq.Translators.PredicateTranslator.TranslateComparison(Expression variableExpression, ExpressionType operatorType, ConstantExpression constantExpression) +409
MongoDB.Driver.Linq.Translators.PredicateTranslator.Translate(Expression node) +461
MongoDB.Driver.Linq.Translators.PredicateTranslator.Translate(Expression node, IBsonSerializerRegistry serializerRegistry) +38
MongoDB.Driver.MongoCollectionImpl1.FindAsync(FilterDefinition1 filter, FindOptions2 options, CancellationToken cancellationToken) +416 MongoDB.Driver.FindFluent2.ToCursorAsync(CancellationToken cancellationToken) +125
MongoDB.Driver.IFindFluentExtensions.FirstOrDefaultAsync(IFindFluent2 find, CancellationToken cancellationToken) +198 AspNet.Identity.MongoDB.UserStore1.FindByIdAsync(String userId) +540
Microsoft.AspNet.Identity.Owin.<b__1>d__4.MoveNext() +592
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +13847892
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +61
Microsoft.Owin.Security.Cookies.d__2.MoveNext() +2531
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +13847892
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +61
Microsoft.Owin.Security.Infrastructure.d__0.MoveNext() +822
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +13847892
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +61
Microsoft.Owin.Security.Infrastructure.d__0.MoveNext() +333
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +13847892
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +61
Microsoft.AspNet.Identity.Owin.d__0.MoveNext() +450
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +13847892
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +61
Microsoft.AspNet.Identity.Owin.d__0.MoveNext() +450
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +13847892
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +61
Microsoft.AspNet.Identity.Owin.d__0.MoveNext() +450
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +13847892
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +61
Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.d__5.MoveNext() +202
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +13847892
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +61
Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.d__2.MoveNext() +193
Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.StageAsyncResult.End(IAsyncResult ar) +96
System.Web.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +363
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +137

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.6.1055.0

Authorize(Roles="Admin") -attribute not working

When decorating my controller methods with i.e.:
Autorize(Roles="Admin")
I get the 404-errormessage "Not found".

If I remove Roles="Admin", it's all good (as long as the user has logged in of course).
I might be missing some fundamental stuff here, but if so - please enlighten me! :-)

Regards,
Yonzo

Reference to type 'IdentityBuilder' claims it is defined in 'Microsoft.AspNetCore.Identity', but it could not be found

Hi all,

Attempting to follow the steps in the quickstart. However, the line:

services.AddIdentityWithMongoStores("mongodb://localhost/myDB");

...throws a syntax error:

Reference to type 'IdentityBuilder' claims it is defined in 'Microsoft.AspNetCore.Identity', but it could not be found

I am referencing Microsoft.AspNetCore.Identity 2.2.0, however when I look within this .dll I cannot find any definition for this IdentityBuilder class. Even more confusingly, when I look at the source for 'Microsoft.AspNetCore.Identity', I can see references to that class within it. What the heck?

Problem with normalized roles

Hi,

I have a problem with this comment:

// todo might have issue, I'm just storing Normalized only now, so I'm returning normalized here instead of not normalized.
// EF provider returns not noramlized here
// however, the rest of the API uses normalized (add/remove/isinrole) so maybe this approach is better anyways
// note: could always map normalized to not if people complain
public virtual async Task<IList<string>> GetRolesAsync(TUser user, CancellationToken token)
=> user.Roles;

The problem is, that my javascript client gets the claims including the role and the role is in upper case. A little bit annoying.

please upgrade this library to .Net core 2.0?

I have tried to upgrade this class library to .Net core 2.0, without any issue.

In sample application, we have extension method - AddIdentityWithMongoStore. I was not able to find any reference to this on github code shared by you. Where is file MongoIdentityBuilderExtensions?

 // Register identity framework services and also Mongo storage. 
	        services.AddIdentityWithMongoStores(Configuration.GetConnectionString("DefaultConnection"))
		        .AddDefaultTokenProviders();

Appreciate if you can upgrade the library along with sharing code for MongoIdentityBuilderExtensions.

Thank you.

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.