0

这是我的场景。

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

4

2 回答 2

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 模块之后注册,因此它已经处理了用户是否登录。您要做的是查找其他信息(如果他们已登录),以获取角色等。

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 服务。我会把它留给你。

于 2012-05-20T17:58:16.037 回答
0

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

于 2013-05-28T20:39:35.427 回答