如何在我的ASP中附加一个自定义的成员提供程序。净MVC应用程序?

时间:2022-06-02 20:34:54

How do I tie up my custom membership provider with my ASP.NET MVC [Authorize()] attribute? I've blasted through a number of tutorials for how to create a custom membership provider but all the information I've found about how to hook it up to an application seems to revolve around regular ASP.NET WebForms applications which seem to be a piece of cake.

如何将我的自定义会员提供程序与ASP绑定。净MVC(授权())属性?我已经详细介绍了如何创建自定义成员资格提供程序的一些教程,但是我找到的关于如何将其与应用程序挂钩的所有信息似乎都围绕着常规的ASP。NET WebForms应用程序似乎是小菜一碟。

I'm coming unstuck with the amount of "magic" that just happens in ASP.NET MVC which is great, but I'm used to plugging stuff in in a WebForms way so this "it just works" methodology is a bit of a mind bender for me. How do I know when I'm supposed to do the heavy lifting or I'm supposed to just rely on it happening by magic?

我被ASP中出现的“魔法”弄得不知所措。NET MVC很棒,但是我习惯了用WebForms的方式插入东西,所以这个“它只是工作”的方法对我来说有点疯狂。我怎么知道我什么时候应该做这些繁重的工作或者我应该仅仅依靠魔法来完成?

Where do I tie my provider in to an MVC app? Am I right in assuming that it is invoked through the [Authorize()] attribute once I do get it hooked up?

我要把我的提供者和MVC应用绑定在哪里?我是否正确地假设,一旦我把它连接起来,它就会通过[授权()]属性被调用?

3 个解决方案

#1


6  

Hopefully I can add some additional clarity over the other answers as they really don't explain what's going on which isn't going to help your confusion.

希望我能在其他答案上增加一些额外的清晰性,因为它们并不能解释发生了什么,这对你的困惑没有帮助。

First up, implement your custom provider which from the sound of things you've done already, so I'll just throw up a little code snippet and won't go into any further detail here:

首先,实现您的自定义提供程序,从您已经做过的事情的声音,所以我将抛出一个小代码片段,这里不再详细介绍:

using System.Web.Security;

public class MyCustomMembershipProvider : MembershipProvider
{
    public override bool ValidateUser(string username, string password)
    {
        if (username.Equals("BenAlabaster") && password.Equals("Elephant"))
            return true;

        return false;
    }

    /* Override all the other methods required to extend MembershipProvider */        
}

Then you configure your provider in your web.config making sure to populate the attributes that configure the base MembershipProvider:

然后在web中配置提供者。配置确保填充配置基本MembershipProvider的属性:

<membership defaultProvider="MyCustomMembershipProvider">      
    <providers>        
        <clear />        
        <add name="MyCustomMembershipProvider" 
             type="MyNamespace.MyCustomMembershipProvider" 
             enablePasswordRetrieval="false"
             enablePasswordReset="true"          
             requiresQuestionAndAnswer="false"          
             requiresUniqueEmail="true"           
             passwordFormat="Hashed"           
             maxInvalidPasswordAttempts="10"           
             minRequiredPasswordLength="6"           
             minRequiredNonalphanumericCharacters="0"           
             passwordAttemptWindow="10"           
             passwordStrengthRegularExpression=""           
             applicationName="/" />      
    </providers>     
</membership>

The next bit I think you're overthinking, the actual tie-in to your web application. Whereas in a WebForms app you kind of have to code the rest for yourself - the MVC framework does the rest for you - all you need to do is add the [Authorize] attribute to your action method and the framework will check to see if you're logged in, and if not redirect you to the login page. The login page will find your custom provider because that's what's configured in the web.config and will log your user in. You can access information about the logged in user from your controllers by referencing the User object:

下一点,我认为你想得太多了,你的web应用程序的实际关联。而在WebForms应用你的剩下的代码——MVC框架为你做其他所有您需要做的是(授权)属性添加到您的操作方法和框架将检查如果你登录,如果没有将您重定向到登录页面。登录页面将找到您的自定义提供程序,因为这是在web中配置的。配置,并将登录您的用户。您可以通过引用用户对象从控制器访问登录用户的信息:

