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,