使用asp.net身份验证和自定义身份验证

时间:2012-05-20 17:14:40

标签: asp.net asp.net-mvc

这是我的情景。

我有其他域公开的身份验证Web服务。现在我希望将用户名和密码发送到该外部域进行身份验证。当用户通过身份验证(返回true)时,我希望ASP.net进一步采用该身份验证,并让用户进入并向我提供所有可访问的asp.net标准实用程序,如currentuser,Isauthorized,Roles等,对于用户,经过身份验证。我希望这是有道理的。

2 个答案:

答案 0 :(得分:2)

这不是问题。您有多种选择。一种方法是将表单身份验证与您自己的安全模型进行混合。

基本思路是让Forms Auth为登录用户创建和管理故障单(以加密票证的形式)。故障单用于确定某人是否已登录,以及他们是谁。然后,您可以混合使用任何其他安全相关的逻辑。

要处理登录请求,您只需拥有一个像往常一样的控制器和操作。注意:在下面的示例中,我对LoginViewModel,您用于进行身份验证的服务以及它返回的对象(如果有)进行了一些假设。你必须在你的实际逻辑中加入。

public ActionResult Login(LoginViewModel model)
{
      // make sure the user filled out the login fields correctly
      if (!ModelState.IsValid) return View(model);

      // authenticate the user here
      var authenticatedUser = AuthorizeUserUsingRemoteWebService(model.Username, model.Password);

      if (authenticatedUser.IsAuthenticated) 
      {
         // create forms auth ticket cookie and redirect to the home page
         FormsAuthentication.SetAuthCookie(authenticatedUser.Username);

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

     // authentication failed, so show the login page again 
     return View(model);
}

除此之外,您可能还有一个处理AuthenticateRequest事件的HTTP模块。您的模块将在Forms Auth HTTP模块之后注册,因此它已经处理过用户是否已登录。您要做的是在登录时查找其他信息,以获取角色等。< / p>

public class CustomAuthHttpModule : IHttpModule
{    
    public void Init(HttpApplication context)
    {
        context.AuthenticateRequest += new EventHandler(OnAuthenticateRequest);
    }

    void OnAuthenticateRequest(object sender, EventArgs e)
    {
        HttpApplication application = (HttpApplication)sender;
        HttpContext context = appObject.Context;

        // user isn't logged in, so don't do anything else
        if (!context.User.Identity.IsAuthenticated) return;

        // look up the roles for the specified user, returning the role names as an array of strings
        string[] roles = LookupUserRolesFromWebService(context.User.Identity.Name);

        // replace the current User principal with a new one that includes the roles we discovered for that user.
        context.User = new GenericPrincipal(new GenericIdentity(context.User.Identity.Name), roles);
    }
}

您将在web.config中注册HTTP模块:

<httpModules>
    <add name="CustomAuthHttpModule" 
       type="MyAssembly.CustomAuthenticationModule, MyAssembly" />
</httpModules>

您现在可以在MVC控制器和视图中使用User对象,AuthenticatedAttribute等。

但是,我建议您缓存查找用户角色的结果,这样就不会破坏您的Web服务。我会把它留给你。

答案 1 :(得分:0)

您可以为您的应用程序使用安全令牌服务。设置Windows Identity Foundation SDK并在sdk目录中查找示例(对我而言,它是“C:\ Program Files(x86)\ Windows Identity Foundation SDK \ v4.0 \ Samples \ End-to-end \ Federation for Web Apps”) 。其中一个(名为“Web应用程序联盟”)实现了AD身份验证的案例。