Permalink
Browse files

modified the sample for ASP.NET Identity MongoDB plugin

  • Loading branch information...
tugberkugurlu committed Nov 4, 2015
1 parent 926e38b commit 55dcc3e956a8152f74fb2a2503965f71f0124b7c
@@ -1,7 +1,7 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 14
VisualStudioVersion = 14.0.22013.1
VisualStudioVersion = 14.0.23107.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{0F647068-6602-4E24-B1DC-8ED91481A50A}"
EndProject
@@ -28,6 +28,8 @@ Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Microsoft.AspNet.Identity.E
EndProject
Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Microsoft.AspNet.Identity.EntityFramework", "src\Microsoft.AspNet.Identity.EntityFramework\Microsoft.AspNet.Identity.EntityFramework.xproj", "{4490894C-3572-4E63-86F1-EE5105CE8A06}"
EndProject
Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Dnx.Identity.MongoDB", "..\ModernShopping\Auth\src\Dnx.Identity.MongoDB\Dnx.Identity.MongoDB.xproj", "{B195CD03-F3D7-4DEA-A009-6CDD351462EF}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -108,6 +110,18 @@ Global
{4490894C-3572-4E63-86F1-EE5105CE8A06}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
{4490894C-3572-4E63-86F1-EE5105CE8A06}.Release|Mixed Platforms.Build.0 = Release|Any CPU
{4490894C-3572-4E63-86F1-EE5105CE8A06}.Release|x86.ActiveCfg = Release|Any CPU
{B195CD03-F3D7-4DEA-A009-6CDD351462EF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B195CD03-F3D7-4DEA-A009-6CDD351462EF}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B195CD03-F3D7-4DEA-A009-6CDD351462EF}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
{B195CD03-F3D7-4DEA-A009-6CDD351462EF}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
{B195CD03-F3D7-4DEA-A009-6CDD351462EF}.Debug|x86.ActiveCfg = Debug|Any CPU
{B195CD03-F3D7-4DEA-A009-6CDD351462EF}.Debug|x86.Build.0 = Debug|Any CPU
{B195CD03-F3D7-4DEA-A009-6CDD351462EF}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B195CD03-F3D7-4DEA-A009-6CDD351462EF}.Release|Any CPU.Build.0 = Release|Any CPU
{B195CD03-F3D7-4DEA-A009-6CDD351462EF}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
{B195CD03-F3D7-4DEA-A009-6CDD351462EF}.Release|Mixed Platforms.Build.0 = Release|Any CPU
{B195CD03-F3D7-4DEA-A009-6CDD351462EF}.Release|x86.ActiveCfg = Release|Any CPU
{B195CD03-F3D7-4DEA-A009-6CDD351462EF}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@@ -1,8 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageSources>
<clear />
<add key="NuGet" value="https://api.nuget.org/v3/index.json" />
<add key="AspNetVNext" value="https://www.myget.org/f/aspnetmaster/api/v3/index.json" />
</packageSources>
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageSources>
<add key="NuGet" value="https://api.nuget.org/v3/index.json" />
<add key="AspNetVNext" value="https://www.myget.org/f/aspnetmaster/api/v3/index.json" />
</packageSources>
</configuration>
@@ -1,3 +1,4 @@
{
"projects": ["src"]
"projects": [ "src", "../ModernShopping/Auth/src" ],
"sdk": { "version": "1.0.0-beta8" }
}
@@ -7,21 +7,22 @@
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Mvc.Rendering;
using Dnx.Identity.MongoDB;

