我正在尝试设置新企业网站的登录身份验证,我正在尝试从服务器的数据库运行用户登录(而不是在Azure stupp中构建。
我在控制器中使用[授权]标头
public class HomeController : Controller
{
[Authorize]
public ActionResult Index()
{
return View();
}
}
这是我的启动:
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,但是当我尝试使用[授权]标签访问操作时,它会直接将我发送回登录页面,我是什么在这里缺少?
对此有类似的问题,例如设置了持久的authcookie,但被重定向到登录,但是在我的方案中没有任何答案。
表单身份验证与OWIN默认cookies auth是不同的事情。
您的登录方法应依靠IAuthenticationManager
公开的CC_1正确登录用户:
[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))
{
// ...
}
// ...
}