Skip to content

Commit 72c7383

Browse files
committed
First commit
First commit
1 parent a4d9dfb commit 72c7383

File tree

85 files changed

+30917
-0
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

85 files changed

+30917
-0
lines changed

WeApp/App_Start/BundleConfig.cs

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
using System.Web.Optimization;
2+
3+
namespace IdentitySample
4+
{
5+
public class BundleConfig
6+
{
7+
// For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
8+
public static void RegisterBundles(BundleCollection bundles)
9+
{
10+
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
11+
"~/Scripts/jquery-{version}.js"));
12+
13+
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
14+
"~/Scripts/jquery.validate*"));
15+
16+
// Use the development version of Modernizr to develop with and learn from. Then, when you're
17+
// ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
18+
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
19+
"~/Scripts/modernizr-*"));
20+
21+
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
22+
"~/Scripts/bootstrap.js",
23+
"~/Scripts/respond.js"));
24+
25+
bundles.Add(new StyleBundle("~/Content/css").Include(
26+
"~/Content/bootstrap.css",
27+
"~/Content/site.css"));
28+
}
29+
}
30+
}

WeApp/App_Start/FilterConfig.cs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
using System.Web.Mvc;
2+
3+
namespace IdentitySample
4+
{
5+
public class FilterConfig
6+
{
7+
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
8+
{
9+
filters.Add(new HandleErrorAttribute());
10+
}
11+
}
12+
}

WeApp/App_Start/IdentityConfig.cs

Lines changed: 158 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,158 @@
1+
using System.Linq;
2+
using System.Security.Claims;
3+
using Microsoft.AspNet.Identity;
4+
using Microsoft.AspNet.Identity.EntityFramework;
5+
using Microsoft.AspNet.Identity.Owin;
6+
using Microsoft.Owin;
7+
using Microsoft.Owin.Security;
8+
using System;
9+
using System.Collections.Generic;
10+
using System.Data.Entity;
11+
using System.Threading.Tasks;
12+
using System.Web;
13+
14+
namespace IdentitySample.Models
15+
{
16+
// Configure the application user manager used in this application. UserManager is defined in ASP.NET Identity and is used by the application.
17+
18+
public class ApplicationUserManager : UserManager<ApplicationUser>
19+
{
20+
public ApplicationUserManager(IUserStore<ApplicationUser> store)
21+
: base(store)
22+
{
23+
}
24+
25+
public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options,
26+
IOwinContext context)
27+
{
28+
var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));
29+
// Configure validation logic for usernames
30+
manager.UserValidator = new UserValidator<ApplicationUser>(manager)
31+
{
32+
AllowOnlyAlphanumericUserNames = false,
33+
RequireUniqueEmail = true
34+
};
35+
// Configure validation logic for passwords
36+
manager.PasswordValidator = new PasswordValidator
37+
{
38+
RequiredLength = 6,
39+
RequireNonLetterOrDigit = true,
40+
RequireDigit = true,
41+
RequireLowercase = true,
42+
RequireUppercase = true,
43+
};
44+
// Configure user lockout defaults
45+
manager.UserLockoutEnabledByDefault = true;
46+
manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
47+
manager.MaxFailedAccessAttemptsBeforeLockout = 5;
48+
// Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
49+
// You can write your own provider and plug in here.
50+
manager.RegisterTwoFactorProvider("PhoneCode", new PhoneNumberTokenProvider<ApplicationUser>
51+
{
52+
MessageFormat = "Your security code is: {0}"
53+
});
54+
manager.RegisterTwoFactorProvider("EmailCode", new EmailTokenProvider<ApplicationUser>
55+
{
56+
Subject = "SecurityCode",
57+
BodyFormat = "Your security code is {0}"
58+
});
59+
manager.EmailService = new EmailService();
60+
manager.SmsService = new SmsService();
61+
var dataProtectionProvider = options.DataProtectionProvider;
62+
if (dataProtectionProvider != null)
63+
{
64+
manager.UserTokenProvider =
65+
new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
66+
}
67+
return manager;
68+
}
69+
}
70+
71+
// Configure the RoleManager used in the application. RoleManager is defined in the ASP.NET Identity core assembly
72+
public class ApplicationRoleManager : RoleManager<IdentityRole>
73+
{
74+
public ApplicationRoleManager(IRoleStore<IdentityRole,string> roleStore)
75+
: base(roleStore)
76+
{
77+
}
78+
79+
public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context)
80+
{
81+
return new ApplicationRoleManager(new RoleStore<IdentityRole>(context.Get<ApplicationDbContext>()));
82+
}
83+
}
84+
85+
public class EmailService : IIdentityMessageService
86+
{
87+
public Task SendAsync(IdentityMessage message)
88+
{
89+
// Plug in your email service here to send an email.
90+
return Task.FromResult(0);
91+
}
92+
}
93+
94+
public class SmsService : IIdentityMessageService
95+
{
96+
public Task SendAsync(IdentityMessage message)
97+
{
98+
// Plug in your sms service here to send a text message.
99+
return Task.FromResult(0);
100+
}
101+
}
102+
103+
// This is useful if you do not want to tear down the database each time you run the application.
104+
// public class ApplicationDbInitializer : DropCreateDatabaseAlways<ApplicationDbContext>
105+
// This example shows you how to create a new database if the Model changes
106+
public class ApplicationDbInitializer : DropCreateDatabaseIfModelChanges<ApplicationDbContext>
107+
{
108+
protected override void Seed(ApplicationDbContext context) {
109+
InitializeIdentityForEF(context);
110+
base.Seed(context);
111+
}
112+
113+
//Create [email protected] with password=Admin@123456 in the Admin role
114+
public static void InitializeIdentityForEF(ApplicationDbContext db) {
115+
var userManager = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
116+
var roleManager = HttpContext.Current.GetOwinContext().Get<ApplicationRoleManager>();
117+
const string name = "[email protected]";
118+
const string password = "Admin@123456";
119+
const string roleName = "Admin";
120+
121+
//Create Role Admin if it does not exist
122+
var role = roleManager.FindByName(roleName);
123+
if (role == null) {
124+
role = new IdentityRole(roleName);
125+
var roleresult = roleManager.Create(role);
126+
}
127+
128+
var user = userManager.FindByName(name);
129+
if (user == null) {
130+
user = new ApplicationUser { UserName = name, Email = name };
131+
var result = userManager.Create(user, password);
132+
result = userManager.SetLockoutEnabled(user.Id, false);
133+
}
134+
135+
// Add user admin to Role Admin if not already added
136+
var rolesForUser = userManager.GetRoles(user.Id);
137+
if (!rolesForUser.Contains(role.Name)) {
138+
var result = userManager.AddToRole(user.Id, role.Name);
139+
}
140+
}
141+
}
142+
143+
public class ApplicationSignInManager : SignInManager<ApplicationUser, string>
144+
{
145+
public ApplicationSignInManager(ApplicationUserManager userManager, IAuthenticationManager authenticationManager) :
146+
base(userManager, authenticationManager) { }
147+
148+
public override Task<ClaimsIdentity> CreateUserIdentityAsync(ApplicationUser user)
149+
{
150+
return user.GenerateUserIdentityAsync((ApplicationUserManager)UserManager);
151+
}
152+
153+
public static ApplicationSignInManager Create(IdentityFactoryOptions<ApplicationSignInManager> options, IOwinContext context)
154+
{
155+
return new ApplicationSignInManager(context.GetUserManager<ApplicationUserManager>(), context.Authentication);
156+
}
157+
}
158+
}

