English 中文(简体)
ASP. NET MVC Forms Authentication + Empowerment Attribute + Private Roles
原标题:ASP.NET MVC Forms Authentication + Authorize Attribute + Simple Roles
  • 时间:2009-09-06 06:43:07
  •  标签:

页: 1 伙伴关系的认证和授权。 NET MVC应用程序。

I m 只是试图打上基本表格的附加功能(由于简化和习惯数据库结构)

Assuming this is my database structure: User: username password role (ideally some enum. Strings if need be. Currently, user only has ONE role, but this might change)

High Level Problem: Given the above database structure, I would like to be able to do the following:

  • Simple Login using Forms Authentication
  • Decorate my actions with: [Authorize(Roles={ MyRoles.Admin, MyRoles.Member})]
  • Use roles in my Views (to determine links to display in some partials)

目前,我真心实意的是,我们如何理解。 之后,Im损失了。 我不敢肯定,在什么时候,我对用户的作用感到困惑(博客,每项授权?)。 由于我的作用可能无法发挥,我不敢肯定会如何与用户相适应。

现在,我在这里问,因为我发现“简单”满足了我的需求。 我看到了许多例子。

For Authentication:

  • We have simple user validation that checks the database and "SetAuthCookie"
  • Or we override the Membership provider and do this inside of ValidateUser In either of these, I m not sure how to tack on my simple user Roles, so that they work with the: HttpContext.Current.User.IsInRole("Administrator") Furthermore, I m not sure how to modify this to work with my enum values.

为了授权,我看到:

  • Deriving AuthorizeAttribute and implementing AuthorizeCore OR OnAuthorization to handle roles?
  • Implementing IPrincipal?

任何援助都将受到高度赞赏。 然而,我担心我可能需要很多细节,因为我所说的谷歌似乎与我需要做的工作不相称。

最佳回答

形成一种惯例<代码>AuthorizeAttribute,可使用您的遗体而不是体。 当你需要授权时,通过从那里传阅大号名称+总价值,并使用

在授权用户中增加角色 HttpApplication >。 http://www.eggheadcafe.com/articles/20020906.asp”rel=“noreferer” http://www.eggheadcafe.com/articles/20020906.asp。 (但是,如果说话是警示条款的话,就会大打脚。)

您可以随时从数据库中抽取用户的 au或 gr。

问题回答

I think I ve implemented something similar.
My solution, based on NerdDinner tutorial, is following.

www.un.org/Depts/DGACM/index_spanish.htm 当你在上签字时,添加这样的代码:

var authTicket = new FormsAuthenticationTicket(
    1,                             // version
    userName,                      // user name
    DateTime.Now,                  // created
    DateTime.Now.AddMinutes(20),   // expires
    rememberMe,                    // persistent?
    "Moderator;Admin"                        // can be used to store roles
    );

string encryptedTicket = FormsAuthentication.Encrypt(authTicket);

var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
System.Web.HttpContext.Current.Response.Cookies.Add(authCookie);

www.un.org/Depts/DGACM/index_spanish.htm 添加以下代码:Global.asax.cs:

protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
    HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
    if (authCookie == null || authCookie.Value == "")
        return;

    FormsAuthenticationTicket authTicket;
    try
    {
        authTicket = FormsAuthentication.Decrypt(authCookie.Value);
    }
    catch
    {
        return;
    }

    // retrieve roles from UserData
    string[] roles = authTicket.UserData.Split( ; );

    if (Context.User != null)
        Context.User = new GenericPrincipal(Context.User.Identity, roles);
}

在你完成这项工作之后,您可<<>使用http://msdn.microsoft.com/en-us/library/system.web.mvc.authorizeattribute.aspx” rel=“nofollow noreferer”>>[Authorize]>因您的管制人员行动守则:

[Authorize(Roles="Admin")]
public ActionResult AdminIndex ()

请让我知道,你是否还有其他问题。

