2012-05-20 267 views
0

这是我的方案。使用asp.net身份验证与自定义身份验证

我有另一个域暴露身份验证的Web服务。现在我想要将用户名和密码发送到该外部域进行身份验证。而当用户进行身份验证(返回true),我想ASP.net,以采取进一步的认证,并让用户和提供我所有的asp.net标准工具访问,像currentuser,Isauthorized,角色等,对于用户来说,认证。我希望这是有道理的。

回答

2

这不是问题。你有各种选择可供你使用。一种方法是将Forms Authentication与您自己的安全模型混合。

的基本思想是让窗体身份验证的登录用户创建和管理一票(在加密票证的形式)。该票据用于确定某人是否已登录,以及他们是谁。然后,您可以混合使用任何其他安全相关的逻辑。

要处理的登录请求,你只需要一个控制器和行动就像你通常会。注意:在下面的例子中,我对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控制器和视图,该AuthenticatedAttribute

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

0

您可以使用安全令牌服务为您的应用程序。设置Windows Identity Foundation SDK并在sdk目录中找到示例(对于我来说,它是“C:\ Program Files(x86)\ Windows Identity Foundation SDK \ v4.0 \ Samples \ End-to-end \ Web应用程序的联合”) 。其中一个(名为“Web应用程序联盟”)实施您的AD认证案例。

相关问题