我是ASP NET MVC authentication的新手,在我的网络项目中遇到了麻烦
默认情况下(项目生成的结果)有一个AccountController,它有一个Login方法
[Authorize]
public class AccountController : Controller
{
private UserService _userService;
public UserService UserService{
get { return _userService ?? (_userService = new UserService()); }
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl){
if (!ModelState.IsValid)
{
return View(model);
}
//the line with SignInManager is Default in project
//var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
//I have implemented my User service which checks in DB is there exists such a user with email and password and returns the same SignInStatus
var result = UserService.Authenticate(model.Email, model.Password);
switch (result)
{
case SignInStatus.Success:
return RedirectToLocal(returnUrl);
case SignInStatus.LockedOut:
return View("Lockout");
case SignInStatus.RequiresVerification:
return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
case SignInStatus.Failure:
default:
ModelState.AddModelError("", "Invalid login attempt.");
return View(model);
}
}
}我的UserService实现:
public class UserService : IUserService
{
public SignInStatus Authenticate(string email, string password)
{
if (string.IsNullOrEmpty(email) || string.IsNullOrEmpty(password))
{
return SignInStatus.Failure;
}
//TODO: perform authentication against DB account
if (email == "mymail@mail.com" && password == "123")
{
return SignInStatus.Success;
}
else
{
return SignInStatus.Failure;
}
}
}我将它与[Authorize]属性一起使用在AdministrationController上
public class AdministrationController : Controller
{
// GET: Admin/Admin
[Authorize]
public ActionResult Index()
{
return View();
}
}当我进入站点的管理区域时,通过http://localhost:53194/administration不需要任何身份验证(不显示登录屏幕)。
如果我在我的方法上设置属性[Authorize(Roles = "Administrator")]
public class AdministrationController : Controller
{
// GET: Admin/Admin
[Authorize(Roles = "Administrator")]
public ActionResult Index()
{
return View();
}
}出现登录屏幕。我设置了电子邮件和密码。按下Login按钮,从AccountController进入Login方法,用SignInStatus.Success输入情况
但登录屏幕依然存在。它不会重定向到普通的Administration屏幕。
您能告诉我如何实现此身份验证吗?谢谢。
发布于 2015-12-30 10:30:50
您似乎没有在成功登录时设置身份验证cookie。因此,用户实际上被重定向到Administration页面,但是由于他没有有效的身份验证cookie,所以他被重定向回登录表单。
因此,请确保设置了cookie:
case SignInStatus.Success:
var user = new ApplicationUser
{
Email = model.Email,
UserName = model.Email,
... set any other properties that you find convenient
};
await SignInManager.SignInAsync(user, false, false);
return RedirectToLocal(returnUrl);https://stackoverflow.com/questions/34527565
复制相似问题