简体   繁体   English

仅允许在ASP.NET MVC中将用户注册为管理员

[英]Only allow to register users to the admin in ASP.NET MVC

In my scenario, the users can not register, there will be an admin, and that admin will create the users with a default password they can change later. 在我的情况下,用户无法注册,将有一个管理员,该管理员将使用默认密码创建用户,以后可以更改。

I am reviewing the pluralsight videos and according to those I should put the [Authorize] tag in the action method. 我正在审视多元化视频,并根据这些视频,应将[Authorize]标签放入操作方法中。

I did the following, but once I did this, I cant see anything on http://localhost/Account/Register , neither as a logged in user. 我执行了以下操作,但是一旦执行此操作,我就无法以登录用户的身份在http:// localhost / Account / Register上看到任何内容。

  1. The role admin already exists. 角色admin已经存在。
  2. The logged in user is also associated to that role in the UserInRoles table. 登录的用户还与UserInRoles表中的该角色相关联。

If I remove the [Authorize] attribute, then I can access the register page. 如果删除[Authorize]属性,则可以访问注册页面。

// GET: /Account/Register
    [HttpPost]
    [Authorize(Roles = "admin")]
    public ActionResult Register()
    {
        return View();
    }

    //
    // POST: /Account/Register

    [HttpPost]
    [Authorize(Roles="admin")]
    public ActionResult Register(RegisterModel model)
    {
        if (ModelState.IsValid)
        {
            // Attempt to register the user
            MembershipCreateStatus createStatus;
            Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, true, null, out createStatus);

            if (createStatus == MembershipCreateStatus.Success)
            {
                FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */);
                return RedirectToAction("Index", "Home");
            }
            else
            {
                ModelState.AddModelError("", ErrorCodeToString(createStatus));
            }
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

The logon partial is: 登录部分为:

@if(Request.IsAuthenticated) {
    <text>Welcome <strong>@User.Identity.Name</strong>!
    [ @Html.ActionLink("Register", "Register", "Account") ]
    [ @Html.ActionLink("Log Off", "LogOff", "Account") ]
    [ @Html.ActionLink("Change Password", "ChangePassword", "Account") ]
    [ @Html.ActionLink("Position", "Position", "Position") ]
    [ @Html.ActionLink("User Position", "Position", "UserPositionPosition") ]
    </text>
}
else {
    @:[ @Html.ActionLink("Log On", "LogOn", "Account") ]
}








 EDIT: I better attached the full account controller for better understanding

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using HRRazorForms.Models;

namespace HRRazorForms.Controllers
{
    public class AccountController : Controller
    {

        //
        // GET: /Account/LogOn

        public ActionResult LogOn()
        {
            return View();
        }

        //
        // POST: /Account/LogOn

        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (Membership.ValidateUser(model.UserName, model.Password))
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/LogOff

        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();

            return RedirectToAction("Index", "Home");
        }

        //
        // GET: /Account/Register
        [HttpPost]
        [Authorize(Roles = "admin")]       
        public ActionResult Register()
        {
            return View();
        }

        //
        // POST: /Account/Register

        [HttpPost]
        [Authorize(Roles="admin")]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                MembershipCreateStatus createStatus;
                Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, true, null, out createStatus);

                if (createStatus == MembershipCreateStatus.Success)
                {
                    //FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */);
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ModelState.AddModelError("", ErrorCodeToString(createStatus));
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/ChangePassword

        [Authorize]
        public ActionResult ChangePassword()
        {
            return View();
        }

        //
        // POST: /Account/ChangePassword

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {

                // ChangePassword will throw an exception rather
                // than return false in certain failure scenarios.
                bool changePasswordSucceeded;
                try
                {
                    MembershipUser currentUser = Membership.GetUser(User.Identity.Name, true /* userIsOnline */);
                    changePasswordSucceeded = currentUser.ChangePassword(model.OldPassword, model.NewPassword);
                }
                catch (Exception)
                {
                    changePasswordSucceeded = false;
                }

                if (changePasswordSucceeded)
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/ChangePasswordSuccess

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }

        #region Status Codes
        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "User name already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A user name for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
        #endregion
    }
}

在此处输入图片说明

the problem with this is that rolemanager was set to false instead of true by default in the web.config. 问题是在web.config中,默认将rolemanager设置为false而不是true。

Sorry for that, was easy to solve, but never thought it would be disabled.! 抱歉,很容易解决,但从未想到会被禁用。

That should work. 那应该工作。

I would say that you have done something else when trying different things. 我会说您在尝试其他事情时做了其他事情。

EG: Are you sure you don't have a different Authorize attribute on the controller? EG:您确定控制器上没有其他Authorize属性吗? For example: 例如:

[Authorize(Roles="ADifferentRole")]

Is the admin role spelled correctly (for example, sure its not administration instead of admin)? 管理员角色的拼写是否正确(例如,确保它不是管理员,而不是admin)?

Are you sure that you haven't registered, then not noticed that instead of being logged in as the admin, you are now logged in as the recently created user (see below, there is a bug of sorts in your code). 您确定尚未注册,然后没有注意到,您现在不是以管理员身份登录,而是以最近创建的用户身份登录(请参见下文,代码中存在一些错误)。

Sorry I can't be more help, but what you have shown should work. 抱歉,我无法提供更多帮助,但是您显示的内容应该可以工作。

Bug: 错误:

Your HttpPost Action for Register has a fault in it for the kind of use you want to give it. 您的HttpPost Action for Register在您要提供的使用方式上有错误。 If you have another user creating the logins, then when that user registers someone successfully, your code is going to set the authentication cookie to that of the new user. 如果您有另一个用户创建登录名,那么当该用户成功注册某人时,您的代码将把身份验证cookie设置为新用户的身份验证cookie。

This is probably the cause of your problem. 这可能是造成您问题的原因。 The code that does this is: 执行此操作的代码是:

if (createStatus == MembershipCreateStatus.Success)
            {
                FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */);
                return RedirectToAction("Index", "Home");
            }

You need to replace that block with: 您需要将该块替换为:

if (createStatus == MembershipCreateStatus.Success)
            {
                return RedirectToAction("Index", "Home"); // or wherever you want to go...
            }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM