【问题标题】:MVC 4 Only Authorize user's should enter the certain pageMVC 4 只有授权用户才能进入特定页面
【发布时间】:2014-09-02 10:57:11
【问题描述】:

好的,我正在从头开始开发一些 Web 应用程序。我已经使用教程LoginRegistration 中的简单数据库制作了自定义登录和注册页面。现在这是我的站点 GUI 或 API,假设有两个程序 Program AProgram B。任何人都可以访问我网站的 HOMEPAGE 并使用 Program A 但只有经过身份验证的用户才能通过 LOGIN() 使用 Program B,即 Program B 链接将可见给那些登录的用户。


所以我需要帮助来确保我的程序 B 安全,即它的链接将对已登录的人可见。我想再澄清一件事,Program A Link 和“Program B Link”都编码在主 HomePage 上,所以你不能直接访问 Program B 仅通过 URL。我希望你明白我想说的......帮助! 下面是我的 Login.cshtml 代码

  @model FYPFinalTest3.Models.UserLogin
@{
    Layout = null;
}

<h2>Login</h2>

@using (Html.BeginForm("Login","Login", FormMethod.Post))
{
    //this  is for create form tag
    @Html.AntiForgeryToken()          // this is for prevent CSRF attack
    @Html.ValidationSummary(true)
    if (@ViewBag.Message != null)
    {
        <div style="border:1px solid red">
            @ViewBag.Message
        </div>
    }
    <table>
        <tr>
            <td>@Html.LabelFor(a=>a.Username)</td>
            <td>@Html.TextBoxFor(a=>a.Username)</td>
            <td>@Html.ValidationMessageFor(a=>a.Username)</td>
        </tr>
        <tr>
            <td>
                @Html.LabelFor(a=>a.Password)
            </td>
            <td>
                @Html.PasswordFor(a=>a.Password)
            </td>
            <td>
                @Html.ValidationMessageFor(a=>a.Password)
            </td>
        </tr>
        <tr>
            <td></td>
            <td>
                <input type="submit" value="Login" />
            </td>
            <td></td>
        </tr>
    </table>
}

@* This below line is for create javascript section *@

@section Scripts{
    @Scripts.Render("~/bundles/jqueryval")
}

【问题讨论】:

    标签: c# asp.net-mvc asp.net-mvc-4 authentication authorization


    【解决方案1】:

    您可以使用 Authorize 属性并可以如下装饰您的代码:-

    [Authorize]
    public class ProgramB:Controller
       {
    
         public ActionResult Method1()
         {
           return View();
         }
    
         [Authorize]
         public ActionResult Method2()
         {
           return View();
         }
       }
    

    所以那些未登录的用户将被重定向到登录页面。

    更多详情:-

    http://msdn.microsoft.com/en-us/library/system.web.mvc.authorizeattribute.aspx

    您甚至可以创建自己的自定义授权属性,请看这里:-

    http://msdn.microsoft.com/en-us/library/ee707357(v=vs.91).aspx

    【讨论】:

    • 仅仅添加 [授权] 并不能完成这项工作。还有一件事我不明白这个框架如何知道用户被授权,因为我只是使用简单的编码来匹配用户名和密码,没什么太复杂的。
    • 我猜你使用表单身份验证..你是否在 web.config 中给出了身份验证类型?你能把它贴在这里@WaqarAhmed 吗?
    • 请查看教程的链接,以便您正确理解我做了什么,这些步骤与 web.config 无关。我没有更改 webconfig 中的任何内容。
    • 您会发现,由于您启用了表单身份验证,您将被自动重定向到登录页面“~/Account/Login”@WaqarAhmed...cyrrently 用户未登录时发生的情况进去然后直接上programB?
    猜你喜欢
    • 1970-01-01
    • 2014-07-27
    • 1970-01-01
    • 2012-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多