WeApp/App_Start/RouteConfig.cs

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
using System.Web.Mvc;
2+
using System.Web.Routing;
3+
4+
namespace IdentitySample
5+
{
6+
public class RouteConfig
7+
{
8+
public static void RegisterRoutes(RouteCollection routes)
9+
{
10+
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
11+
12+
routes.MapRoute(
13+
name: "Default",
14+
url: "{controller}/{action}/{id}",
15+
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
16+
);
17+
}
18+
}
19+
}

WeApp/App_Start/Startup.Auth.cs

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
using Microsoft.AspNet.Identity;
2+
using Microsoft.AspNet.Identity.Owin;
3+
using Microsoft.Owin;
4+
using Microsoft.Owin.Security.Cookies;
5+
using IdentitySample.Models;
6+
using Owin;
7+
using System;
8+
9+
namespace IdentitySample
10+
{
11+
public partial class Startup
12+
{
13+
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
14+
public void ConfigureAuth(IAppBuilder app)
15+
{
16+
// Configure the db context, user manager and role manager to use a single instance per request
17+
app.CreatePerOwinContext(ApplicationDbContext.Create);
18+
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
19+
app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
20+
app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
21+
22+
// Enable the application to use a cookie to store information for the signed in user
23+
// and to use a cookie to temporarily store information about a user logging in with a third party login provider
24+
// Configure the sign in cookie
25+
app.UseCookieAuthentication(new CookieAuthenticationOptions
26+
{
27+
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
28+
LoginPath = new PathString("/Account/Login"),
29+
Provider = new CookieAuthenticationProvider
30+
{
31+
// Enables the application to validate the security stamp when the user logs in.
32+
// This is a security feature which is used when you change a password or add an external login to your account.
33+
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
34+
validateInterval: TimeSpan.FromMinutes(30),
35+
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
36+
}
37+
});
38+
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
39+
40+
// Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
41+
app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));
42+
43+
// Enables the application to remember the second login verification factor such as phone or email.
44+
// Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
45+
// This is similar to the RememberMe option when you log in.
46+
app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);
47+
48+
// Uncomment the following lines to enable logging in with third party login providers
49+
//app.UseMicrosoftAccountAuthentication(
50+
// clientId: "",
51+
// clientSecret: "");
52+
53+
//app.UseTwitterAuthentication(
54+
// consumerKey: "",
55+
// consumerSecret: "");
56+
57+
//app.UseFacebookAuthentication(
58+
// appId: "",
59+
// appSecret: "");
60+
61+
//app.UseGoogleAuthentication(
62+
// clientId: "",
63+
// clientSecret: "");
64+
}
65+
}
66+
}

WeApp/Content/Site.css

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
body {
2+
padding-top: 50px;
3+
padding-bottom: 20px;
4+
}
5+
6+
/* Set padding to keep content from hitting the edges */
7+
.body-content {
8+
padding-left: 15px;
9+
padding-right: 15px;
10+
}
11+
12+
/* Set width on the form input elements since they're 100% wide by default */
13+
input,
14+
select,
15+
textarea {
16+
max-width: 280px;
17+
}
18+
19+
/* styles for validation helpers */
20+
.field-validation-error {
21+
color: #b94a48;
22+
}
23+
24+
.field-validation-valid {
25+
display: none;
26+
}
27+
28+
input.input-validation-error {
29+
border: 1px solid #b94a48;
30+
}
31+
32+
input[type="checkbox"].input-validation-error {
33+
border: 0 none;
34+
}
35+
36+
.validation-summary-errors {
37+
color: #b94a48;
38+
}
39+
40+
.validation-summary-valid {
41+
display: none;
42+
}

0 commit comments

Comments
 (0)