如何使用 ASP.NET 身份模型进行 WCF 服务授权和身份验证

2023-11-30

我正在开发一个 ASP.NET 4.5 Web 应用程序,它使用 ASP.NET 身份模型进行身份验证和授权。

该 Web 应用程序还托管 WCF 服务并同时使用它。还有另一个基于 WPF 的应用程序将使用托管的 WCF 服务(以及作为客户端本身的 Web 应用程序)。

我想要授权和验证每个 WCF 服务请求(来自 Web 应用程序客户端或 WPF 客户端)。

在理想情况下,我想使用相同的 ASP.NET 身份模型来进行 WCF 操作合约的身份验证/授权。如何从 Web 应用程序和 WPF 应用程序实现此目的?


您可以使用PrincipalPermissionAttribute 来装饰授权操作的实现。

    public class Service1 : IService1 
{
    public string GetData(int value)
    {
        System.Diagnostics.Debug.WriteLine("GetDataCalled");
        if (value == 666)
            throw new FaultException<Evil666Error>(new Evil666Error() { Message = "Hey, this is 666." });

        return string.Format("You entered: {0}", value);
    }

    [PrincipalPermission(SecurityAction.Demand, Role="Admin")]
    [PrincipalPermission(SecurityAction.Demand, Role="Customer")]
    public CompositeType GetDataUsingDataContract(CompositeType composite)
    {
        var userName = ServiceSecurityContext.Current.PrimaryIdentity.Name;


        if (composite == null)
        {
            throw new ArgumentNullException("composite");
        }

        if (composite.BoolValue)
        {
            composite.StringValue += "Suffix";
        }
        return composite;
    }
}

所以第一个操作只需要认证,而第二个操作需要授权。

然后您需要编写自定义身份验证和授权代码。

    /// <summary>
/// Used in ServiceModel's ServiceBehavior for authentication of service operations.
/// </summary>
public class IdentityValidator : UserNamePasswordValidator
{
    public override void Validate(string userName, string password)
    {
        using (var context = new WebPortalDbContext())
        {
            using (var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)))
            {
                var user = userManager.Find(userName, password);
                if (user == null)
                {
                    var msg = String.Format("Unknown Username {0} or incorrect password {1}", userName, password);
                    Trace.TraceWarning(msg);
                    throw new FaultException(msg);//the client actually will receive MessageSecurityException. But if I throw MessageSecurityException, the runtime will give FaultException to client without clear message.
                }
            }

        }

    }
}

/// <summary>
/// Used in ServiceModel's ServiceBehavior for authorization of service operation, according to the role in PrincipalPermissionAttribute
/// </summary>
public class RoleAuthorizationManager : ServiceAuthorizationManager
{
    protected override bool CheckAccessCore(OperationContext operationContext)
    {
        base.CheckAccessCore(operationContext);
        using (var context = new WebPortalDbContext())
        using (var userStore = new UserStore<ApplicationUser>(context))
        {
            using (var userManager = new UserManager<ApplicationUser>(userStore))
            {
                var identity =operationContext.ServiceSecurityContext.PrimaryIdentity;
                var user = userManager.FindByName(identity.Name);
                if (user == null)
                {
                    var msg = String.Format("Unknown Username {0} .", user.UserName);
                    Trace.TraceWarning(msg);
                    throw new FaultException(msg);
                }

                //Assign roles to the Principal property for runtime to match with PrincipalPermissionAttributes decorated on the service operation.
                var roleNames = userManager.GetRoles(user.Id).ToArray();//users without any role assigned should then call operations not decorated by PrincipalPermissionAttributes
                operationContext.ServiceSecurityContext.AuthorizationContext.Properties["Principal"] = new GenericPrincipal(operationContext.ServiceSecurityContext.PrimaryIdentity, roleNames);

                return true;
            }
        }

    }


}

在配置中,您应该将它们连接在一起。

      <serviceBehaviors>
    <behavior name="authBehavior">
      <serviceCredentials>
        <userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="MyNamespace.IdentityValidator,MyNamespace.Security" />
      </serviceCredentials>
      <serviceAuthorization principalPermissionMode="Custom" serviceAuthorizationManagerType="Mynamespace.Security.RoleAuthorizationManager,mynamespace.Security"></serviceAuthorization>
      <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
      <serviceDebug includeExceptionDetailInFaults="True" />
    </behavior>
  </serviceBehaviors>



      <service name="Fonlow.Demo.RealWorldService.Service1" behaviorConfiguration="authBehavior">
    <!-- Service Endpoints. A Service may provide multiple endpoints -->
    <!-- Not need to define host. Relative  -->
    <endpoint address="" binding="basicHttpsBinding" contract="Fonlow.Demo.RealWorldService.IService1" bindingConfiguration="httpsBindingConfig">
      <identity>
        <dns value="localhost" />
      </identity>
    </endpoint>
  </service>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 ASP.NET 身份模型进行 WCF 服务授权和身份验证 的相关文章

随机推荐

  • 控制器中的 MVC Core SelectList 下拉菜单错误“Microsoft.AspNetCore.Mvc.Rendering.SelectListItem”

    我想在 MVC 中创建一个 SelectList Dropdown 我更喜欢选择列表位于存储库中 而不是控制器中 如何调用存储库 甚至不引用模型中的字段名称 我唯一想参考的是存储库 我收到此 Microsoft AspNetCore Mvc
  • 表中每行的边框半径

    我有这样的表格 我想将样式应用到带有圆角的每一行 table tr td Month td td Savings td tr tr td January td td 100 td tr tr td February td td 80 td
  • 使用 PowerShell 将 Windows 用户添加到本地 SQL Server

    我想使用 PowerShell 将现有本地用户作为系统管理员添加到 SQL Server 经过一些研究 到目前为止我有以下脚本 Username JohnDoe System Reflection Assembly LoadWithPart
  • 如何重新定位 Chrome 开发者工具

    默认情况下 这些工具在 Chrome 窗口的底部打开 对于宽屏显示器来说 这是一个相当糟糕的选择 因为右侧有大量的空白空间 但没有太多的垂直空间可供使用 不幸的是 我找不到重新定位工具的方法 我想把它们放在一边 类似于萤火虫 与我想要的类似
  • CMake 无法确定目标的链接器语言:fileloader

    我知道已经有一些关于这个主题的线程 但是 在阅读其中许多线程后 我无法找到解决我的问题的方法 我正在开发文件加载器 解析器 并且是第一次使用 CMake 我的 CMakeList txt 文件用于导入 XML 解析器 xerces 当前如下
  • Pygame 按键/按键

    我正在为学校的计算机俱乐部制作一个小马里奥 好吧 作为团队的一部分 无论如何 我在使用 keyup keydown 命令时遇到了一些麻烦 这是我的代码 1 Import library import pygame from pygame l
  • WooCommerce 更改加载微调器图标

    IM 尝试更改 WooCommerce 加载旋转图标 它在 woocommerce css 中定义 woocommerce blockUI blockOverlay before height 1em width 1em display b
  • 如何配置应用程序以在具有高 DPI 设置(例如 150%)的计算机上正确运行?

    我用 C 创建了一个简单的 Winforms 应用程序 当我在具有高 DPI 设置 例如 150 的计算机上运行应用程序时 应用程序会放大 到目前为止 一切都很好 但所有文本也只是按比例放大 而不是使用更大的字体大小渲染字体 这当然会导致文
  • 鼠标光标与画布不匹配

    我有一个问题 当我在画布上画一条线时 似乎鼠标位置与画布位置不匹配 所以每当我画画时 光标和画线之间都有一定的距离 请帮助我这个问题 这是我的代码 document ready function context document getEl
  • 卸载矩阵并释放内存

    我可以从文本文件加载矩阵 load mydata txt 问题是我的矩阵文件大约有 250Mb 经过几次这样的加载后 我没有内存来处理下一个文件 如何卸载它并释放资源以供进一步使用 Use clear or 清除变量 默认情况下 MATLA
  • Swift 2.2,包含方法不起作用

    包含方法无法正常工作 即使它与对象匹配 它也会给我错误的结果 我的代码如下 class Generic NSObject NSCoding var genericCode String var genericName String var
  • 为什么 PostgreSQL 适配器 psycopg2 在 Google App Engine dev_appserver.py 中失败?

    我想将 GAE 中的应用程序与 ElephantDB 连接起来 我想使用 lib psycopg2 但发现了一个问题 我在本地安装了该库来测试它并完美运行 然后我将该库安装在我的应用程序的 lib 文件夹中 就像我对其他库所做的很多次一样
  • 命名空间和类同名吗?

    我正在组织一个图书馆项目 并且有一个名为的中央管理器类Scenegraph以及位于 Scenegraph 命名空间中的一大堆其他类 我真正想要的是场景图MyLib Scenegraph和其他类别MyLib Scenegraph 但似乎唯一的
  • AngularJS UI-Router:在应用程序加载之前预加载 $http 数据

    我需要使用过 ui router 插件的 AngularJS 专家的帮助 有人可以提供一个在应用程序运行之前预加载 http 数据请求的 plunker 示例吗 我做了一些研究 但最接近的是这两个堆栈溢出 AngularJS 如何在应用程序
  • Java程序禁用SSL认证存在安全风险

    我们的团队会抓取网站以使我们的信息保持最新 我遇到了抓取HTTPS页面时的安全异常 问题在于 Java 在接受页面自签名证书时存在问题 我没有保留要接受的证书列表 将来可能很难维护 而是使用 neu242 提供的解决方法来禁用 SSL 证书
  • 在运行时将 C# 标签添加到表单

    我正在尝试用 C 制作一个简单的基于文本的游戏 我想实现这一点的方法是向表单添加标签 而不是使用命令提示符 我在将它们添加到屏幕时遇到一些问题 Visual Studio 给出了一个未指定的错误 只是说我有一个未处理的异常 你调用的对象是空
  • 如何去除抽屉上方的台阶

    我在用着DaisyUI and 顺风CSS 我正在使用一个drawer and steps div class drawer div
  • 在托管类中调用非托管函数时出现 C++/CLI System.AccessViolationException

    我在 C 中有一个本机回调函数 让我们这样说 void CallbackFunction void Do nothing 现在我有另一个本机函数 void SomeNativeFunction void m callback std tr1
  • 终止子进程时终止所有(孙)子进程

    我将直接进入 简短且具有描述性 C Windows API 我正在使用创建子进程CreateProcess运行外部 命令行 应用程序 我已经内置了一个超时 如果到那时子进程还没有返回正常执行 我希望强制终止该子进程 理想情况下 我希望该子进
  • 如何使用 ASP.NET 身份模型进行 WCF 服务授权和身份验证

    我正在开发一个 ASP NET 4 5 Web 应用程序 它使用 ASP NET 身份模型进行身份验证和授权 该 Web 应用程序还托管 WCF 服务并同时使用它 还有另一个基于 WPF 的应用程序将使用托管的 WCF 服务 以及作为客户端