本文转自:https://msdn.microsoft.com/en-us/library/aa702720(v=vs.110).aspx

The PrincipalPermissionAttribute is a declarative means of controlling access to service methods. When using this attribute, the PrincipalPermissionMode enumeration specifies the mode for performing authorization checks. When this mode is set to Custom, it enables the user to specify a custom IPrincipal class returned by the CurrentPrincipal property. This topic illustrates the scenario when Custom is used in combination with a custom authorization policy and a custom principal.

For more information about using the PrincipalPermissionAttribute, see How to: Restrict Access with the PrincipalPermissionAttribute Class.

Example

namespace CustomMode
{
public class Test
{
public static void Main()
{
try
{
ShowPrincipalPermissionModeCustom ppwm = new ShowPrincipalPermissionModeCustom();
ppwm.Run(); }
catch (Exception exc)
{
Console.WriteLine("Error: {0}", exc.Message);
Console.ReadLine();
}
}
} class ShowPrincipalPermissionModeCustom
{
[ServiceContract]
interface ISecureService
{
[OperationContract]
string Method1(string request);
} [ServiceBehavior]
class SecureService : ISecureService
{
[PrincipalPermission(SecurityAction.Demand, Role = "everyone")]
public string Method1(string request)
{
return String.Format("Hello, \"{0}\"", Thread.CurrentPrincipal.Identity.Name);
}
} public void Run()
{
Uri serviceUri = new Uri(@"http://localhost:8006/Service");
ServiceHost service = new ServiceHost(typeof(SecureService));
service.AddServiceEndpoint(typeof(ISecureService), GetBinding(), serviceUri);
List<IAuthorizationPolicy> policies = new List<IAuthorizationPolicy>();
policies.Add(new CustomAuthorizationPolicy());
service.Authorization.ExternalAuthorizationPolicies = policies.AsReadOnly();
service.Authorization.PrincipalPermissionMode = PrincipalPermissionMode.Custom;
service.Open(); EndpointAddress sr = new EndpointAddress(
serviceUri, EndpointIdentity.CreateUpnIdentity(WindowsIdentity.GetCurrent().Name));
ChannelFactory<ISecureService> cf = new ChannelFactory<ISecureService>(GetBinding(), sr);
ISecureService client = cf.CreateChannel();
Console.WriteLine("Client received response from Method1: {0}", client.Method1("hello"));
((IChannel)client).Close();
Console.ReadLine();
service.Close();
} public static Binding GetBinding()
{
WSHttpBinding binding = new WSHttpBinding(SecurityMode.Message);
binding.Security.Message.ClientCredentialType = MessageCredentialType.Windows;
return binding;
} class CustomAuthorizationPolicy : IAuthorizationPolicy
{
string id = Guid.NewGuid().ToString(); public string Id
{
get { return this.id; }
} public ClaimSet Issuer
{
get { return ClaimSet.System; }
} public bool Evaluate(EvaluationContext context, ref object state)
{
object obj;
if (!context.Properties.TryGetValue("Identities", out obj))
return false; IList<IIdentity> identities = obj as IList<IIdentity>;
if (obj == null || identities.Count <= 0)
return false; context.Properties["Principal"] = new CustomPrincipal(identities[0]);
return true;
}
} class CustomPrincipal : IPrincipal
{
IIdentity identity;
public CustomPrincipal(IIdentity identity)
{
this.identity = identity;
} public IIdentity Identity
{
get { return this.identity; }
} public bool IsInRole(string role)
{
return true;
}
}
}
}