namespace IdentitySample.Controllers
{
[Authorize]
public class AccountController : Controller
{
public AccountController(UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager)
public AccountController(UserManager<MongoIdentityUser> userManager, SignInManager<MongoIdentityUser> signInManager)
{
UserManager = userManager;
SignInManager = signInManager;
}

public UserManager<ApplicationUser> UserManager { get; private set; }
public UserManager<MongoIdentityUser> UserManager { get; private set; }

public SignInManager<ApplicationUser> SignInManager { get; private set; }
public SignInManager<MongoIdentityUser> SignInManager { get; private set; }

//
// GET: /Account/Login
@@ -86,7 +87,7 @@ public async Task<IActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var user = new MongoIdentityUser(model.Email, model.Email);
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
@@ -185,7 +186,8 @@ public async Task<IActionResult> ExternalLoginConfirmation(ExternalLoginConfirma
{
return View("ExternalLoginFailure");
}
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };

var user = new MongoIdentityUser(model.Email, model.Email);
var result = await UserManager.CreateAsync(user);
if (result.Succeeded)
{
@@ -422,7 +424,7 @@ private void AddErrors(IdentityResult result)
}
}

private async Task<ApplicationUser> GetCurrentUserAsync()
private async Task<MongoIdentityUser> GetCurrentUserAsync()
{
return await UserManager.FindByIdAsync(HttpContext.User.GetUserId());
}
@@ -6,21 +6,22 @@
using Microsoft.AspNet.Authorization;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Mvc;
using Dnx.Identity.MongoDB;

namespace IdentitySample.Controllers
{
[Authorize]
public class ManageController : Controller
{
public ManageController(UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager)
public ManageController(UserManager<MongoIdentityUser> userManager, SignInManager<MongoIdentityUser> signInManager)
{
UserManager = userManager;
SignInManager = signInManager;
}

public UserManager<ApplicationUser> UserManager { get; private set; }
public UserManager<MongoIdentityUser> UserManager { get; private set; }

public SignInManager<ApplicationUser> SignInManager { get; private set; }
public SignInManager<MongoIdentityUser> SignInManager { get; private set; }

//
// GET: /Account/Index
@@ -368,7 +369,7 @@ public enum ManageMessageId
Error
}

private async Task<ApplicationUser> GetCurrentUserAsync()
private async Task<MongoIdentityUser> GetCurrentUserAsync()
{
return await UserManager.FindByIdAsync(HttpContext.User.GetUserId());
}

This file was deleted.

Oops, something went wrong.

This file was deleted.

Oops, something went wrong.
@@ -1,12 +1,17 @@
using IdentitySample.Models;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Data.Entity;
using Microsoft.Framework.Configuration;
using Microsoft.Framework.DependencyInjection;
using Microsoft.Framework.Logging;
using Microsoft.Dnx.Runtime;
#if DNX451
using Microsoft.AspNet.Identity;
using Microsoft.Framework.DependencyInjection.Extensions;
using System.Threading.Tasks;
using System.Security.Claims;
using System;
using Microsoft.Framework.OptionsModel;
using Dnx.Identity.MongoDB;
using MongoDB.Driver;
#if DNX452
using NLog.Config;
using NLog.Targets;
#endif
@@ -33,25 +38,42 @@ public Startup(IApplicationEnvironment env)

public void ConfigureServices(IServiceCollection services)
{
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration["Data:IdentityConnection:ConnectionString"]));
services.Configure<IdentityDbContextOptions>(options =>
services.AddSingleton<IUserStore<MongoIdentityUser>>(provider =>
{
options.DefaultAdminUserName = Configuration["DefaultAdminUsername"];
options.DefaultAdminPassword = Configuration["DefaultAdminPassword"];
var client = new MongoClient();
var database = client.GetDatabase("IdentitySampleMvc");
var loggerFactory = provider.GetService(typeof(ILoggerFactory)) as ILoggerFactory;

return new MongoUserStore<MongoIdentityUser>(database, loggerFactory);
});

services.AddOptions();
services.AddAuthentication(options =>
{
// This is the Default value for ExternalCookieAuthenticationScheme
options.SignInScheme = new IdentityCookieOptions().ExternalCookieAuthenticationScheme;
});

services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
// Identity services
services.TryAddSingleton<IdentityMarkerService>();
services.TryAddScoped<IUserValidator<MongoIdentityUser>, UserValidator<MongoIdentityUser>>();
services.TryAddScoped<IPasswordValidator<MongoIdentityUser>, PasswordValidator<MongoIdentityUser>>();
services.TryAddScoped<IPasswordHasher<MongoIdentityUser>, PasswordHasher<MongoIdentityUser>>();
services.TryAddScoped<ILookupNormalizer, UpperInvariantLookupNormalizer>();
services.TryAddScoped<IdentityErrorDescriber>();
services.TryAddScoped<ISecurityStampValidator, SecurityStampValidator<MongoIdentityUser>>();
services.TryAddScoped<IUserClaimsPrincipalFactory<MongoIdentityUser>, UserClaimsPrincipalFactory<MongoIdentityUser>>();
services.TryAddScoped<UserManager<MongoIdentityUser>, UserManager<MongoIdentityUser>>();
services.TryAddScoped<SignInManager<MongoIdentityUser>, SignInManager<MongoIdentityUser>>();

AddDefaultTokenProviders(services);

services.AddMvc();
}

public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
#if DNX451
#if DNX452
var config = new LoggingConfiguration();

// Step 2. Create targets and add them to the configuration
@@ -88,10 +110,84 @@ public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
template: "{controller}/{action}/{id?}",
defaults: new { controller = "Home", action = "Index" });
});
}

