protected override IPrincipal GetPrincipal(ServiceSecurityContext
     serviceSecurityContext)
 {
     var userName = serviceSecurityContext.PrimaryIdentity.Name;
     var identity = new GenericIdentity(userName);
     var roles = this.RoleProvider.GetRolesForUser(userName);
     return new GenericPrincipal(identity, roles);
 }
		public void Constructor ()
		{
			ServiceSecurityContext c = new ServiceSecurityContext (new PolicyList (new IAuthorizationPolicy [0]));
			Assert.IsNotNull (c.AuthorizationContext, "#1");
			Assert.AreEqual (0, c.AuthorizationPolicies.Count, "#2");
			// it is somehow treated as anonymous ...
			Assert.IsTrue (c.IsAnonymous, "#3");
			// FIXME: test PrimaryIdentity
		}
 protected override IPrincipal GetPrincipal(ServiceSecurityContext serviceSecurityContext)
 {
     WindowsIdentity identity = serviceSecurityContext.WindowsIdentity;
     if (null == identity)
     {
         identity = WindowsIdentity.GetAnonymous();
     }
     return new WindowsPrincipal(identity);
 }
        protected override bool CheckAccessCore(OperationContext operationContext)
        {
            if (!base.CheckAccessCore(operationContext))
            {
                return false;
            }

            HttpRequestMessageProperty httpDetails = operationContext.RequestContext.RequestMessage.Properties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;
            Uri requestUri = operationContext.RequestContext.RequestMessage.Properties.Via;
            ServiceProvider sp = OAuthServiceProvider.ServiceProvider;
            try
            {
                var auth = sp.ReadProtectedResourceAuthorization(httpDetails, requestUri);
                if (auth != null)
                {
                    var accessToken = Database.DataContext.IssuedTokens.OfType<IssuedAccessToken>().First(token => token.Token == auth.AccessToken);

                    var principal = sp.CreatePrincipal(auth);
                    var policy = new OAuthPrincipalAuthorizationPolicy(principal);
                    var policies = new List<IAuthorizationPolicy> {
                        policy,
                    };

                    var securityContext = new ServiceSecurityContext(policies.AsReadOnly());
                    if (operationContext.IncomingMessageProperties.Security != null)
                    {
                        operationContext.IncomingMessageProperties.Security.ServiceSecurityContext = securityContext;
                    }
                    else
                    {
                        operationContext.IncomingMessageProperties.Security = new SecurityMessageProperty
                        {
                            ServiceSecurityContext = securityContext,
                        };
                    }

                    securityContext.AuthorizationContext.Properties["Identities"] = new List<IIdentity> {
                        principal.Identity,
                    };

                    // Only allow this method call if the access token scope permits it.
                    string[] scopes = accessToken.Scope.Split('|');
                    if (scopes.Contains(operationContext.IncomingMessageHeaders.Action))
                    {
                        return true;
                    }
                }
            }
            catch (ProtocolException /*ex*/)
            {
                ////Logger.Error("Error processing OAuth messages.", ex);
            }

            return false;
        }
		protected override bool CheckAccessCore(OperationContext operationContext) {
			if (!base.CheckAccessCore(operationContext)) {
				return false;
			}

			var httpDetails = operationContext.RequestContext.RequestMessage.Properties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;
			var requestUri = operationContext.RequestContext.RequestMessage.Properties.Via;

			return Task.Run(async delegate {
				ProtocolFaultResponseException exception = null;
				try {
					var principal = await VerifyOAuth2Async(
						httpDetails,
						requestUri,
						operationContext.IncomingMessageHeaders.Action ?? operationContext.IncomingMessageHeaders.To.AbsolutePath);
					if (principal != null) {
						var policy = new OAuthPrincipalAuthorizationPolicy(principal);
						var policies = new List<IAuthorizationPolicy> { policy, };

						var securityContext = new ServiceSecurityContext(policies.AsReadOnly());
						if (operationContext.IncomingMessageProperties.Security != null) {
							operationContext.IncomingMessageProperties.Security.ServiceSecurityContext = securityContext;
						} else {
							operationContext.IncomingMessageProperties.Security = new SecurityMessageProperty {
								ServiceSecurityContext = securityContext,
							};
						}

						securityContext.AuthorizationContext.Properties["Identities"] = new List<IIdentity> { principal.Identity, };

						return true;
					} else {
						return false;
					}
				} catch (ProtocolFaultResponseException ex) {
					Global.Logger.Error("Error processing OAuth messages.", ex);
					exception = ex;
				} catch (ProtocolException ex) {
					Global.Logger.Error("Error processing OAuth messages.", ex);
				}

				if (exception != null) {
					// Return the appropriate unauthorized response to the client.
					var outgoingResponse = await exception.CreateErrorResponseAsync(CancellationToken.None);
					this.Respond(WebOperationContext.Current.OutgoingResponse, outgoingResponse);
				}

				return false;
			}).GetAwaiter().GetResult();
		}
        /// <summary>
        /// This method authorizes the OAuth request. The token is extracted from the header and the scope is checked.
        /// For the demonstration pourposes the scope is the URL of the service. In real world applications the scope would be the functional entity being accessed (eg. the calendar, the fotos etc...).
        /// </summary>
        /// <param name="operationContext"></param>
        /// <returns></returns>
        protected override bool CheckAccessCore(OperationContext operationContext)
        {
            if (!base.CheckAccessCore(operationContext)) {
                return false;
            }

            HttpRequestMessageProperty httpDetails = operationContext.RequestContext.RequestMessage.Properties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;
            Uri requestUri = operationContext.RequestContext.RequestMessage.Properties.Via;
            ServiceProvider sp = Constants.CreateServiceProvider();
            try {
                var auth = sp.ReadProtectedResourceAuthorization(httpDetails, requestUri);
                if (auth != null) {
                    var accessToken = Global.AuthTokens.Single(token => token.Token == auth.AccessToken);

                    var principal = sp.CreatePrincipal(auth);
                    var policy = new OAuthPrincipalAuthorizationPolicy(principal);
                    var policies = new List<IAuthorizationPolicy> {
                    policy,
                };

                    var securityContext = new ServiceSecurityContext(policies.AsReadOnly());
                    if (operationContext.IncomingMessageProperties.Security != null) {
                        operationContext.IncomingMessageProperties.Security.ServiceSecurityContext = securityContext;
                    } else {
                        operationContext.IncomingMessageProperties.Security = new SecurityMessageProperty {
                            ServiceSecurityContext = securityContext,
                        };
                    }

                    securityContext.AuthorizationContext.Properties["Identities"] = new List<IIdentity> {
                    principal.Identity,
                };

                    // Only allow this method call if the access token scope permits it.
                    string[] scopes = accessToken.Scope.Split('|');

                    //extracting the URL which is demanded
                    var action = "http://" + operationContext.IncomingMessageProperties.Via.Authority + operationContext.IncomingMessageProperties.Via.AbsolutePath;

                    //comparing the SCOPE and the demanded URL
                    if (scopes.Contains(action)) {
                        return true;
                    }
                }
            } catch (ProtocolException ex) {
                Debug.WriteLine(ex.Message);
            }

            return false;
        }