[转]How to: Create a Custom Principal Identity的更多相关文章

  1. [转]How do you create a custom AuthorizeAttribute in ASP.NET Core?

    问: I'm trying to make a custom authorization attribute in ASP.NET Core. In previous versions it was ...

  2. Part 13 Create a custom filter in AngularJS

    Custom filter in AngularJS 1. Is a function that returns a function 2. Use the filter function to cr ...

  3. How could I create a custom windows message?

    [问题] Our project is running on Windows CE 6.0 and is written in C++ . We have some problems with the ...

  4. [Angular] Create a custom validator for reactive forms in Angular

    Also check: directive for form validation User input validation is a core part of creating proper HT ...

  5. [Angular] Create a custom validator for template driven forms in Angular

    User input validation is a core part of creating proper HTML forms. Form validators not only help yo ...

  6. how to create react custom hooks with arguments

    how to create react custom hooks with arguments React Hooks & Custom Hooks // reusable custom ho ...

  7. [Angular] Create a custom pipe

    For example we want to create a pipe, to tranform byte to Mb. We using it in html like: <div> ...

  8. Create a custom configSection in web.config or app.config file

    config file: <?xml version="1.0" encoding="utf-8" ?> <configuration> ...

  9. How to create a custom action type with a custom control (BarCheckItem), associated with it

    https://www.devexpress.com/Support/Center/Example/Details/E1977/how-to-create-a-custom-action-type-w ...

随机推荐

  1. 应用OpenMP的一个简单的设计模式

    小喵的唠叨话:最近很久没写博客了,一是因为之前写的LSoftmax后馈一直没有成功,所以在等作者的源码.二是最近没什么想写的东西.前两天,在预处理图片的时候,发现处理200w张图片,跑了一晚上也才处理 ...

  2. 从零开始编写自己的C#框架(15)——Web层后端登陆功能

    对于一个后端管理系统,最重要内容之一的就是登陆页了,无论是安全验证.用户在线记录.相关日志记录.单用户或多用户使用帐号控制等,都是在这个页面进行处理的. 1.在解决方案中创建一个Web项目,并将它设置 ...

  3. Hawk 4.2 过滤器

    过滤器可以在流中,过滤掉不符合条件的文档.当然也可勾选反向,此时只会留下不符合条件的文档. 空对象过滤器 最为常用,需要列名,可以过滤掉所有内容为Null,或字符串全部都是空字符的情况 数值范围过滤 ...

  4. 如何修复VUM在客户端启用之后报数据库连接失败的问题

    在上一篇随笔中介绍了关于重新注册VMware Update Manager(VUM)至vCenter Server中的方法,最近有朋友反应,原本切换过去好好的更新服务为什么某次使用一下就不灵了? 当时 ...

  5. 使用session页面控制登录入口及购物车效果的实现

          由于 Session 是以文本文件形式存储在服务器端的,所以不怕客户端修改 Session 内容.实际上在服务器端的 Session 文件,PHP 自动修改 Session 文件的权限,只 ...

  6. 你真的会玩SQL吗?EXISTS和IN之间的区别

    你真的会玩SQL吗?系列目录 你真的会玩SQL吗?之逻辑查询处理阶段 你真的会玩SQL吗?和平大使 内连接.外连接 你真的会玩SQL吗?三范式.数据完整性 你真的会玩SQL吗?查询指定节点及其所有父节 ...

  7. 匹夫细说C#:庖丁解牛聊委托,那些编译器藏的和U3D给的

    0x00 前言 由于工作繁忙所以距离上一篇博客已经过去一个多月的时间了,因此决心这个周末无论如何也得写点东西出来,既是总结也是分享.那么本文主要的内容集中在了委托的使用以及内部结构(当然还有事件了,但 ...

  8. OA办公自动化系统源码

    最新extjs6富客户端,.net平台开发,sql server数据库,基础权限人员基础平台,可方便二次开发,使用EF为orm,autofac为ioc,Castle为基础的aop,实现常用OA系统功能 ...

  9. C#——this关键字(2,3)(含求助贴)

    这次来看一看this关键字的第二个用法:将对象作为参数传递到其他方法 ----------------------------------------------------------------- ...

  10. asp.net创建事务的方法

    1.建立List用于存放多条语句 /// <summary> /// 保存表单 /// </summary> /// <param name="context& ...