【问题标题】:MVC Authentication In Controller控制器中的 MVC 身份验证
【发布时间】:2016-09-01 04:27:37
【问题描述】:

我们正在尝试做一些有登录屏幕的网站。但是我们有一个问题。我们的域是 localhost/Login/User。但是如果用户输入 localhost/Home/Index,他/她可以在没有登录的情况下访问我们的主站点。所以我们将 [Authorize] 写入我们的索引控制器。但我找不到我必须使用什么。我必须在我们的项目中使用 AuthorizeAttribute 吗?

#Login Page
public class LoginController : Controller
{
     //GET: Login
    [IntranetAction]
    public ActionResult Users()
    {
        return View();
    }

    public ActionResult Authentication(UserLoginInfo loginInfo)
    {
        bool isAuthenticated = new LdapServiceManager().isAuthenticated(loginInfo);


        if (isAuthenticated)
        {
            //AUTHORIZED
            Session["userName"] = loginInfo.username;
            return Redirect("/Home/Index");
        }
        //WORNG PASSWORD, BACK TO LOGIN PAGE
        TempData["message"] = "Yanlış kullanıcı adı ya da şifre";
        return Redirect("/");
    }
}

索引页

[Authorize]
public ActionResult Index()
{
    Session["ip"] = Request.UserHostAddress;
    if (IsDbExists())
    {
        _contactList = new List<Contact>();
        UpdateOperations();
        return View(_contactList);
    }

    Response.Redirect("/Loading/LoadingScreen");
    return null;
}

如何在我的 LoginController/Authentication 函数中访问索引

【问题讨论】:

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


    【解决方案1】:

    添加 [AllowAnonymous] 属性。我将添加另一个名为 AuthController 的控制器,该控制器将具有 [AllowAnonymous] 属性,因此用户无需实际登录即可登录。

    我通常会默认过滤所有控制器,并将 [AllowAnonymous] 属性添加到任何人都可以访问的控制器。

    我用这个来处理那个。

    using System.Web.Mvc;
    
    namespace Test
    {
        public class FilterConfig
        {
            public static void RegisterGlobalFilters(GlobalFilterCollection filters)
            {
                filters.Add(new HandleErrorAttribute());
                filters.Add(new AuthorizeAttribute());
            }
        }
    }
    

    AuthController 中的 [AllowAnonymous] 属性示例。

    using System.Security.Claims;
    using System.Web;
    using System.Web.Mvc;
    using BusinessLogic.Services;
    using Common.Models;
    using Microsoft.AspNet.Identity;
    using Microsoft.Owin.Security;
    
    namespace Test.Controllers
    {
        [AllowAnonymous]
        public class AuthController : Controller
        {
            private readonly IUsersService _usersService;
    
            public AuthController(IUsersService usersService)
            {
                _usersService = usersService;
            }
    
            [HttpGet]
            public ActionResult LogIn()
            {
                return View();
            }
    
            [HttpPost]
            public ActionResult LogIn(LoginModel loginModel)
            {
                if (!ModelState.IsValid)
                {
                    return View();
                }
    
                var isValid = _usersService.AuthenticateUser(loginModel);
                if (isValid)
                {
                    var identity = new ClaimsIdentity(new[]
                    {
                        new Claim(ClaimTypes.NameIdentifier, loginModel.Username),
                        new Claim(ClaimTypes.Name, loginModel.Username),
                    }, DefaultAuthenticationTypes.ApplicationCookie);
    
                    Request.GetOwinContext().Authentication.SignIn(new AuthenticationProperties() { IsPersistent = false }, identity);
    
                    return Redirect(GetRedirectUrl(loginModel.ReturnUrl));
                }
    
                ModelState.AddModelError("", "Invalid credentials");
                return View();
            }
    
            public ActionResult LogOut()
            {
                var ctx = Request.GetOwinContext();
                var authManager = ctx.Authentication;
    
                authManager.SignOut("ApplicationCookie");
                return RedirectToAction("index", "home");
            }
    
            private string GetRedirectUrl(string returnUrl)
            {
                if (string.IsNullOrEmpty(returnUrl) || !Url.IsLocalUrl(returnUrl))
                {
                    return Url.Action("index", "home");
                }
                return returnUrl;
            }
        }
    
    
    
    }
    

    可能对您有所帮助的参考资料: http://benfoster.io/blog/aspnet-identity-stripped-bare-mvc-part-1

    https://softwareengineering.stackexchange.com/questions/284380/is-formsauthentication-obsolete

    Role-based access control (RBAC) vs. Claims-based access control (CBAC) in ASP.NET MVC

    https://www.owasp.org/index.php/.NET_Security_Cheat_Sheet

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-25
      • 1970-01-01
      • 2023-04-10
      • 1970-01-01
      • 2015-08-04
      • 2013-05-05
      • 2016-10-06
      • 2012-12-23
      相关资源
      最近更新 更多