public class WhateverController : Controller
{
    [Authorize]
    public ActionResult WhateverAction()
    {
        ViewData["LoggedInAs"] = string.Format("You are logged in as {0}.", User.Identity.Name);
        Return View();
    }
}

So this action requires that the user is logged in and presents the user information to the Whatever/WhateverAction.aspx view to be displayed on the page.

因此这个操作需要用户登录并将用户信息呈现给Whatever/WhateverAction。aspx视图显示在页面上。

#2


1  

My custom membership provider is referenced in the web.config:

我的自定义成员提供程序在web.config中被引用:

 <membership defaultProvider="MyMembershipProvider">
  <providers>
    <clear/>
    <add name="MyMembershipProvider" type="Namespace.MyMembershipProvider, Namespace" connectionStringName="connstring" [...] />
  </providers>
</membership>

Then just use static Membership class.

然后使用静态成员类。

#3


0  

How much did you change in this custom membership? Like did you change table names around? Can you log users in and stuff? Ie is your custom membership working?

您在这个自定义会员中更改了多少?就像你换过名字一样?你能记录用户的信息吗?你的自定义会员资格有效吗?

If you changed lots of stuff around like you changed the roles table name to something different or stuff like that then your going to have to override the Authroize tag.

如果你改变了很多东西比如你把roles表名改成了不同的或者类似的东西那么你就必须重写Authroize标签。

However if your custom membership is not working then you probably have not configured it right and configuring is the same as in webforms. You just have to setup your webconfig.

但是,如果您的自定义成员关系不工作,那么您可能没有正确地配置它,并且配置与在webforms中相同。你只需要设置你的webconfig。

  </authentication>
    <membership>
      <providers>
        <clear />
        <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="ConnectionString"
         enablePasswordRetrieval="false"
         enablePasswordReset="true"
          requiresQuestionAndAnswer="false"
          requiresUniqueEmail="true"
           passwordFormat="Hashed"
           maxInvalidPasswordAttempts="10"
           minRequiredPasswordLength="6"
           minRequiredNonalphanumericCharacters="0"
           passwordAttemptWindow="10"
           passwordStrengthRegularExpression=""
           applicationName="/"  />
      </providers>
    </membership>
    <profile>
      <providers>
        <clear />
        <add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="ConnectionString" applicationName="/" />
      </providers>
    </profile>
    <roleManager enabled="true">
      <providers>
        <clear />
        <add connectionStringName="ConnectionString"
          applicationName="/" name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
        <add applicationName="/" name="AspNetWindowsTokenRoleProvider"
          type="System.Web.Security.WindowsTokenRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
      </providers>
    </roleManager>

#1


6  

Hopefully I can add some additional clarity over the other answers as they really don't explain what's going on which isn't going to help your confusion.

希望我能在其他答案上增加一些额外的清晰性,因为它们并不能解释发生了什么,这对你的困惑没有帮助。

First up, implement your custom provider which from the sound of things you've done already, so I'll just throw up a little code snippet and won't go into any further detail here:

首先,实现您的自定义提供程序,从您已经做过的事情的声音,所以我将抛出一个小代码片段,这里不再详细介绍:

using System.Web.Security;

public class MyCustomMembershipProvider : MembershipProvider
{
    public override bool ValidateUser(string username, string password)
    {
        if (username.Equals("BenAlabaster") && password.Equals("Elephant"))
            return true;

        return false;
    }

    /* Override all the other methods required to extend MembershipProvider */        
}

Then you configure your provider in your web.config making sure to populate the attributes that configure the base MembershipProvider:

然后在web中配置提供者。配置确保填充配置基本MembershipProvider的属性:

