我正在尝试为新的企业站点设置登录身份验证,我正在尝试从我的服务器数据库运行用户登录(而不是使用azure的东西构建。
我在控制器中使用[授权]标题
public class HomeController : Controller
{
[Authorize]
public ActionResult Index()
{
return View();
}
}
这是我的Startup.cs:
public void ConfigureAuth(IAppBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Login/Index")
});
然后在我的登录控制器中设置AuthCookie:
[HttpGet]
[AllowAnonymous]
public ActionResult Index(string Error)
{
return View();
}
[HttpPost]
[AllowAnonymous]
public ActionResult Index(string userID, string password)
{
if(CheckUserCredentialsAgainstDB(userID, password))
{
FormsAuthentication.SetAuthCookie(userID, true);
}
}
当我运行该应用程序并登录时,我的浏览器中有.ASPAUTH cookie,但当我尝试使用[Authorize]标签访问某个动作时,它会直接将我发送回登录页面,我是什么角色在这里失踪?
有类似的问题,例如Persistent AuthCookie is set but being redirected to login,但是我的方案中没有一个答案有所帮助。
答案 0 :(得分:0)
表单身份验证与OWIN默认cookie身份验证不同。
您的登录方式应依赖IAuthenticationManager
公开的OwinContext
来正确登录用户:
[HttpPost]
[AllowAnonymous]
public ActionResult Index(string userID, string password)
{
if(CheckUserCredentialsAgainstDB(userID, password))
{
var claims = new Claim[]
{
new Claim(ClaimTypes.NameIdentifier, userID),
new Claim(ClaimTypes.Role, "therole")
};
var identity = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie); // create a new user identity
var auth = Request.GetOwinContext().Authentication;
auth.SignIn(new AuthenticationProperties
{
IsPersistent = false // set to true if you want `remember me` feature
}, identity);
// redirect the user somewhere
}
// notify the user of failure
}
请勿在POST方法中使用多个参数,尤其是在发布登录信息等敏感数据时。
基本参数通常在查询字符串中传输,任何人只要查看URL(这也意味着在服务器日志中)就可以看到它们。
相反,使用简单的视图模型来获得相同的结果:
public class LoginViewModel
{
public string UserId { get; set; }
public string Password { get; set; }
}
// ...
[HttpPost]
[AllowAnonymous]
public ActionResult Index(LoginViewModel model)
{
if(CheckUserCredentialsAgainstDB(model.UserId, model.Password))
{
// ...
}
// ...
}