微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

asp.net-mvc – 向MVC 3添加基于声明的授权

我有一个MVC应用程序,我想添加基于声明的授权。在不久的将来,我们将使用ADFS2进行联合身份验证,但现在我们将在本地使用表单身份验证。

有没有人看到一个教程或博客文章关于没有外部身份提供商使用WIF的最佳方式?

我已经看到以下,但现在是一岁,我认为应该有一个更容易的解决方案:

http://geekswithblogs.net/shahed/archive/2010/02/05/137795.aspx

解决方法

您可以在没有STS的情况下在MVC中使用WIF。

我使用认的MVC2模板,但它也应该与MVC 3一起工作。

你需要:

1-插入WIF的SessionAuthenticationModule(web.config)

< add name="SessionAuthenticationModule" type="Microsoft.IdentityModel.Web.SessionAuthenticationModule,Microsoft.IdentityModel,Version=3.5.0.0,Culture=neutral,PublicKeyToken=31bf3856ad364e35" />

2-无论何时验证用户,创建ClaimPrincipal,添加所有必需的声明,然后创建一个SessionSecurityToken。这是MVC创建的AccountController中的logon Action:

[HttpPost]
        public ActionResult logon(logonModel model,string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ValidateUser(model.UserName,model.Password))
                {
                    var cp = new ClaimsPrincipal();
                    cp.Identities.Add(new ClaimsIdentity());
                    IClaimsIdentity ci = (cp.Identity as IClaimsIdentity);

                    ci.Claims.Add(new Claim(ClaimTypes.Name,model.UserName));

                    SessionSecurityToken sst = FederatedAuthentication
                        .SessionAuthenticationModule
                        .CreateSessionSecurityToken(cp,"MVC Test",DateTime.
                                                        UtcNow,DateTime.
                                                        UtcNow.
                                                        AddHours
                                                        (1),true);


                    FederatedAuthentication.SessionAuthenticationModule.CookieHandler.RequireSsl = false;
                    FederatedAuthentication.SessionAuthenticationModule.AuthenticateSessionSecurityToken(sst,true);


                    //FormsService.SignIn(model.UserName,model.RememberMe);
                    if (!String.IsNullOrEmpty(returnUrl))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index","Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("","The user name or password provided is incorrect.");
                }
            }

            // If we got this far,something Failed,redisplay form
            return View(model);
        }

我只是添加了所需的行,并保持一切都一样。因此可能需要重构。

从那时起,您的应用程式将会收到ClaimPrincipal。全部由WIF自动处理。

CookieHandler.RequiresSsl = false只是因为它是一个开机,我不在IIS上部署。它也可以在配置中定义。

原文地址:https://www.jb51.cc/aspnet/252340.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