[转]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

C#

VB

Copy

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:

时间: 2024-10-19 15:29:44

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

[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 HTML forms. Form validators not only help you to get better quality data but they also guide the user through your form. Angular comes with a series of

[Javascript] Create a Custom Iterator for Any Array

Using Symbol.iterator, you can create custom iterators that can be used inside of for loops and Array spreads. This lesson walks you through creating a function to create iterators from arrays that you pass into the function. const abcs = ["A",

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

config file: <?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="FileDepend" type="TestConsole.FileDepend,TestConsole"/> </configSections> <FileDe

Part 20 Create custom service in AngularJS

Whenever the case changes from lower to upper, a single space character should be inserted. This means the string "AngularVideoTutorial" should be converted to"Angular Video Tutorial". Let us first see, how to achieve this without usin

[转]How to Create Custom Filters in AngularJs

本文转自:http://www.codeproject.com/Tips/829025/How-to-Create-Custom-Filters-in-AngularJs Introduction Filter in Angular JS is a way that will help you to represent your data in View in a certain format. There are many inbuilt filters provided by Angular

【ASP.NET Identity系列教程(三)】Identity高级技术

注:本文是[ASP.NET Identity系列教程]的第三篇.本系列教程详细.完整.深入地介绍了微软的ASP.NET Identity技术,描述了如何运用ASP.NET Identity实现应用程序的用户管理,以及实现应用程序的认证与授权等相关技术,译者希望本系列教程能成为掌握ASP.NET Identity技术的一份完整而有价值的资料.读者若是能够按照文章的描述,一边阅读.一边实践.一边理解,定能有意想不到的巨大收获!希望本系列博文能够得到广大园友的高度推荐. 15 Advanced ASP

Asp.Net Identity学习笔记+MVC5默认项目解析_授权&Claim

Identity学习笔记 Asp.Net Identity学习笔记+MVC5默认项目解析_基础用法 Asp.Net Identity学习笔记+MVC5默认项目解析_授权&Claim Identity学习笔记授权以角色授权IdentityRoleRoleManager基于声明的(Claims)IPrincipalIIdentityCalimsIdentityClaim用户登入用户授权其他细节Claim Type命名空间 授权 最常用的授权就是给Controller或Action打上[Authori

Configuring Autofac to work with the ASP.NET Identity Framework in MVC 5

https://developingsoftware.com/configuring-autofac-to-work-with-the-aspnet-identity-framework-in-mvc-5 Configuring Autofac to work with the ASP.NET Identity Framework in MVC 5 By Tony Mackay  02 February 2015 This post will show you how to modify the

【ASP.NET Identity教程】ASP.NET Identity入门

注:本文是[ASP.NET Identity系列教程]的第一篇.本系列教程详细.完整.深入地介绍了微软的ASP.NET Identity技术,描述了如何运用ASP.NET Identity实现应用程序的用户管理,以及实现应用程序的认证与授权等相关技术,译者希望本系列教程成为掌握ASP.NET Identity技术的一份完整而有价值的资料,希望得到广大园友的高度推荐. 13 Getting Started with Identity 13 Identity入门 Identity is a new