如何设置在asp.net mvc的身份自定义身份验证? [英] How to setup a custom authentication on asp.net mvc identity?

查看:281
本文介绍了如何设置在asp.net mvc的身份自定义身份验证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

坦白说我很新的ASP.NET MVC因此,我请你和我一起裸同时解释我的问题。
我需要什么?!
我有一个ASP.NET识别系统的设置和使用外部登录运行。无论出于何种原因,我需要设置ASP.NET身份认证后,自定义身份验证。让我解释一下怎么样?比方说我有用户三页以查看我的应用程序,网页A,B,C。
谁可以查看页面A?
任何匿名用户可以查看页面A.
谁可以查看页面A和B'
谁创造或者与他/她的电子邮件和放大器的帐户任何用户;密码或使用外部登录。
谁可以查看网页A,B和; C 3


  

下面是我想设置自定义验证的地方。
  谁已经创建了一个账户或者与他/她的电子邮件帐户或外部登录名,并具有有效的序列密钥的任何用户。
  序列密钥?
  我设置ASP.NET身份类,如下:


 公共类的UserDetails:IdentityUser
    {
        公共虚拟MembershipSerial MembershipSerial {搞定;组; }
    }    公共类MembershipSerial
    {
        [HiddenInput(DisplayValue = FALSE)]
        公众诠释标识{搞定;组; }
        [HiddenInput(DisplayValue = FALSE)]
        公共字符串序列{搞定;组; }
        [需要]
        [显示(名称=会员串行)]
        公共字符串SerialConfirmed {搞定;组; }
    }    公共类MyDbContext:IdentityDbContext<&的UserDetails GT;
    {
        公共MyDbContext()
            :基地(EFDbContext)
        {
        }
        公共System.Data.Entity.DbSet< MembershipSerial> MembershipSerial {搞定;组; }
    }

正如你看到上面的类我设立在班三个属性。现场ID是连续的ID,​​串行是由管理员输入一个14字母数字字母,你可以看到它是不允许空的隐藏字段。本场SerialConfirmed也将由用户输入才能做一些特定任务的应用程序来验证14字母数字字母。
整体概念是,一个登录的用户应按压用于第二类型的认证是验证VS序号

我认真地需要帮助和网上搜索并没有帮助太多。如果您需要了解更多信息或者其还不清楚不要犹豫,问我。
问候
编辑:我使用EF code第一。
Dostdar


解决方案

这似乎是一个自定义的授权属性会工作。下面是一个例子实现:

  [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method,的AllowMultiple = FALSE)]
公共类RequiresSerialValidationAttribute:AuthorizeAttribute
{
    公共覆盖无效OnAuthorization(AuthorizationContext filterContext)
    {
        布尔hasVa​​lidSerial = FALSE;
        如果(filterContext.HttpContext.Request.IsAuthenticated)
        {
            字符串username = filterContext.HttpContext.User.Identity.Name;            如果(!string.IsNullOrWhiteSpace(用户名))
            {
                串序列=的String.Empty; // TODO:获取用户的previously从会话或cookie的认证序列,也许?                如果(!string.IsNullOrWhiteSpace(串行))
                {
                    VAR的服务= DependencyResolver.Current.GetService< IYourAuthService>();
                    hasVa​​lidSerial = service.IsSerialValidForUser(用户名,串行);
                }
            }
        }        如果(!hasVa​​lidSerial)
        {
            filterContext.Result =新RedirectToRouteResult(新RouteValueDictionary(新{控制器=yourserialauthcontroller,行动=yourauthaction,面积=的String.Empty}));
        }
        其他
        {
            base.OnAuthorization(filterContext);
        }
    }
}

您将装点的操作方法与此属性:

  [RequireSerialValidation]
公众的ActionResult SomeAction()
{
}

属性会触发重定向到你的挑战行动,在那里你提示你为自己的串行用户。如果一切顺利,你存储他们的串行某处(会话可以在这里工作,或创建一个加密的Cookie),然后重定向回原来的动作。在第二次尝试,你已经验证了的动作是允许的,所以没有发生重定向

您认证服务可以是你希望它是什么。在这个例子中,我假设你正在使用依赖注入,并且您已经配置了全局依赖解析器。鉴于此,您IYourAuthService看起来是这样的(忽略其他方法):

 公共IYourAuthService
{
    布尔IsSerialValidForUser(用户名字符串,字符串串行);
}

像这样实现:

 公共YourAuthService:IYourAuthService
{
    公共BOOL IsSerialValidForUser(用户名字符串,字符串串行)
    {
        使用(VAR上下文=新YourEntityFrameworkDbContext())
        {
            返回context.Users.Any(U => u.UserName.Equals(用户名,StringComparison.OrdinalIgnoreCase)及和放大器; u.Serial.Equals(串行,StringComparison.OrdinalIgnoreCase));
        }
    }
}

