0

I want to do authorization in .Net Core but I don't want to use Identity DB tables. I have User, Role, and UserRoles tables. I want to be able to login with User, authorize methods with CustomAuthorize and use these privileges in View.

I did login and CustomAuthorize but I can't use in view..

Login

public IActionResult LoginUser(string returnUrl)
{
    ViewBag.returnUrl = returnUrl;
    return View();
}

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> LoginUser(LoginModel loginModel, string returnUrl)
{
    var userCheck = UnitOfWork.Users.ValidateUser(loginModel.EmailAddress, loginModel.Password);
    if (ModelState.IsValid && userCheck != 0)
    {
        User user = UnitOfWork.Users.Query(x => x.EmailAddress == loginModel.EmailAddress && x.Password == loginModel.Password).FirstOrDefault();

        if (user != null)
        {
            var claims = new List<Claim>
            {
                new Claim(ClaimTypes.Name, user.Id.ToString())
            };

            var userIdentity = new ClaimsIdentity(claims, "login");

            ClaimsPrincipal principal = new ClaimsPrincipal(userIdentity);
            await HttpContext.SignInAsync(principal);
        }
        return Redirect(returnUrl ?? "/");
       // return RedirectToAction("Index", "Home");
    }
    else
    {
        ModelState.AddModelError("", "Kullanıcı adı veya şifre geçersiz!");
    }

    return View(loginModel);
}

CustomAuthorizeAttribute

public class AuthorizeUserAttribute : AuthorizeAttribute, IAuthorizationFilter
    {
        private readonly IUnitOfWork _unitOfWork = new UnitOfWork.UnitOfWork.UnitOfWork();

        // Custom property
        public string AccessView { get; set; }
        public string AccessInsert { get; set; }
        public string AccessUpdate { get; set; }
        public string AccessDelete { get; set; }
        public string AccessFileView { get; set; }
        public string AccessFileInsert { get; set; }
        public string AccessFileDelete { get; set; }
        public string NotifyUrl { get; set; } = "/Home/Index";


        public void OnAuthorization(AuthorizationFilterContext context)
        {

            var user = context.HttpContext.User;

            if (!user.Identity.IsAuthenticated)
            {

                return;
            }

            var userInfoModel = AppHttpContext.Current.Session.GetStringToObject<UserInfoModel>("UserInfo") ??
                                new UserInfoModel();

            if (AccessUpdate != "Modul")
            {
                context.Result = new StatusCodeResult((int) System.Net.HttpStatusCode.Forbidden);
                context.Result = new RedirectResult(NotifyUrl);
                return;
            }
        }

    }

Use CustomAuthorize in controller

[AuthorizeUser(AccessUpdate = "Modul", NotifyUrl = "/Modul/ListModul")]
public IActionResult Index()
{
    return View();
}

How I can use CustomAuthorize in View pages like this..? but without policy.

@if ((await AuthorizationService.AuthorizeAsync(User, "PolicyName")).Succeeded)
{
    <p>This paragraph is displayed because you fulfilled PolicyName.</p>
}

Thanks,

  • 1
    Basically , you don't need to custom your own AuthorizeUserAttribute . Use `Policy` or authorization handler to do that . As for using in the view pages , you can inject a PolicyChecker to do that – itminus Oct 18 '18 at 09:21
  • Be sure to check out the docs on authorization: https://docs.microsoft.com/en-us/aspnet/core/security/authorization/?view=aspnetcore-2.1 – juunas Oct 18 '18 at 09:23
  • Possible duplicate of [How do you create a custom AuthorizeAttribute in ASP.NET Core?](https://stackoverflow.com/questions/31464359/how-do-you-create-a-custom-authorizeattribute-in-asp-net-core) – Cake or Death Oct 18 '18 at 09:36
  • The policy method is not appropriate because I will need too many authorizations. I just need using in the view pages.. – Cemalettin Oct 18 '18 at 11:19

0 Answers0