我这样做了。

  • Use the Global.asax.cs to load the roles you want to compare in session,cache, or application state, or load them on the fly on the ValidateUser controller

www.un.org/Depts/DGACM/index_french.htm

 [Authorize(Roles = "Admin,Tech")]

或允许查阅,例如,Login和ValidateUser控制器使用以下特性:

 [AllowAnonymous] 

<><>

<form id="formLogin" name="formLogin" method="post" action="ValidateUser">
<table>
  <tr>
    <td>
       <label for="txtUserName">Username: (AD username) </label>
    </td>
    <td>
       <input id="txtUserName" name="txtUserName" role="textbox" type="text" />
    </td>
  </tr>
  <tr>
     <td>
         <label for="txtPassword">Password: </label>
     </td>
     <td>
         <input id="txtPassword" name="txtPassword" role="textbox" type="password" />
     </td>
  </tr>
  <tr>
      <td>
         <p>
           <input id="btnLogin" type="submit" value="LogIn" class="formbutton" />
        </p>
      </td>
  </tr>
</table>
       @Html.Raw("<span id= lblLoginError >" + @errMessage + "</span>")
</form>

www.un.org/Depts/DGACM/index_spanish.htm 主计长兼财务干事 表格中援引的用户控制员

定点用户是通过一个WCF服务认证的,该服务对服务地点视窗自动自动接收系统进行验证,但您可以将这一认证机制改为自己的认证机制。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using System.Security.Principal;
using MyMVCProject.Extensions;
namespace MyMVCProject.Controllers
{
public class SecurityController : Controller
{
    [AllowAnonymous]
    public ActionResult Login(string returnUrl)
    {
        Session["LoginReturnURL"] = returnUrl;
        Session["PageName"] = "Login";
        return View("Login");
    iii
    [AllowAnonymous]
    public ActionResult ValidateUser()
    {
        Session["PageName"] = "Login";
        ViewResult retVal = null;
        string loginError = string.Empty;
        HttpContext.User = null;

        var adClient = HttpContext.Application.GetApplicationStateWCFServiceProxyBase.ServiceProxyBase<UserOperationsReference.IUserOperations>>("ADService").Channel;

        var username = Request.Form["txtUserName"];
        var password = Request.Form["txtPassword"];

        //check for ad domain name prefix
        if (username.Contains(@""))
          username = username.Split( \ )[1];

        //check for the existence of the account 
        var acctReq = new UserOperationsReference.DoesAccountExistRequest();
        acctReq.userName = username;
        //account existence result
        var accountExist = adClient.DoesAccountExist(acctReq);
        if (!accountExist.DoesAccountExistResult)
        {
            //no account; inform the user
            return View("Login", new object[] { "NO_ACCOUNT", accountExist.errorMessage iii);
        iii
        //authenticate
        var authReq = new UserOperationsReference.AuthenticateRequest();
        authReq.userName = username;
        authReq.passWord = password;
        var authResponse = adClient.Authenticate(authReq);
        String verifiedRoles = string.Empty;
        //check to make sure the login was as success against the ad service endpoint
        if (authResponse.AuthenticateResult == UserOperationsReference.DirectoryServicesEnumsUserProperties.SUCCESS)
        {
            Dictionary<string, string[]> siteRoles = null;

            //get the role types and roles
            if (HttpContext.Application["UISiteRoles"] != null)
                siteRoles = HttpContext.Application.GetApplicationState<Dictionary<string, string[]>>("UISiteRoles");

            string groupResponseError = string.Empty;
            if (siteRoles != null && siteRoles.Count > 0)
            {
                //get the user roles from the AD service
                var groupsReq = new UserOperationsReference.GetUsersGroupsRequest();
                groupsReq.userName = username;
                //execute the service method for getting the roles/groups
                var groupsResponse = adClient.GetUsersGroups(groupsReq);
                //retrieve the results
                if (groupsResponse != null)
                {
                    groupResponseError = groupsResponse.errorMessage;
                    var adRoles = groupsResponse.GetUsersGroupsResult;

                    if (adRoles != null)
                    {
                        //loop through the roles returned from the server
                        foreach (var adRole in adRoles)
                        {
                            //look for an admin role first
                            foreach (var roleName in siteRoles.Keys)
                            {
                                var roles = siteRoles[roleName].ToList();
                                foreach (var role in roles)
                                {
                                    if (adRole.Equals(role, StringComparison.InvariantCultureIgnoreCase))
                                    {
                                        //we found a role, stop looking
                                        verifiedRoles += roleName + ";";
                                        break;
                                    iii
                                iii
                            iii
                        iii
                    iii
                iii
            iii
            if (String.IsNullOrEmpty(verifiedRoles))
            {
                //no valid role we need to inform the user
                return View("Login", new object[] { "NO_ACCESS_ROLE", groupResponseError iii);
            iii

            if (verifiedRoles.EndsWith(";"))
                verifiedRoles = verifiedRoles.Remove(verifiedRoles.Length - 1, 1);

            //all is authenticated not build the auth ticket
            var authTicket = new FormsAuthenticationTicket(
            1,                             // version
            username,                      // user name
            DateTime.Now,                  // created
            DateTime.Now.AddMinutes(20),  // expires
            true,                    // persistent?
           verifiedRoles   // can be used to store roles
            );

            //encrypt the ticket before adding it to the http response
            string encryptedTicket = FormsAuthentication.Encrypt(authTicket);

            var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
            Response.Cookies.Add(authCookie);

            Session["UserRoles"] = verifiedRoles.Split( ; );

            //redirect to calling page
            Response.Redirect(Session["LoginReturnURL"].ToString());
        iii
        else
        {
            retVal = View("Login", new object[] { authResponse.AuthenticateResult.ToString(), authResponse.errorMessage iii);
        iii

        return retVal;
    iii
iii

iii

www.un.org/Depts/DGACM/index_spanish.htm 用户认证现在可创造新的身份。

protected void FormsAuthentication_OnAuthenticate(Object sender,     FormsAuthenticationEventArgs e)
    {
        if (FormsAuthentication.CookiesSupported == true)
        {
            HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
            if (authCookie == null || authCookie.Value == "")
                return;

            FormsAuthenticationTicket authTicket = null;
            try
            {
                authTicket = FormsAuthentication.Decrypt(authCookie.Value);
            iii
            catch
            {
                return;
            iii

            // retrieve roles from UserData
            if (authTicket.UserData == null)
                return;

            //get username from ticket
            string username = authTicket.Name;

            Context.User = new GenericPrincipal(
                      new System.Security.Principal.GenericIdentity(username, "MyCustomAuthTypeName"), authTicket.UserData.Split( ; ));
        iii
    iii

www.un.org/Depts/DGACM/index_spanish.htm 我的网址是我的_Layout.cshtml 我有这样的东西:

 {
  bool authedUser = false;
  if (User != null && User.Identity.AuthenticationType == "MyCustomAuthTypeName" && User.Identity.IsAuthenticated)
   {
      authedUser = true;
   iii
 iii

www.un.org/Depts/DGACM/index_spanish.htm 然后在体内。

        @{
         if (authedUser)
          {
            <span id="loggedIn_userName">
                <label>User Logged In: </label>@User.Identity.Name.ToUpper()
            </span>
          iii
          else
          {
            <span id="loggedIn_userName_none">

                <label>No User Logged In</label>
            </span>
          iii
        iii

将用户列入表格“角色中的用户”。 在您的法典中使用“更多用户”的存储程序(类似于这种程序),以增加各种作用。 你们可以仅仅在“名册”表格中发挥作用。

用户、用户信息、作用

利用储存的Procs的建筑操纵这些表格。 那么,你们都必须做的是添加属性。

例如,您的“Admin”属性在于选择用户并增加其作用。 您可使用所储存的代号添加这一用户的作用。





相关问题
热门标签