MVC使用表单身份验证登录

时间:2015-12-22 09:37:44

标签: vb.net asp.net-mvc-4 model-view-controller

我决定使用表单身份验证来登录用户,不幸的是我遇到了一些问题。我想如果用户正确登录将他移动到某个特定的控制器,那么他可以通过其他控制器检查他是否真的被授权。当然,在所有控制器的方法中,都会检查用户是否真的经过了身份验证?这是本主题底部的主要问题和其他3个问题。请你的支持。

到目前为止,我在LoginController中有这个代码:

    Function Index() As ActionResult
        Return View()
    End Function

    'Action for POST method (login)
    <HttpPost>
    <AllowAnonymous>
    Function Index(ByVal user As tbLogin) As ActionResult
        Try
            If (ModelState.IsValid) Then
                If IsValid(user.Login, user.Password) Then
                    FormsAuthentication.SetAuthCookie(user.Id, False)
                    Return RedirectToAction("AfterLogin")
                Else
                    ViewData("Success") = "Login error"
                End If
            End If
        Catch ex As Exception
            Return RedirectToAction("Index", "Home")
        End Try
        Return View(user)

    End Function

  'Action for Show view after login
    <Authorize>
    Function AfterLogin() As ActionResult
            Return RedirectToAction("Index", "Home")
        End If
    End Function

 Function IsValid(Login As String, password As String) As Boolean
        Dim _isValid As Boolean = False

        Using dc = New woitgroup_transport.production_WojtgroupEntitesContext
            Dim user = dc.tbLogin.Where(Function(a) a.Login.Equals(Login) And a.Password.Equals(password)).FirstOrDefault()

            If Not IsNothing(user) Then
                If user.Password = password Then
                    _isValid = True
                End If
            End If

        End Using
        Return _isValid
    End Function

在webconfig中:

<authentication mode="Forms">
  <forms loginUrl="~/Login/Index" timeout="2880" />
</authentication>

第一个问题:目前在每个控制器和每个方法中我都将它们标记为<Authorized>。我检查手动输入链接到地址,没有用户登录用户将被重定向到登录页面(因为webconfig) - 似乎它正在工作。你能证实这一点吗?

e.g:

<Authorize>
    Public Function Index(model As CustomModelProjetsTransports, Optional filter As String = "") As ActionResult

第3个问题:因为我保留了user.Id这里:FormsAuthentication.SetAuthCookie(user.Id, False)我想在某个控制器中读取这个id。我怎样才能读到这个值?

第4个问题:自用户验证后是否有超时?

第5个问题:这个命令是否正确退出用户 - 打破会话?: FormsAuthentication.SignOut

进一步讨论(使用@ C0dingJammer) - 扩展:

 <HttpPost>
    <AllowAnonymous>
    <ValidateAntiForgeryToken>
    Function Index(ByVal user As tbLogin) As ActionResult
        Try
            If (ModelState.IsValid) Then
                Dim userId As Integer
                If Not IsNothing(GetUserIdIfValid(user.Login, user.Password)) Then
                    userId = GetUserIdIfValid(user.Login, user.Password)
                    'false wywali cookie po zamknieciu browser - true zostawi
                    FormsAuthentication.SetAuthCookie(userId, False)
                    Return RedirectToAction("AfterLogin")
                Else
                    ViewData("Success") = "Login error"
                End If
            End If
        Catch ex As Exception
            Return RedirectToAction("Index", "Home")
        End Try
        Return View(user)

    End Function

这应该只返回false / true但是也得到user.Id我重构它以获得它并传递给FormsAuthentication.SetAuthCookie(userId,False)。我正在寻找比现在更好的一点:

Function GetUserIdIfValid(Login As String, password As String) As Object
        Dim _getuserId As Object = Nothing
        Using dc = New woitgroup_transport.production_WojtgroupEntitesContext
            Dim user = dc.tbLogin.Where(Function(a) a.Login.Equals(Login) And a.Password.Equals(password)).FirstOrDefault()

            If Not IsNothing(user) Then
                If user.Password = password Then
                    _getuserId = user.Id
                End If
            End If
        End Using
        Return _getuserId
    End Function

1 个答案:

答案 0 :(得分:2)

2问题: 是的,您可以在web.config中设置登录表单。请参阅问题4

第3个问题: How to get current user in Asp.Net MVC

  

如果需要从控制器中获取用户,请使用Controller的User属性。如果您从视图中需要它,我会在ViewData中填充您特别需要的内容,或者您​​可以调用User,因为我认为它是ViewPage的属性。

第四个问题。您可以在Web.config文件中设置用户中loged的超时。我看起来像这样:

 <system.web>
    <authentication mode="Forms">
      <forms loginUrl="~/Account/Login" timeout="1440" /> <!--1440Min = 24Hours-->
    </authentication>
.....
 </system.web>

当登录时间到期时,用户将被注销(自动更新GUI)。如果他现在点击链接,将他重定向到&#39; EmployeeController&#39;已设置属性&#39; [授权]&#39;他被重定向到登录页面,该登录页面已在web.config文件中设置。 如果EmployeeController没有Attribute,它将允许用户以普通用户身份访问(控制器)站点/视图

 [Authorize]
 public class EmployeeController : Controller
 {
       private ActionResult Index()
        {
            return View("You are allowed to see this page, because you are logged-in");
        }
 }

所以只有身份验证。允许用户访问Employes-Controlelr。如果他们没有权限,他们将被重定向到登录页面

第五个问题是的,它是正确的,但您需要重定向到视图而不是仅传递视图。

    public ActionResult LogOff()
    {
        FormsAuthentication.SignOut();

        //Important part
        return RedirectToAction("Index", "ErrorLogs");
    }

我希望它有所帮助。

编辑(讨论)

//This is the model which is used as a object to transfer data from View to Controller. Itself contains a method named Validate which is validating the user against Ad for ex.
public class tbLogin
{
    public string UserId { get; set;}
    private string Password { get; set;}

    public tbLogin(string uId, string pw)
    {
        this.UserId = uId;
        this.Password = pw;
    }

    public boolean Validate()
    {
        if(String.IsNullOrEmpty(UserId) || String.IsNullOrEmpty(Password)) { return; }
        //Validate user against Active Directory for ex.    
        return true;
    }
}


//This is your method in your account controller. It gets the data from the view and calls the validation method in the model
//Post
Public ActionResult Index(tbLogin user)
{

    if (!ModelState.IsValid)
    {
        return View(user);
    }

    if(user == null) 
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }

    try
    {
        if(user.Validate())
        {
            FormsAuthentication.SetAuthCookie(user.UserId, False);
            return RedirectToAction("AfterLogin");
        }
        else
        {
            //ViewData("Success") = "Login error"
        }
    }
    catch(Exception ex)
    {
         //Handle Expetion and redirect to Home-index
         return  RedirectToAction("Index","Home");
    }

    return View(user);
}