C# PasswordSignInAsync尝试创建新数据库
C# PasswordSignInAsync尝试创建新数据库,c#,asp.net-mvc,entity-framework,asp.net-identity-2,C#,Asp.net Mvc,Entity Framework,Asp.net Identity 2,我正在使用Windows身份验证和现有数据库处理一个现有的项目(因此,对于实体框架,我们首先使用数据库) 现在我们正在更改OWIN身份验证的身份验证方式。 在学习了一些教程之后,我获得了asp标识表的新上下文: public class ApplicationDbContext : IdentityDbContext<ApplicationUser> { public ApplicationDbContext() : base("myconnexionstri
我正在使用Windows身份验证和现有数据库处理一个现有的项目(因此,对于实体框架,我们首先使用数据库)
现在我们正在更改OWIN身份验证的身份验证方式。
在学习了一些教程之后,我获得了asp标识表的新上下文:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("myconnexionstring", throwIfV1Schema: false)
{
Database.SetInitializer<ApplicationDbContext>(null);
}
protected override void OnModelCreating(DbModelBuilder builder)
{
base.OnModelCreating(builder);
// Customize the ASP.NET Identity model and override the defaults if needed.
// For example, you can rename the ASP.NET Identity table names and more.
// Add your customizations after calling base.OnModelCreating(builder);
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
public类ApplicationDbContext:IdentityDbContext
{
公共应用程序上下文()
:base(“myconnectionnstring”,throwifvv1schema:false)
{
Database.SetInitializer(null);
}
模型创建时受保护的覆盖无效(DbModelBuilder builder)
{
基于模型创建(生成器);
//自定义ASP.NET标识模型,并根据需要覆盖默认值。
//例如,可以重命名ASP.NET标识表名称等。
//在调用base.OnModelCreating(builder)后添加自定义项;
}
公共静态应用程序上下文创建()
{
返回新的ApplicationDbContext();
}
}
MyConnectionInstance与EDMX首先在数据库中生成的原始上下文完全相同
我还通过PackageManager控制台启用了迁移,并在数据库中播放迁移来创建asp标识表。这部分没问题
这是我的课程:
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
this.ConfigureAuth(app);
app.MapSignalR();
}
public void ConfigureAuth(IAppBuilder app)
{
// Configure the db context, user manager and signin manager to use a single instance per request
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
// Enable the application to use a cookie to store information for the signed in user
// and to use a cookie to temporarily store information about a user logging in with a third party login provider
// Configure the sign in cookie
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Login/LogOn"),
CookieName = "MyCookie",
});
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
}
}
公共部分类启动
{
公共无效配置(IAppBuilder应用程序)
{
此.ConfigureAuth(应用程序);
app.mapsigner();
}
public void ConfigureAuth(IAppBuilder应用程序)
{
//将数据库上下文、用户管理器和登录管理器配置为每个请求使用一个实例
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext(ApplicationUserManager.Create);
app.CreatePerOwinContext(ApplicationSignInManager.Create);
//使应用程序能够使用cookie存储登录用户的信息
//以及使用cookie临时存储用户登录第三方登录提供商的信息
//配置登录cookie
app.UseCookieAuthentication(新的CookieAuthenticationOptions
{
AuthenticationType=DefaultAuthenticationTypes.ApplicationOkie,
LoginPath=新路径字符串(“/Login/LogOn”),
CookieName=“MyCookie”,
});
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
}
}
现在,当我尝试对我进行身份验证时,我收到一条异常消息:在数据库“master”中拒绝创建数据库权限。当我调用我的应用程序SignInManager的PasswordSignInAsync方法时,会发生此异常
这是我的LoginController类:
public class LoginController : Controller
{
private ApplicationSignInManager _signInManager;
public ApplicationSignInManager SignInManager
{
get
{
return _signInManager ?? HttpContext.GetOwinContext().Get<ApplicationSignInManager>();
}
private set { _signInManager = value; }
}
//
// GET: /Account/Login
[HttpGet]
[AllowAnonymous]
public ActionResult LogOn(string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
return View();
}
[HttpPost]
[AllowAnonymous]
public async Task<ActionResult> LogOn(LoginViewModel model, string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
if (ModelState.IsValid)
{
// the SqlException throw there
SignInStatus result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, false, false);
if (result == SignInStatus.Success)
{
return RedirectToLocal(returnUrl);
}
else
{
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return View(model);
}
}
else
{
ModelState.AddModelError(string.Empty, "Adress invalid");
return View(model);
}
}
private ActionResult RedirectToLocal(string returnUrl)
{
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
}
公共类登录控制器:控制器
{
专用应用程序signInManager\u signInManager;
公共应用程序SignInManager SignInManager
{
得到
{
return _signInManager??HttpContext.GetOwinContext().Get();
}
私有集{u signInManager=value;}
}
//
//获取:/Account/登录
[HttpGet]
[异名]
公共操作结果登录(字符串returnUrl=null)
{
ViewData[“ReturnUrl”]=ReturnUrl;
返回视图();
}
[HttpPost]
[异名]
公共异步任务登录(LoginViewModel模型,字符串returnUrl=null)
{
ViewData[“ReturnUrl”]=ReturnUrl;
if(ModelState.IsValid)
{
//SqlException在那里抛出
SignInStatus结果=等待SignInManager.PasswordSignInAsync(model.Email,model.Password,false,false);
如果(结果==SignInStatus.Success)
{
返回重定向到本地(returnUrl);
}
其他的
{
AddModelError(string.Empty,“登录尝试无效”);
返回视图(模型);
}
}
其他的
{
AddModelError(string.Empty,“地址无效”);
返回视图(模型);
}
}
私有操作结果重定向到本地(字符串返回URL)
{
if(Url.islocalur(returnUrl))
{
返回重定向(returnUrl);
}
其他的
{
返回重定向到操作(“索引”、“主页”);
}
}
}
这是我的ApplicationSignInManager:
public class ApplicationSignInManager : SignInManager<ApplicationUser, string>
{
public ApplicationSignInManager(ApplicationUserManager userManager, IAuthenticationManager authenticationManager)
: base(userManager, authenticationManager)
{
}
public override Task<ClaimsIdentity> CreateUserIdentityAsync(ApplicationUser user)
{
return user.GenerateUserIdentityAsync((ApplicationUserManager)UserManager);
}
public static ApplicationSignInManager Create(IdentityFactoryOptions<ApplicationSignInManager> options, IOwinContext context)
{
return new ApplicationSignInManager(context.GetUserManager<ApplicationUserManager>(), context.Authentication);
}
}
公共类应用程序SignInManager:SignInManager
{
公共应用程序签名管理器(ApplicationUserManager用户管理器、IAAuthenticationManager authenticationManager)
:base(userManager、authenticationManager)
{
}
公共覆盖任务CreateUserIdentityAsync(ApplicationUser用户)
{
返回user.GenerateUserIdentityAsync((ApplicationUserManager)UserManager);
}
公共静态应用程序SigninManager创建(IdentityFactoryOptions选项,IOwinContext上下文)
{
返回新的ApplicationSignInManager(context.GetUserManager(),context.Authentication);
}
}
ApplicationUserManager:
public class ApplicationUserManager : UserManager<ApplicationUser>
{
public ApplicationUserManager(IUserStore<ApplicationUser> store)
: base(store)
{
}
public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
{
var manager = new ApplicationUserManager(new UserStore<ApplicationUser>());
// Configure validation logic for usernames
manager.UserValidator = new UserValidator<ApplicationUser>(manager)
{
AllowOnlyAlphanumericUserNames = false,
RequireUniqueEmail = true
};
// Configure validation logic for passwords
manager.PasswordValidator = new PasswordValidator
{
RequiredLength = 6,
RequireNonLetterOrDigit = true,
RequireDigit = true,
RequireLowercase = true,
RequireUppercase = true,
};
// Configure user lockout defaults
manager.UserLockoutEnabledByDefault = true;
manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
manager.MaxFailedAccessAttemptsBeforeLockout = 5;
//manager.EmailService = new EmailService();
var dataProtectionProvider = options.DataProtectionProvider;
if (dataProtectionProvider != null)
{
manager.UserTokenProvider =
new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
}
return manager;
}
}
公共类应用程序管理员:用户管理员
{
公共应用程序服务器管理器(IUserStore存储)
:基地(商店)
{
}
公共静态应用程序SerManager创建(IdentityFactoryOptions选项,IOwinContext上下文)
{
var manager=new ApplicationUserManager(new UserStore());
//为用户名配置验证逻辑
manager.UserValidator=新的UserValidator(管理器)
{
AllowOnlyAlphanumericUserNames=false,
RequireUniqueEmail=true
};
//配置密码的验证逻辑
manager.PasswordValidator=新密码验证器
{
所需长度=6,
RequiredOnletterDigit=真,
RequireDigit=true,
RequireLowercase=true,
RequireUppercase=true,
public class ApplicationUser : IdentityUser
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
}
<add name="myconnexionstring" connectionString="metadata=res://*/DbModel.csdl|res://*/DbModel.ssdl|res://*/DbModel.msl;provider=System.Data.SqlClient;provider connection string="data source=localhost\SQLEXPRESS;initial catalog=Database2014;persist security info=True;user id=sa;password=MyPassword;multipleactiveresultsets=True;application name=EntityFramework"" providerName="System.Data.EntityClient" />
<add name="myconnexionstringForIdentity" connectionString="data source=localhost\SQLEXPRESS;initial catalog=Database2014;persist security info=True;user id=sa;password=MyPassword;multipleactiveresultsets=True;application name=EntityFramework" providerName="System.Data.SqlClient" />
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("myconnexionstringForIdentity", throwIfV1Schema: false)
{
Database.SetInitializer<ApplicationDbContext>(null);
}
protected override void OnModelCreating(DbModelBuilder builder)
{
base.OnModelCreating(builder);
// Customize the ASP.NET Identity model and override the defaults if needed.
// For example, you can rename the ASP.NET Identity table names and more.
// Add your customizations after calling base.OnModelCreating(builder);
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}