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上部署。它也可以在配置中定义。

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....