此假设你有一个名为表用户(或用户)的数据库,而用户名串口是该表的字段。 StringComparison.OrdinalIgnoreCase 让你做一个不区分大小写,文化 - 在你试图比较不敏感的字符串匹配。

Frankly spoken i am quite new to ASP.NET MVC therefore i ask you to bare with me while explaining my question. What I Need?! I have an ASP.NET identity system setup and running with external logins. For whatever reason i need to setup a custom authentication after the ASP.NET identity authentication. Let me explain how? Lets say I have three pages for the users to view on my application, Page A,B,C. Who can view Page A? Any anonymous user can view page A. Who can view Page A & B? Any user who have created an account either with his/her email & password or with external logins. Who can view Page A,B & C?

Here is the place i want to set custom authentication. Any user who have created an account either with his/her email account or external logins AND has a valid serial key. Serial Key? I set a class in ASP.NET identity as below:

 public class UserDetails : IdentityUser
    {
        public virtual MembershipSerial MembershipSerial { get; set; }
    }

    public class MembershipSerial
    {
        [HiddenInput(DisplayValue=false)]
        public int Id { get; set; }
        [HiddenInput(DisplayValue=false)]
        public string Serial { get; set; }
        [Required]
        [Display(Name="Membership Serial")]
        public string SerialConfirmed { get; set; }
    }

    public class MyDbContext : IdentityDbContext<UserDetails>
    {
        public MyDbContext()
            : base ("EFDbContext")
        {
        }
        public System.Data.Entity.DbSet<MembershipSerial> MembershipSerial { get; set; }
    }

As you see above class i set up three properties in the class. Field Id is for the Ids of the serials, The Serial is a 14 Alpha numeric letters which is entered by the administrator and as you can see it is a hidden field which not allowing null. The field SerialConfirmed is also a 14 Alpha Numeric letters which will be entered by the users to authenticate in order to do some certain tasks in the application. The whole concept is, that a logged in user should be pushed for a second type authentication which is authentication vs serial numbers.

I am seriously in need of help and searching online didn't help too much. If you need more information or yet its is unclear don't hesitate to ask me. Regards Edit: I am using EF code first. Dostdar

解决方案

It seems like a custom authorization attribute would work. Here's an example implementation:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
public class RequiresSerialValidationAttribute : AuthorizeAttribute
{
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        bool hasValidSerial = false;
        if (filterContext.HttpContext.Request.IsAuthenticated)
        {
            string userName = filterContext.HttpContext.User.Identity.Name;

            if (!string.IsNullOrWhiteSpace(userName))
            {       
                string serial = string.Empty;// TODO: Retrieve user's previously authenticated serial, perhaps from Session or a cookie?

                if(!string.IsNullOrWhiteSpace(serial))
                {
                    var service = DependencyResolver.Current.GetService<IYourAuthService>();
                    hasValidSerial = service.IsSerialValidForUser(userName, serial);
                }
            }
        }

        if (!hasValidSerial)
        {
            filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "yourserialauthcontroller", action = "yourauthaction", area = string.Empty }));
        }
        else
        {
            base.OnAuthorization(filterContext);
        }
    }
}

You would decorate the action methods with this attribute:

[RequireSerialValidation]
public ActionResult SomeAction()
{
}

The attribute would trigger a redirect to your challenge action, where you prompt your user for their serial. Assuming all goes well, you store their serial somewhere (Session could work here, or create an encrypted cookie), and then redirect back to the original action. On this second attempt, you've already verified that the action is allowed, so no redirect occurs.

Your authentication service can be whatever you want it to be. In this example, I assume you're using dependency injection and that you've configured the global dependency resolver. Given that, your IYourAuthService could look like this (omitting other methods):

public IYourAuthService
{
    bool IsSerialValidForUser(string userName, string serial);
}

with an implementation like so:

public YourAuthService : IYourAuthService
{
    public bool IsSerialValidForUser(string userName, string serial)
    {
        using(var context = new YourEntityFrameworkDbContext())
        {
            return context.Users.Any(u => u.UserName.Equals(userName, StringComparison.OrdinalIgnoreCase) && u.Serial.Equals(serial, StringComparison.OrdinalIgnoreCase));
        }
    }
}

This assumes you have a table called User (or Users) in your database, and that UserName and Serial are fields on that table. StringComparison.OrdinalIgnoreCase lets you do a case-insensitive, culture-insensitive match on the strings you're attempting to compare.

这篇关于如何设置在asp.net mvc的身份自定义身份验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