<membership defaultProvider="MyCustomMembershipProvider">      
    <providers>        
        <clear />        
        <add name="MyCustomMembershipProvider" 
             type="MyNamespace.MyCustomMembershipProvider" 
             enablePasswordRetrieval="false"
             enablePasswordReset="true"          
             requiresQuestionAndAnswer="false"          
             requiresUniqueEmail="true"           
             passwordFormat="Hashed"           
             maxInvalidPasswordAttempts="10"           
             minRequiredPasswordLength="6"           
             minRequiredNonalphanumericCharacters="0"           
             passwordAttemptWindow="10"           
             passwordStrengthRegularExpression=""           
             applicationName="/" />      
    </providers>     
</membership>

The next bit I think you're overthinking, the actual tie-in to your web application. Whereas in a WebForms app you kind of have to code the rest for yourself - the MVC framework does the rest for you - all you need to do is add the [Authorize] attribute to your action method and the framework will check to see if you're logged in, and if not redirect you to the login page. The login page will find your custom provider because that's what's configured in the web.config and will log your user in. You can access information about the logged in user from your controllers by referencing the User object:

下一点,我认为你想得太多了,你的web应用程序的实际关联。而在WebForms应用你的剩下的代码——MVC框架为你做其他所有您需要做的是(授权)属性添加到您的操作方法和框架将检查如果你登录,如果没有将您重定向到登录页面。登录页面将找到您的自定义提供程序,因为这是在web中配置的。配置,并将登录您的用户。您可以通过引用用户对象从控制器访问登录用户的信息:

public class WhateverController : Controller
{
    [Authorize]
    public ActionResult WhateverAction()
    {
        ViewData["LoggedInAs"] = string.Format("You are logged in as {0}.", User.Identity.Name);
        Return View();
    }
}

So this action requires that the user is logged in and presents the user information to the Whatever/WhateverAction.aspx view to be displayed on the page.

因此这个操作需要用户登录并将用户信息呈现给Whatever/WhateverAction。aspx视图显示在页面上。

#2


1  

My custom membership provider is referenced in the web.config:

我的自定义成员提供程序在web.config中被引用:

 <membership defaultProvider="MyMembershipProvider">
  <providers>
    <clear/>
    <add name="MyMembershipProvider" type="Namespace.MyMembershipProvider, Namespace" connectionStringName="connstring" [...] />
  </providers>
</membership>

Then just use static Membership class.

然后使用静态成员类。

#3


0  

How much did you change in this custom membership? Like did you change table names around? Can you log users in and stuff? Ie is your custom membership working?

您在这个自定义会员中更改了多少?就像你换过名字一样?你能记录用户的信息吗?你的自定义会员资格有效吗?

If you changed lots of stuff around like you changed the roles table name to something different or stuff like that then your going to have to override the Authroize tag.

如果你改变了很多东西比如你把roles表名改成了不同的或者类似的东西那么你就必须重写Authroize标签。

However if your custom membership is not working then you probably have not configured it right and configuring is the same as in webforms. You just have to setup your webconfig.

但是,如果您的自定义成员关系不工作,那么您可能没有正确地配置它,并且配置与在webforms中相同。你只需要设置你的webconfig。

  </authentication>
    <membership>
      <providers>
        <clear />
        <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="ConnectionString"
         enablePasswordRetrieval="false"
         enablePasswordReset="true"
          requiresQuestionAndAnswer="false"
          requiresUniqueEmail="true"
           passwordFormat="Hashed"
           maxInvalidPasswordAttempts="10"
           minRequiredPasswordLength="6"
           minRequiredNonalphanumericCharacters="0"
           passwordAttemptWindow="10"
           passwordStrengthRegularExpression=""
           applicationName="/"  />
      </providers>
    </membership>
    <profile>
      <providers>
        <clear />
        <add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="ConnectionString" applicationName="/" />
      </providers>
    </profile>
    <roleManager enabled="true">
      <providers>
        <clear />
        <add connectionStringName="ConnectionString"
          applicationName="/" name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
        <add applicationName="/" name="AspNetWindowsTokenRoleProvider"
          type="System.Web.Security.WindowsTokenRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
      </providers>
    </roleManager>