PasswordSignInAsync пытается создать новую базу данных
Я работаю над существующим проектом с Windows, и удостоверению подлинности существующей базы данных (так мы в базе данных первой для структуры объекта).
Теперь мы меняем способ аутентификации аутентификации OWIN Identity.
Выполнив некоторые учебники, я получил этот новый контекст для моих таблиц идентичности асп:
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();
}
}
myconnexionstring точно так же, как и мой первоначальный контекст порожденного EDMX в базе данных-первое.
Я также включил поддержку миграции из консоли диспетчера пакетов и воспроизведет миграцию, чтобы создать таблицы идентификации asp в моей базе данных. Нет проблем для этой части.
Это мой StartupClass:
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);
}
}
Теперь, когда я пытаюсь проверить подлинность меня, я получаю исключение с этим сообщением: CREATE DATABASE разрешение Отказано в базе данных «мастер». Это исключение возникает, когда я называю метод PasswordSignInAsync моего ApplicationSignInManager
Это мой 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");
}
}
}
И это мой 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);
}
}
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;
}
}
ApplicationUser:
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;
}
}
Любая идея, чтобы помочь мне? Не следует пытаться создать базу данных, но только знак пользователя в.
EDIT
Исключение происходит в первый раз, когда база данных называется. Это моя связь строка:
<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" />
EDIT 2
Моя новая связь строка
<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" />
И я изменил ApplicationDbContext:
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();
}
}
SignInAsync впервые база данных называется. Какова ваша строка соединения? –
Спасибо, Ричард. Да, это первый раз. Пользователь не аутентифицирован, поэтому он перенаправляется на страницу входа в систему. Поэтому он пытается войти в систему, но есть исключения. Я редактирую строку связи – thibaudlosc