如何使用OWIN和使用ASP.NET MVC从ADFS返回的SAML票证进行登录?

Chr*_*ris 5 c# authentication asp.net-mvc claims-based-identity owin-middleware

我有一个拥有自己的登录屏幕的网站,用户在其中输入用户名和密码。按下登录按钮后,应该通过ADFS对用户进行身份验证,并且我应该获得SAML令牌。这可行。不过目前我不确定要登录的用户该怎么做,我不确定的原因是因为该网站有些曲折。就像我说过的那样,用户通过我们网站的登录页面通过ADFS登录。但是,如果用户访问了未经授权的页面,而不是将用户重定向到我们的登录页面,则需要将用户重定向到我们的ADFS登录页面。我以这种方式开始了整个项目。用户通过ADFS的登录页面进行身份验证。只需通过如下设置我的ConfigureAuth方法(在StartupAuth.cs中)即可完成:

public void ConfigureAuth(IAppBuilder app)
{
    app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

    app.UseCookieAuthentication(new CookieAuthenticationOptions());

    app.UseWsFederationAuthentication(
        new WsFederationAuthenticationOptions
        {
            Wtrealm = realm,
            MetadataAddress = adfsMetadata
        });
}
Run Code Online (Sandbox Code Playgroud)

很简单!如果我尝试转到某个[Authorized]页面,它将带我进入ADFS登录页面。之后,是时候尝试其他登录方法了(通过使用登录页面通过ADFS进行身份验证)。请记住,尝试进行身份验证的任何一种方式仍在使用相同的ADFS进行身份验证。一个正在使用ADFS的登录页面,另一个正在使用自定义登录页面。因此,我使用一个简单的小表单来创建自定义登录页面以进行登录:

<form action="@Url.Action("SignIn", "Account")" method="post">
    <input type="text" name="username" />
    <input type="password" name="password" />
    <input type="submit" value="Login" />
</form>
Run Code Online (Sandbox Code Playgroud)

这样很好。按下提交按钮后,它将尝试登录操作。登录操作如下所示:

[HttpPost]
public ActionResult SignIn(string username, string password)
{
    if (!Request.IsAuthenticated)
    {
        const string _relyingPartyUri = "https://myrelayingparty/";
        const string _serverName = "myservername";
        const string certSubject = "CN=mycertsubject";
        string endpointUri = string.Format("https://{0}/adfs/services/trust/13/usernamemixed", _serverName);

        var factory = new WSTrustChannelFactory(new UserNameWSTrustBinding(), endpointUri)
        {
            TrustVersion = TrustVersion.WSTrust13
        };

        factory.Credentials.UserName.UserName = @"mydomain\" + username;
        factory.Credentials.UserName.Password = password;

        var rst = new RequestSecurityToken
        {
            RequestType = RequestTypes.Issue,
            AppliesTo = new EndpointReference(_relyingPartyUri),
            KeyType = KeyTypes.Bearer
        };

        var channel = factory.CreateChannel();

        var genericToken = channel.Issue(rst) as GenericXmlSecurityToken;

        if (genericToken != null)
        {
            //Setup the handlers needed to convert the generic token to a SAML Token
            var tokenHandlers = new SecurityTokenHandlerCollection(new SecurityTokenHandler[] { new SamlSecurityTokenHandler() });
            tokenHandlers.Configuration.AudienceRestriction = new AudienceRestriction();
            tokenHandlers.Configuration.AudienceRestriction.AllowedAudienceUris.Add(new Uri(_relyingPartyUri));

            var trusted = new TrustedIssuerNameRegistry(certSubject);
            tokenHandlers.Configuration.IssuerNameRegistry = trusted;

            //convert the generic security token to a saml token
            SecurityToken samlToken = tokenHandlers.ReadToken(new XmlTextReader(new StringReader(genericToken.TokenXml.OuterXml)));

            //convert the saml token to a claims principal
            var claimsPrincipal = new ClaimsPrincipal(tokenHandlers.ValidateToken(samlToken).First());


            HttpContext.GetOwinContext().Authentication.SignIn(new AuthenticationProperties { IsPersistent = true, RedirectUri = "Home/Homepage" },
                claimsPrincipal.Identities.ElementAt(0));
        }
    }

    return RedirectToAction("Index", "Home");
}
Run Code Online (Sandbox Code Playgroud)

它可以成功检索并创建samlToken,甚至可以对其进行验证并创建ClaimsPrincipal。我不确定在此之后要做什么才能登录。我尝试使用HttpContext.GetOwinContext().Authentication.SignIn(new AuthenticationProperties { IsPersistent = true, RedirectUri = "Home/Homepage" }, claimsPrincipal.Identities.ElementAt(0));,但是如果在此之后检查Request.IsAuthenticated,它仍然是错误的。我暗中怀疑StartupAuth.cs文件中需要其他配置,但是我不确定,这就是为什么我向你们求助。感谢您提供的所有帮助!