【问题标题】:Authentication ASP.NET MVC 5 against Database针对数据库的身份验证 ASP.NET MVC 5
【发布时间】:2016-04-04 07:29:49
【问题描述】:

我是 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;
        }
    }
}

我将它与AdministrationController 上的[Authorize] 属性一起使用

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的case

登录屏幕仍然存在。它不会重定向到正常的管理屏幕。

请您建议我如何实施此身份验证。谢谢。

【问题讨论】:

    标签: c# authentication asp.net-mvc-5


    【解决方案1】:

    您似乎没有在成功登录时设置身份验证 cookie。所以用户实际上被重定向到管理页面,但由于他没有有效的身份验证 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);
    

    【讨论】:

    • 感谢您的建议。这是有道理的。我必须在 cookie 中添加用户。我添加了您建议的行,但它也停留在登录页面,不允许进入正常的管理视图。可能是因为我使用了属性[Authorize(Roles="Administrator")]。我应该添加一些逻辑来为这个用户添加角色吗?或者不知何故需要更改属性?
    • 是的,当然,如果您需要,您应该为该用户分配管理员角色。
    • 实际上,如果我使用不带角色的 [Authorize],它不会“触发”登录过程。是否可以通过使用此属性但没有角色以某种方式“触发”登录过程?
    • 当您使用[Authorize] 属性装饰控制器或操作时,ASP.NET MVC 将检查请求是否与包含用户的有效 cookie 相关联。当您使用[Authorize(Roles = "foobar")] 装饰控制器或操作时,ASP.NET MVC 将另外检查当前用户是否具有所需的角色。因此,如果您不关心角色,请不要使用它们:[Authorize]。如果你打算使用它,我还建议你阅读一些关于 ASP.NET Identity 的教程。
    • 如果我使用 [Authorize] 登录页面不会显示。我不知道为什么。你知道周围的事情吗?谢谢推荐。我当然会阅读!
    猜你喜欢
    • 1970-01-01
    • 2014-01-02
    • 1970-01-01
    • 2011-06-10
    • 2014-10-12
    • 1970-01-01
    • 2014-03-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多