[转]How to: Create a Custom Principal Identity
本文转自: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;
}
}
}
}
Compiling the Code
References to the following namespaces are needed to compile the code:
[转]How to: Create a Custom Principal Identity的更多相关文章
- [转]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 ...
- 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 ...
- 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 ...
- [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 ...
- [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 ...
- how to create react custom hooks with arguments
how to create react custom hooks with arguments React Hooks & Custom Hooks // reusable custom ho ...
- [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> ...
- Create a custom configSection in web.config or app.config file
config file: <?xml version="1.0" encoding="utf-8" ?> <configuration> ...
- 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 ...
随机推荐
- C/S架构应用程序开发培训笔记
最近为客户组织了一项C/S架构程序的开发培训,讲解C/S应用程序开发中需要注意的点. 我主要是做C/S方面的ERP/CRM程序开发,界面是用Windows Forms技术,有遗漏或错误的地方欢迎批评指 ...
- ★Kali信息收集~ 5.The Harvester:邮箱挖掘器
官网:http://www.edge-security.com 安装:apt-get install theHarvester 运行:终端输入 theharvester (小写) 用法+参数:(返回邮 ...
- Log4Net生成出现未引用错误解决方法
1.步骤一: 2.步骤二: 明明添加了引用怎么还提示找不到命名空间呢.解决这个问题很简单,右键项目选择属性: 3.步骤三:换成.NET Framework 4即可,解决! 4.两个有啥区别? Micr ...
- Python模拟登陆新浪微博
上篇介绍了新浪微博的登陆过程,这节使用Python编写一个模拟登陆的程序.讲解与程序如下: 1.主函数(WeiboMain.py): import urllib2 import cookielib i ...
- 关于android中调用系统拍照,返回图片是旋转90度
转载博客:http://blog.csdn.net/walker02/article/details/8211628 项目开发中遇到的一个问题,对于三星手机在做手机照片选择时出现图片显示不正常,研究后 ...
- Encountered an unexpected error when attempting to resolve tag helper directive '@addTagHelper' with value '"*, Microsoft.AspNet.Mvc.TagHelpers"'
project.json 配置: { "version": "1.0.0-*", "compilationOptions": { " ...
- Event Sourcing Pattern 事件源模式
Use an append-only store to record the full series of events that describe actions taken on data in ...
- 配置IIS的通配符应用程序映射
使用IIS 6架设网站,如果要使用伪静态的功能,可能需要设置“通配符应用程序映射(执行顺序)”. 在Windows Server 2012 r2 的IIS 8中,对应的是添加设置“通配符脚本映射”,参 ...
- 设计模式(十二)享元模式(Flyweight Pattern)
一.引言 在软件开发过程,如果我们需要重复使用某个对象的时候,如果我们重复地使用new创建这个对象的话,这样我们在内存就需要多次地去申请内存空间了,这样可能会出现内存使用越来越多的情况,这样的问题是非 ...
- Java第三方数据库连接池库-DBCP-C3P0-Tomcat内置连接池
连接池原理 数据库连接池的基本思想就是为数据库连接建立一个“缓冲池”.预先在缓冲池中放入一定数量的连接,当需要建立数据库连接时,只需从“缓冲池”中取出一个,使用完毕之后再放回去.我们可以通过设定连接池 ...