Exemple #7
0
 Claim FindClaim(ServiceSecurityContext context)
 {
     Claim result = null;
     foreach (ClaimSet set in context.AuthorizationContext.ClaimSets)
     {
         IEnumerator<Claim> claims = set.FindClaims(ClaimTypes.Name, null).GetEnumerator();
         if (claims.MoveNext())
         {
             result = claims.Current;
             break;
         }
     }
     return result;
 }
        /// <summary>
        /// Find the thumbprint of the clients certificate
        /// </summary>
        /// <param name="operationContext"></param>
        /// <returns></returns>
        public static string GetClientCertificateThumbprint(ServiceSecurityContext securityContext)
        {
            foreach (ClaimSet claimSet in securityContext.AuthorizationContext.ClaimSets)
            {
                foreach (Claim claim in claimSet.FindClaims(ClaimTypes.Thumbprint, Rights.Identity))
                {
                    string tb = BitConverter.ToString((byte[])claim.Resource);
                    tb = tb.Replace("-", "");
                    return tb;
                }
            }

            return string.Empty;
        }
        public static void InitializeSecurityContext(Message request, string username)
        {
            var principal = new GenericPrincipal(new GenericIdentity(username), new string[] { });

            var policies = new List<IAuthorizationPolicy> { new PrincipalAuthorizationPolicy(principal) };
            var securityContext = new ServiceSecurityContext(policies.AsReadOnly());

            if (request.Properties.Security != null)
            {
                request.Properties.Security.ServiceSecurityContext = securityContext;
            }
            else
            {
                request.Properties.Security = new SecurityMessageProperty() { ServiceSecurityContext = securityContext };
            }
        }
		protected override bool CheckAccessCore(OperationContext operationContext) {
			if (!base.CheckAccessCore(operationContext)) {
				return false;
			}

			var httpDetails = operationContext.RequestContext.RequestMessage.Properties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;
			var requestUri = operationContext.RequestContext.RequestMessage.Properties.Via;

			return Task.Run(
				async delegate {
					using (var crypto = OAuthResourceServer.CreateRSA()) {
						var tokenAnalyzer = new SpecialAccessTokenAnalyzer(crypto, crypto);
						var resourceServer = new ResourceServer(tokenAnalyzer);
						ProtocolFaultResponseException exception = null;
						try {
							IPrincipal principal =
								await resourceServer.GetPrincipalAsync(httpDetails, requestUri, CancellationToken.None, operationContext.IncomingMessageHeaders.Action);
							var policy = new OAuthPrincipalAuthorizationPolicy(principal);
							var policies = new List<IAuthorizationPolicy> { policy, };

							var securityContext = new ServiceSecurityContext(policies.AsReadOnly());
							if (operationContext.IncomingMessageProperties.Security != null) {
								operationContext.IncomingMessageProperties.Security.ServiceSecurityContext = securityContext;
							} else {
								operationContext.IncomingMessageProperties.Security = new SecurityMessageProperty {
									ServiceSecurityContext = securityContext,
								};
							}

							securityContext.AuthorizationContext.Properties["Identities"] = new List<IIdentity> { principal.Identity, };

							return true;
						} catch (ProtocolFaultResponseException ex) {
							// Return the appropriate unauthorized response to the client.
							exception = ex;
						} catch (DotNetOpenAuth.Messaging.ProtocolException /* ex*/) {
							////Logger.Error("Error processing OAuth messages.", ex);
						}

						var errorResponse = await exception.CreateErrorResponseAsync(CancellationToken.None);
						await errorResponse.SendAsync();
					}

					return false;
				}).Result;
		}
		protected override bool CheckAccessCore(OperationContext operationContext) {
			if (!base.CheckAccessCore(operationContext)) {
				return false;
			}

			var httpDetails = operationContext.RequestContext.RequestMessage.Properties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;
			var requestUri = operationContext.RequestContext.RequestMessage.Properties.Via;

			using (var crypto = OAuthAuthorizationServer.CreateAsymmetricKeyServiceProvider()) {
				var tokenAnalyzer = new SpecialAccessTokenAnalyzer(crypto, crypto);
				var resourceServer = new ResourceServer(tokenAnalyzer);

				try {
					IPrincipal principal;
					var errorResponse = resourceServer.VerifyAccess(httpDetails, requestUri, out principal);
					if (errorResponse == null) {
						var policy = new OAuthPrincipalAuthorizationPolicy(principal);
						var policies = new List<IAuthorizationPolicy> {
						policy,
					};

						var securityContext = new ServiceSecurityContext(policies.AsReadOnly());
						if (operationContext.IncomingMessageProperties.Security != null) {
							operationContext.IncomingMessageProperties.Security.ServiceSecurityContext = securityContext;
						} else {
							operationContext.IncomingMessageProperties.Security = new SecurityMessageProperty {
								ServiceSecurityContext = securityContext,
							};
						}

						securityContext.AuthorizationContext.Properties["Identities"] = new List<IIdentity> {
						principal.Identity,
					};

						// Only allow this method call if the access token scope permits it.
						if (principal.IsInRole(operationContext.IncomingMessageHeaders.Action)) {
							return true;
						}
					}
				} catch (ProtocolException /*ex*/) {
					////Logger.Error("Error processing OAuth messages.", ex);
				}
			}

			return false;
		}
		protected override bool CheckAccessCore(OperationContext operationContext) {
			if (!base.CheckAccessCore(operationContext)) {
				return false;
			}

			HttpRequestMessageProperty httpDetails = operationContext.RequestContext.RequestMessage.Properties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;
			Uri requestUri = operationContext.RequestContext.RequestMessage.Properties.Via;
			ServiceProvider sp = Constants.CreateServiceProvider();
			((DatabaseTokenManager)sp.TokenManager).OperationContext = operationContext; // artificially preserve this across thread changes.
			return Task.Run(
				async delegate {
					try {
						var auth = await sp.ReadProtectedResourceAuthorizationAsync(httpDetails, requestUri);
						if (auth != null) {
							var accessToken = Global.DataContext.OAuthTokens.Single(token => token.Token == auth.AccessToken);

							var principal = sp.CreatePrincipal(auth);
							var policy = new OAuthPrincipalAuthorizationPolicy(principal);
							var policies = new List<IAuthorizationPolicy> { policy, };

							var securityContext = new ServiceSecurityContext(policies.AsReadOnly());
							if (operationContext.IncomingMessageProperties.Security != null) {
								operationContext.IncomingMessageProperties.Security.ServiceSecurityContext = securityContext;
							} else {
								operationContext.IncomingMessageProperties.Security = new SecurityMessageProperty {
									ServiceSecurityContext = securityContext,
								};
							}

							securityContext.AuthorizationContext.Properties["Identities"] = new List<IIdentity> { principal.Identity, };

							// Only allow this method call if the access token scope permits it.
							string[] scopes = accessToken.Scope.Split('|');
							if (scopes.Contains(operationContext.IncomingMessageHeaders.Action)) {
								return true;
							}
						}
					} catch (ProtocolException ex) {
						Global.Logger.Error("Error processing OAuth messages.", ex);
					}

					return false;
				}).GetAwaiter().GetResult();
		}
		protected override bool CheckAccessCore(OperationContext operationContext) {
			if (!base.CheckAccessCore(operationContext)) {
				return false;
			}

			var httpDetails = operationContext.RequestContext.RequestMessage.Properties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;
			var requestUri = operationContext.RequestContext.RequestMessage.Properties.Via;

			try {
				var principal = VerifyOAuth2(httpDetails, requestUri);
				if (principal != null) {
					var policy = new OAuthPrincipalAuthorizationPolicy(principal);
					var policies = new List<IAuthorizationPolicy> {
						policy,
					};

					var securityContext = new ServiceSecurityContext(policies.AsReadOnly());
					if (operationContext.IncomingMessageProperties.Security != null) {
						operationContext.IncomingMessageProperties.Security.ServiceSecurityContext = securityContext;
					} else {
						operationContext.IncomingMessageProperties.Security = new SecurityMessageProperty {
							ServiceSecurityContext = securityContext,
						};
					}

					securityContext.AuthorizationContext.Properties["Identities"] = new List<IIdentity> {
						principal.Identity,
					};

					// Only allow this method call if the access token scope permits it.
					return principal.IsInRole(operationContext.IncomingMessageHeaders.Action);
				} else {
					return false;
				}
			} catch (ProtocolException ex) {
				Global.Logger.Error("Error processing OAuth messages.", ex);
			}

			return false;
		}
