控制器中的MVC认证

本文关键字:认证 MVC 控制器 | 更新日期: 2023-09-27 18:05:02

我们正在尝试做一些有登录屏幕的网站。但是我们有一个问题。我们的域名是localhost/Login/User。但如果用户输入localhost/Home/Index,则无需登录即可访问我们的主站。所以我们写了[authorization]给我们的索引控制器。但我不知道该用什么。我是否必须在我们的项目中使用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函数中访问index

控制器中的MVC认证

添加[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

ASP中基于角色的访问控制(RBAC)与基于声明的访问控制(CBAC)。净MVC https://www.owasp.org/index.php/.NET_Security_Cheat_Sheet