我需要在我的MVC4 C#项目中实现授权和身份验证。
我不想实现登录逻辑来输入用户名和密码;即没有登录屏幕。
我有HttpContext.Current.User.Identity.Name的用户ID。
如果用户具有角色" admin"我需要的一切他可以访问所有控制器页面,如果他是用户,他只能访问用户控制器,如果他试图点击管理员的动作链接,他将收到你未经授权的消息。
每次用户访问任何Action方法时,我的授权逻辑将首先被执行并检查和验证,而不管他正在访问哪个URL。
直到现在我已经做到了。
在网络配置中
<authentication mode="Forms" />
<forms loginUrl="~/Appauth/appauth" timeout="2880" />
</authentication>
我的路线表:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters*
new { controller = "Appauth", action = "appauth", id = UrlParameter.Optional });
public class LoginController : Controller
{
public ActionResult appauth(returnUrl)
{
bool userValid = false;
currentuserID = HttpContext.Current.User.Identity.Name;
if(currentuserID!=null)
{
userValid = true;
}
// User valid
if (userValid)
{
FormsAuthentication.SetAuthCookie(username, false);
if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
&& !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("UserHome", "Home");
}
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
return RedirectToAction("Homeview");
}
}
protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
{
if (FormsAuthentication.CookiesSupported == true)
{
if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
{
try
{
//let us take out the username now
string username = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name;
string roles = string.Empty;
role =//roles logic ;
HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(
new System.Security.Principal.GenericIdentity(username, "Forms"), roles.Split(';'));
}
catch (Exception)
{
//somehting went wrong
}
}
}
}
public class AdminHomeController : Controller
{
[Authorize(Roles="Admin")]
public ActionResult About()
{
//admin logic
return View("AdminViewHOme");
}
}
public class UserHomeController : Controller
{
[Authorize]
public ActionResult Index()
{
//user logic
return View(userviewhome);
}
}
当我运行此代码循环时,总是调用我的登录逻辑并设置票证,然后使用身份验证票据和再次登录逻辑跳转到全局asax以促进角色提取,我想为用户而不是每次都执行一次时间。
PS:如果是asp.net我可以通过在Onpageload()事件中编写方法来实现它。 混淆了这个票务系统并且流程请帮助代码。