Exemple #14
0
        /// <summary>
        /// This function extracts a Name claim from the provided ServiceSecurityContext and 
        /// returns the associated resource value.
        /// </summary>
        /// <param name="securityContext">The ServiceSecurityContext in which the Name claim should be found</param>
        /// <returns>The resource value associated </returns>
        static string GetNameIdentity(ServiceSecurityContext securityContext)
        {
            // Iterate through each of the claimsets in the AuthorizationContext.
            foreach (ClaimSet claimSet in securityContext.AuthorizationContext.ClaimSets)
            {
                // Find all the Name claims
                IEnumerable<Claim> nameClaims = claimSet.FindClaims(ClaimTypes.Name, Rights.PossessProperty);
                if (nameClaims != null)
                {
                    // Get the first claim 
                    IEnumerator<Claim> enumerator = nameClaims.GetEnumerator();
                    if (enumerator.MoveNext())
                    {
                        // return the resource value.
                        return enumerator.Current.Resource.ToString();
                    }
                }
            }

            // If there are no Name claims in the AuthorizationContext, return the Name of the Anonymous Windows Identity.
            return WindowsIdentity.GetAnonymous().Name;
        }
 public override void ProcessRequest(ref RequestContext requestContext)
 {
     if (requestContext == null || requestContext.RequestMessage == null)
     {
         return;
     }
     Message message = requestContext.RequestMessage;
     if (message.Properties.Security == null)
     {
         // check if there is an IPrincipal in HttpContext.Current
         if (HttpContext.Current != null)
         {
             IPrincipal currentUser = HttpContext.Current.User;
             if (currentUser != null)
             {
                 List<IAuthorizationPolicy> policies = new List<IAuthorizationPolicy>();
                 policies.Add(new PrincipalAuthorizationPolicy(currentUser));
                 ServiceSecurityContext securityContext = new ServiceSecurityContext(policies.AsReadOnly());
                 message.Properties.Security = new SecurityMessageProperty() { ServiceSecurityContext = securityContext };
             }
         }
     }
 }
        IDisposable StartImpersonation2(ref MessageRpc rpc, ServiceSecurityContext securityContext, bool isSecurityContextImpersonationOn)
        {
            IDisposable impersonationContext = null;
            try
            {
                if (isSecurityContextImpersonationOn)
                {
                    if (securityContext == null)
                        throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxSecurityContextPropertyMissingFromRequestMessage)), rpc.Request);

                    WindowsIdentity impersonationToken = securityContext.WindowsIdentity;
                    if (impersonationToken.User != null)
                    {
                        impersonationContext = impersonationToken.Impersonate();
                    }
                    else if (securityContext.PrimaryIdentity is WindowsSidIdentity)
                    {
                        WindowsSidIdentity sidIdentity = (WindowsSidIdentity)securityContext.PrimaryIdentity;
                        if (sidIdentity.SecurityIdentifier.IsWellKnown(WellKnownSidType.AnonymousSid))
                        {
                            impersonationContext = new WindowsAnonymousIdentity().Impersonate();
                        }
                        else
                        {
                            string fullyQualifiedDomainName = GetUpnFromDownlevelName(sidIdentity.Name);
                            using (WindowsIdentity windowsIdentity = new WindowsIdentity(fullyQualifiedDomainName, SecurityUtils.AuthTypeKerberos))
                            {
                                impersonationContext = windowsIdentity.Impersonate();
                            }
                        }
                    }
                    else
                        throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SecurityContextDoesNotAllowImpersonation, rpc.Operation.Action)), rpc.Request);
                }
                else if (AspNetEnvironment.Current.RequiresImpersonation)
                {
                    if (rpc.HostingProperty != null)
                    {
                        impersonationContext = rpc.HostingProperty.Impersonate();
                    }
                }

                SecurityTraceRecordHelper.TraceImpersonationSucceeded(rpc.EventTraceActivity, rpc.Operation);

                // update the impersonation succeed audit
                if (AuditLevel.Success == (this.auditLevel & AuditLevel.Success))
                {
                    SecurityAuditHelper.WriteImpersonationSuccessEvent(this.auditLogLocation,
                        this.suppressAuditFailure, rpc.Operation.Name, SecurityUtils.GetIdentityNamesFromContext(securityContext.AuthorizationContext));
                }
            }
            catch (Exception ex)
            {
                if (Fx.IsFatal(ex))
                {
                    throw;
                }
                SecurityTraceRecordHelper.TraceImpersonationFailed(rpc.EventTraceActivity, rpc.Operation, ex);

                //
                // Update the impersonation failure audit
                // Copy SecurityAuthorizationBehavior.Audit level to here!!!
                //
                if (AuditLevel.Failure == (this.auditLevel & AuditLevel.Failure))
                {
                    try
                    {
                        string primaryIdentity;
                        if (securityContext != null)
                            primaryIdentity = SecurityUtils.GetIdentityNamesFromContext(securityContext.AuthorizationContext);
                        else
                            primaryIdentity = SecurityUtils.AnonymousIdentity.Name;

                        SecurityAuditHelper.WriteImpersonationFailureEvent(this.auditLogLocation,
                            this.suppressAuditFailure, rpc.Operation.Name, primaryIdentity, ex);
                    }
#pragma warning suppress 56500
                    catch (Exception auditException)
                    {
                        if (Fx.IsFatal(auditException))
                            throw;

                        DiagnosticUtility.TraceHandledException(auditException, TraceEventType.Error);
                    }
                }

                throw;
            }

            return impersonationContext;
        }
		public ServiceSecurityContextWrapper(ServiceSecurityContext context)
		{
			this.context = context;
		}
 public ServiceSecurityContextWrapper(ServiceSecurityContext context)
 {
     this.context = context;
 }
        private void InitializeSecurityContext(Message request, IPrincipal principal)
        {
            var policies = new List<IAuthorizationPolicy>();
            policies.Add(new PrincipalAuthorizationPolicy(principal));
            
            var securityContext = new ServiceSecurityContext(policies.AsReadOnly());

            if (request.Properties.Security != null)
            {
                request.Properties.Security.ServiceSecurityContext = securityContext;
            }
            else
            {
                request.Properties.Security = new SecurityMessageProperty() { ServiceSecurityContext = securityContext };
            }
        }
 // Gets IIdentity by ServiceSecurityContext - intended for server-side usage.
 public WcfClientIdentity(ServiceSecurityContext serviceSecurityContext)
 {
     _identity = serviceSecurityContext.PrimaryIdentity;
     _windowsIdentity = serviceSecurityContext.WindowsIdentity;
 }
 static IPrincipal GetCustomPrincipal(ServiceSecurityContext securityContext)
 {
     object customPrincipal;
     if (securityContext.AuthorizationContext.Properties.TryGetValue(SecurityUtils.Principal, out customPrincipal) && customPrincipal is IPrincipal)
         return (IPrincipal)customPrincipal;
     else
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.NoPrincipalSpecifiedInAuthorizationContext)));
 }        
        IPrincipal SetCurrentThreadPrincipal(ServiceSecurityContext securityContext, out bool isThreadPrincipalSet)
        {
            IPrincipal result = null;
            IPrincipal principal = null;

            ClaimsPrincipal claimsPrincipal = OperationContext.Current.ClaimsPrincipal;

            if (this.principalPermissionMode == PrincipalPermissionMode.UseWindowsGroups)
            {
                principal = ( claimsPrincipal is WindowsPrincipal ) ? claimsPrincipal : GetWindowsPrincipal( securityContext );
            }
            else if (this.principalPermissionMode == PrincipalPermissionMode.UseAspNetRoles)
            {
                principal = new RoleProviderPrincipal(this.roleProvider, securityContext);
            }
            else if (this.principalPermissionMode == PrincipalPermissionMode.Custom)
            {
                principal = GetCustomPrincipal(securityContext);
            }
            else if (this.principalPermissionMode == PrincipalPermissionMode.Always)
            {
                principal = claimsPrincipal ?? new ClaimsPrincipal( new ClaimsIdentity() );
            }

            if (principal != null)
            {
                result = Thread.CurrentPrincipal;
                Thread.CurrentPrincipal = principal;
                isThreadPrincipalSet = true;
            }
            else
            {
                isThreadPrincipalSet = false;
            }

            return result;
        }
 public WindowsSidPrincipal(WindowsSidIdentity identity, ServiceSecurityContext securityContext)
 {
     this.identity = identity;
     this.securityContext = securityContext;
 }
 private static IPrincipal GetCustomPrincipal(ServiceSecurityContext securityContext)
 {
     object obj2;
     if (!securityContext.AuthorizationContext.Properties.TryGetValue("Principal", out obj2) || !(obj2 is IPrincipal))
     {
         throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("NoPrincipalSpecifiedInAuthorizationContext")));
     }
     return (IPrincipal) obj2;
 }
 private IDisposable StartImpersonation2(ref MessageRpc rpc, ServiceSecurityContext securityContext, bool isSecurityContextImpersonationOn)
 {
     IDisposable disposable = null;
     try
     {
         if (isSecurityContextImpersonationOn)
         {
             if (securityContext == null)
             {
                 throw TraceUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("SFxSecurityContextPropertyMissingFromRequestMessage")), rpc.Request);
             }
             WindowsIdentity windowsIdentity = securityContext.WindowsIdentity;
             if (windowsIdentity.User == null)
             {
                 if (securityContext.PrimaryIdentity is WindowsSidIdentity)
                 {
                     WindowsSidIdentity primaryIdentity = (WindowsSidIdentity) securityContext.PrimaryIdentity;
                     if (primaryIdentity.SecurityIdentifier.IsWellKnown(WellKnownSidType.AnonymousSid))
                     {
                         disposable = new WindowsAnonymousIdentity().Impersonate();
                         goto Label_0103;
                     }
                     using (WindowsIdentity identity3 = new WindowsIdentity(this.GetUpnFromDownlevelName(primaryIdentity.Name), "Kerberos"))
                     {
                         disposable = identity3.Impersonate();
                         goto Label_0103;
                     }
                 }
                 throw TraceUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("SecurityContextDoesNotAllowImpersonation", new object[] { rpc.Operation.Action })), rpc.Request);
             }
             disposable = windowsIdentity.Impersonate();
         }
         else if (AspNetEnvironment.Current.RequiresImpersonation && (rpc.HostingProperty != null))
         {
             disposable = rpc.HostingProperty.Impersonate();
         }
     Label_0103:
         SecurityTraceRecordHelper.TraceImpersonationSucceeded(rpc.Operation);
         if (AuditLevel.Success == (this.auditLevel & AuditLevel.Success))
         {
             SecurityAuditHelper.WriteImpersonationSuccessEvent(this.auditLogLocation, this.suppressAuditFailure, rpc.Operation.Name, System.ServiceModel.Security.SecurityUtils.GetIdentityNamesFromContext(securityContext.AuthorizationContext));
         }
     }
     catch (Exception exception)
     {
         if (Fx.IsFatal(exception))
         {
             throw;
         }
         SecurityTraceRecordHelper.TraceImpersonationFailed(rpc.Operation, exception);
         if (AuditLevel.Failure == (this.auditLevel & AuditLevel.Failure))
         {
             try
             {
                 string identityNamesFromContext;
                 if (securityContext != null)
                 {
                     identityNamesFromContext = System.ServiceModel.Security.SecurityUtils.GetIdentityNamesFromContext(securityContext.AuthorizationContext);
                 }
                 else
                 {
                     identityNamesFromContext = System.ServiceModel.Security.SecurityUtils.AnonymousIdentity.Name;
                 }
                 SecurityAuditHelper.WriteImpersonationFailureEvent(this.auditLogLocation, this.suppressAuditFailure, rpc.Operation.Name, identityNamesFromContext, exception);
             }
             catch (Exception exception2)
             {
                 if (Fx.IsFatal(exception2))
                 {
                     throw;
                 }
                 System.ServiceModel.DiagnosticUtility.ExceptionUtility.TraceHandledException(exception2, TraceEventType.Error);
             }
         }
         throw;
     }
     return disposable;
 }
 private IPrincipal SetCurrentThreadPrincipal(ServiceSecurityContext securityContext, out bool isThreadPrincipalSet)
 {
     IPrincipal currentPrincipal = null;
     IPrincipal windowsPrincipal = null;
     if (this.principalPermissionMode == PrincipalPermissionMode.UseWindowsGroups)
     {
         windowsPrincipal = this.GetWindowsPrincipal(securityContext);
     }
     else if (this.principalPermissionMode == PrincipalPermissionMode.UseAspNetRoles)
     {
         windowsPrincipal = new RoleProviderPrincipal(this.roleProvider, securityContext);
     }
     else if (this.principalPermissionMode == PrincipalPermissionMode.Custom)
     {
         windowsPrincipal = GetCustomPrincipal(securityContext);
     }
     if (windowsPrincipal != null)
     {
         currentPrincipal = Thread.CurrentPrincipal;
         Thread.CurrentPrincipal = windowsPrincipal;
         isThreadPrincipalSet = true;
         return currentPrincipal;
     }
     isThreadPrincipalSet = false;
     return currentPrincipal;
 }
 private IPrincipal GetWindowsPrincipal(ServiceSecurityContext securityContext)
 {
     WindowsIdentity windowsIdentity = securityContext.WindowsIdentity;
     if (!windowsIdentity.IsAnonymous)
     {
         return new WindowsPrincipal(windowsIdentity);
     }
     WindowsSidIdentity primaryIdentity = securityContext.PrimaryIdentity as WindowsSidIdentity;
     if (primaryIdentity != null)
     {
         return new WindowsSidPrincipal(primaryIdentity, securityContext);
     }
     return AnonymousWindowsPrincipal;
 }
 public SecurityMessageProperty()
 {
     _securityContext = ServiceSecurityContext.Anonymous;
 }
        internal MessageRpc(RequestContext requestContext, Message request, DispatchOperationRuntime operation,
            ServiceChannel channel, ServiceHostBase host, ChannelHandler channelHandler, bool cleanThread,
            OperationContext operationContext, InstanceContext instanceContext, EventTraceActivity eventTraceActivity)
        {
            Fx.Assert((operationContext != null), "System.ServiceModel.Dispatcher.MessageRpc.MessageRpc(), operationContext == null");
            Fx.Assert(channelHandler != null, "System.ServiceModel.Dispatcher.MessageRpc.MessageRpc(), channelHandler == null");

            this.Activity = null;
            this.EventTraceActivity = eventTraceActivity;            
            this.AsyncResult = null;
            this.CanSendReply = true;
            this.Channel = channel;
            this.channelHandler = channelHandler;
            this.Correlation = EmptyArray.Allocate(operation.Parent.CorrelationCount);
            this.CorrelationCallback = null;
            this.DidDeserializeRequestBody = false;
            this.TransactionMessageProperty = null;
            this.TransactedBatchContext = null;
            this.Error = null;
            this.ErrorProcessor = null;
            this.FaultInfo = new ErrorHandlerFaultInfo(request.Version.Addressing.DefaultFaultAction);
            this.HasSecurityContext = false;
            this.Host = host;
            this.Instance = null;
            this.MessageRpcOwnsInstanceContextThrottle = false;
            this.NextProcessor = null;
            this.NotUnderstoodHeaders = null;
            this.Operation = operation;
            this.OperationContext = operationContext;
            this.paused = false;
            this.ParametersDisposed = false;
            this.ReceiveContext = null;
            this.Request = request;
            this.RequestContext = requestContext;
            this.RequestContextThrewOnReply = false;
            this.SuccessfullySendReply = false;
            this.RequestVersion = request.Version;
            this.Reply = null;
            this.ReplyTimeoutHelper = new TimeoutHelper();
            this.SecurityContext = null;
            this.InstanceContext = instanceContext;
            this.SuccessfullyBoundInstance = false;
            this.SuccessfullyIncrementedActivity = false;
            this.SuccessfullyLockedInstance = false;
            this.switchedThreads = !cleanThread;
            this.transaction = null;
            this.InputParameters = null;
            this.OutputParameters = null;
            this.ReturnParameter = null;
            this.isInstanceContextSingleton = InstanceContextProviderBase.IsProviderSingleton(this.Channel.DispatchRuntime.InstanceContextProvider);
            this.invokeContinueGate = null;

            if (!operation.IsOneWay && !operation.Parent.ManualAddressing)
            {
                this.RequestID = request.Headers.MessageId;
                this.ReplyToInfo = new RequestReplyCorrelator.ReplyToInfo(request);
            }
            else
            {
                this.RequestID = null;
                this.ReplyToInfo = new RequestReplyCorrelator.ReplyToInfo();
            }

            this.HostingProperty = AspNetEnvironment.Current.GetHostingProperty(request, true);

            if (DiagnosticUtility.ShouldUseActivity)
            {
                this.Activity = TraceUtility.ExtractActivity(this.Request);
            }

            if (DiagnosticUtility.ShouldUseActivity || TraceUtility.ShouldPropagateActivity)
            {
                this.ResponseActivityId = ActivityIdHeader.ExtractActivityId(this.Request);
            }
            else
            {
                this.ResponseActivityId = Guid.Empty;
            }

            this.InvokeNotification = new MessageRpcInvokeNotification(this.Activity, this.channelHandler);

            if (this.EventTraceActivity == null && FxTrace.Trace.IsEnd2EndActivityTracingEnabled)
            {
                if (this.Request != null)
                {
                    this.EventTraceActivity = EventTraceActivityHelper.TryExtractActivity(this.Request, true);
                }
            }
        }
        protected override bool CheckAccessCore(OperationContext operationContext)
        {
            if (!base.CheckAccessCore(operationContext))
            {
                return false;
            }

            HttpRequestMessageProperty httpDetails = operationContext.RequestContext.RequestMessage.Properties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;
            Uri requestUri = operationContext.RequestContext.RequestMessage.Properties.Via;
            Uri httpUriBeforeRewrite = HttpContext.Current.Request.Url;

            if (requestUri.AbsoluteUri!=httpUriBeforeRewrite.AbsoluteUri && httpDetails.Headers["Host"] != null)
            {
                string urlBeforeOverwrite = httpUriBeforeRewrite.AbsoluteUri.Replace(httpUriBeforeRewrite.Authority, httpDetails.Headers["Host"]);
                requestUri = new Uri(urlBeforeOverwrite);
            }

            ServiceProvider sp = Constants.CreateServiceProvider();
            try
            {
                var auth = sp.ReadProtectedResourceAuthorization(httpDetails, requestUri);
                if (auth != null)
                {
                    var accessToken = OAuthServices.GetAccessToken(auth.AccessToken);//  Global.AuthTokens.Single(token => token.Token == auth.AccessToken);

                    var principal = sp.CreatePrincipal(auth);
                    var policy = new OAuthPrincipalAuthorizationPolicy(principal);
                    var policies = new List<IAuthorizationPolicy> {
                        policy,
                    };

                    var securityContext = new ServiceSecurityContext(policies.AsReadOnly());
                    if (operationContext.IncomingMessageProperties.Security != null)
                    {
                        operationContext.IncomingMessageProperties.Security.ServiceSecurityContext = securityContext;
                    }
                    else
                    {
                        operationContext.IncomingMessageProperties.Security = new SecurityMessageProperty
                        {
                            ServiceSecurityContext = securityContext,
                        };
                    }

                    securityContext.AuthorizationContext.Properties["Identities"] = new List<IIdentity> {
                        principal.Identity,
                    };

                    // Only allow this method call if the access token scope permits it.
                    string[] scopes = accessToken.Scope.Split('|');

                    //originally this was ment to be used: operationContext.IncomingMessageHeaders.Action
                    //var action = operationContext.Host.BaseAddresses + operationContext.IncomingMessageProperties.Via.AbsolutePath;
                    //var action = "http://" + operationContext.IncomingMessageProperties.Via.Authority + operationContext.IncomingMessageProperties.Via.AbsolutePath;

                    //cut the url to the first "?", after the "?" there is bunch of OAuth stuff
                    //this way we can see whether the scope connected with this token is equal to the demanded service
                    var action = requestUri.AbsoluteUri.Substring(0, requestUri.AbsoluteUri.IndexOf("?"));

                    if (scopes.Contains(action))
                    {
                        return true;
                    }
                }
            }
            catch (ProtocolException ex)
            {
                log.Error(String.Format("Error in the communication protocol. {0}",ex.Message));
            }
            catch (Exception ex)
            {
                log.Error(String.Format("Unexpected error: {0}\n Accesing the url: {1}, which was before server rewrite: {2}",ex.Message,requestUri,httpUriBeforeRewrite));
            }

            return false;
        }
        IPrincipal GetWindowsPrincipal(ServiceSecurityContext securityContext)
        {
            WindowsIdentity wid = securityContext.WindowsIdentity;
            if (!wid.IsAnonymous)
                return new WindowsPrincipal(wid);

            WindowsSidIdentity wsid = securityContext.PrimaryIdentity as WindowsSidIdentity;
            if (wsid != null)
                return new WindowsSidPrincipal(wsid, securityContext);

            return AnonymousWindowsPrincipal;
        }