public virtual void AddDefaultTokenProviders(IServiceCollection services)
{
var dataProtectionProviderType = typeof(DataProtectorTokenProvider<>).MakeGenericType(typeof(MongoIdentityUser));
var phoneNumberProviderType = typeof(PhoneNumberTokenProvider<>).MakeGenericType(typeof(MongoIdentityUser));
var emailTokenProviderType = typeof(EmailTokenProvider<>).MakeGenericType(typeof(MongoIdentityUser));
AddTokenProvider(services, TokenOptions.DefaultProvider, dataProtectionProviderType);
AddTokenProvider(services, TokenOptions.DefaultEmailProvider, emailTokenProviderType);
AddTokenProvider(services, TokenOptions.DefaultPhoneProvider, phoneNumberProviderType);
}

private void AddTokenProvider(IServiceCollection services, string providerName, Type provider)
{
services.Configure<IdentityOptions>(options =>
{
options.Tokens.ProviderMap[providerName] = new TokenProviderDescriptor(provider);
});

services.AddTransient(provider);
}
}

public class UserClaimsPrincipalFactory<TUser> : IUserClaimsPrincipalFactory<TUser>
where TUser : class
{
public UserClaimsPrincipalFactory(
UserManager<TUser> userManager,
IOptions<IdentityOptions> optionsAccessor)
{
if (userManager == null)
{
throw new ArgumentNullException(nameof(userManager));
}
if (optionsAccessor == null || optionsAccessor.Value == null)
{
throw new ArgumentNullException(nameof(optionsAccessor));
}

//Populates the Admin user and role
SampleData.InitializeIdentityDatabaseAsync(app.ApplicationServices).Wait();
UserManager = userManager;
Options = optionsAccessor.Value;
}

public UserManager<TUser> UserManager { get; private set; }

public IdentityOptions Options { get; private set; }

public virtual async Task<ClaimsPrincipal> CreateAsync(TUser user)
{
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
var userId = await UserManager.GetUserIdAsync(user);
var userName = await UserManager.GetUserNameAsync(user);
var id = new ClaimsIdentity(Options.Cookies.ApplicationCookieAuthenticationScheme,
Options.ClaimsIdentity.UserNameClaimType,
Options.ClaimsIdentity.RoleClaimType);
id.AddClaim(new Claim(Options.ClaimsIdentity.UserIdClaimType, userId));
id.AddClaim(new Claim(Options.ClaimsIdentity.UserNameClaimType, userName));
if (UserManager.SupportsUserSecurityStamp)
{
id.AddClaim(new Claim(Options.ClaimsIdentity.SecurityStampClaimType,
await UserManager.GetSecurityStampAsync(user)));
}
if (UserManager.SupportsUserRole)
{
var roles = await UserManager.GetRolesAsync(user);
foreach (var roleName in roles)
{
id.AddClaim(new Claim(Options.ClaimsIdentity.RoleClaimType, roleName));
}
}
if (UserManager.SupportsUserClaim)
{
id.AddClaims(await UserManager.GetClaimsAsync(user));
}
return new ClaimsPrincipal(id);
}
}
}
Oops, something went wrong.

0 comments on commit 55dcc3e

Please sign in to comment.