private ServiceSecurityContext GetAndCacheSecurityContext(MessageRpc rpc)
        {
            ServiceSecurityContext securityContext = rpc.SecurityContext;

            if (!rpc.HasSecurityContext)
            {
                SecurityMessageProperty securityContextProperty = rpc.Request.Properties.Security;
                if (securityContextProperty == null)
                {
                    securityContext = null; // SecurityContext.Anonymous
                }
                else
                {
                    securityContext = securityContextProperty.ServiceSecurityContext;
                    if (securityContext == null)
                    {
                        throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SecurityContextMissing, rpc.Operation.Name)), rpc.Request);
                    }
                }

                rpc.SecurityContext    = securityContext;
                rpc.HasSecurityContext = true;
            }

            return(securityContext);
        }
Example #2
0
        // Returns the username and certificate subject name provided by the client.
        void GetCallerIdentities(ServiceSecurityContext callerSecurityContext, out string userName, out string certificateSubjectName)
        {
            userName = null;
            certificateSubjectName = null;

            // Look in all the claimsets in the authorization context.
            foreach (ClaimSet claimSet in callerSecurityContext.AuthorizationContext.ClaimSets)
            {
                // Try to find a Upn claim. This has been generated from the windows username.
                string tmpName;
                if (TryGetClaimValue <string>(claimSet, ClaimTypes.Upn, out tmpName))
                {
                    userName = tmpName;
                }
                else
                {
                    // Try to find an X500DisinguishedName claim. This has been generated from the client certificate.
                    X500DistinguishedName tmpDistinguishedName;
                    if (TryGetClaimValue <X500DistinguishedName>(claimSet, ClaimTypes.X500DistinguishedName, out tmpDistinguishedName))
                    {
                        certificateSubjectName = tmpDistinguishedName.Name;
                    }
                }
            }
        }
        //When we need to pass the current user to the business logic
        private string GetServiceUserEmail()
        {
            OperationContext       oc  = OperationContext.Current;
            ServiceSecurityContext ssc = oc.ServiceSecurityContext;

            return(ssc.PrimaryIdentity.Name);
        }
        protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            IPrincipal originalPrincipal = Thread.CurrentPrincipal;

            // here you can see the requestor's identity via the request message
            // convert the Generic Identity to some IPrincipal object, and set it in the request's property
            // later the authorization filter will use the role information to authorize request.
            SecurityMessageProperty property = request.GetSecurityMessageProperty();

            if (property != null)
            {
                ServiceSecurityContext context = property.ServiceSecurityContext;

                if (context.PrimaryIdentity.Name == "username")
                {
                    Thread.CurrentPrincipal = new GenericPrincipal(context.PrimaryIdentity, new string[] { "Administrators" });
                }
            }

            try
            {
                return(await base.SendAsync(request, cancellationToken));
            }
            finally
            {
                Thread.CurrentPrincipal = originalPrincipal;
            }
        }
        IPrincipal SetCurrentThreadPrincipal(ServiceSecurityContext securityContext, out bool isThreadPrincipalSet)
        {
            IPrincipal result    = null;
            IPrincipal principal = null;

            ClaimsPrincipal claimsPrincipal = OperationContext.Current.ClaimsPrincipal;

            if (principalPermissionMode == PrincipalPermissionMode.UseWindowsGroups)
            {
                principal = (claimsPrincipal is WindowsPrincipal) ? claimsPrincipal : GetWindowsPrincipal(securityContext);
            }
            else if (principalPermissionMode == PrincipalPermissionMode.Custom)
            {
                principal = GetCustomPrincipal(securityContext);
            }
            else if (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);
        }
Example #6
0
        public void InitiateHandShake()
        {
            IPeerNeighbor neighbor = host;
            Message       reply    = null;

            Fx.Assert(host != null, "Cannot initiate security handshake without a host!");

            //send the RST message.
            using (OperationContextScope scope = new OperationContextScope(new OperationContext((ServiceHostBase)null)))
            {
                PeerHashToken token   = this.securityManager.GetSelfToken();
                Message       request = Message.CreateMessage(MessageVersion.Soap12WSAddressing10, TrustFeb2005Strings.RequestSecurityToken, new PeerRequestSecurityToken(token));
                bool          fatal   = false;
                try
                {
                    reply = neighbor.RequestSecurityToken(request);

                    if (!(reply != null))
                    {
                        throw Fx.AssertAndThrow("SecurityHandshake return empty message!");
                    }
                    ProcessRstr(neighbor, reply, PeerSecurityManager.FindClaim(ServiceSecurityContext.Current));
                }
                catch (Exception e)
                {
                    if (Fx.IsFatal(e))
                    {
                        fatal = true;
                        throw;
                    }
                    DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
                    this.state = PeerAuthState.Failed;
                    if (DiagnosticUtility.ShouldTraceError)
                    {
                        ServiceSecurityContext context = ServiceSecurityContext.Current;
                        ClaimSet claimSet = null;
                        if (context != null && context.AuthorizationContext != null && context.AuthorizationContext.ClaimSets != null && context.AuthorizationContext.ClaimSets.Count > 0)
                        {
                            claimSet = context.AuthorizationContext.ClaimSets[0];
                        }
                        PeerAuthenticationFailureTraceRecord record = new PeerAuthenticationFailureTraceRecord(
                            meshId,
                            neighbor.ListenAddress.EndpointAddress.ToString(),
                            claimSet,
                            e);
                        TraceUtility.TraceEvent(TraceEventType.Error,
                                                TraceCode.PeerNodeAuthenticationFailure, SR.GetString(SR.TraceCodePeerNodeAuthenticationFailure),
                                                record, this, null);
                    }
                    neighbor.Abort(PeerCloseReason.AuthenticationFailure, PeerCloseInitiator.LocalNode);
                }
                finally
                {
                    if (!fatal)
                    {
                        request.Close();
                    }
                }
            }
        }
Example #7
0
        static void GetOrCreateSecureMessageAtClient(Message msg)
        {
            foreach (object o in msg.Properties)
            {
                if (o is SecurityMessageProperty)
                {
                    Assert.Fail("The input msg should not contain SecurityMessageProperty yet.");
                }
            }
            SecurityMessageProperty p = SecurityMessageProperty.GetOrCreate(msg);

            Assert.AreEqual(null, p.InitiatorToken, "#1");
            Assert.AreEqual(null, p.RecipientToken, "#2");
            Assert.IsNull(p.ProtectionToken, "#3");
            Assert.IsNull(p.TransportToken, "#4");
            Assert.IsNull(p.ExternalAuthorizationPolicies, "#5");
//			Assert.AreEqual (0, p.ExternalAuthorizationPolicies.Count, "#5");
            Assert.IsFalse(p.HasIncomingSupportingTokens, "#6");
            Assert.IsNotNull(p.IncomingSupportingTokens, "#6-2");
            Assert.AreEqual("_", p.SenderIdPrefix, "#6-3");
            ServiceSecurityContext ssc = p.ServiceSecurityContext;

            Assert.IsNotNull(ssc, "#7");

            // not sure if it is worthy of testing though ...
            GenericIdentity identity = ssc.PrimaryIdentity as GenericIdentity;

            Assert.IsNotNull(identity, "#8-1");
            Assert.AreEqual("", identity.Name, "#8-2");
            Assert.AreEqual("", identity.AuthenticationType, "#8-3");

            Assert.AreEqual(0, ssc.AuthorizationPolicies.Count, "#9");
            Assert.IsTrue(ssc.IsAnonymous, "#10");
        }
Example #8
0
        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);
        }
        protected virtual void CheckClientAuthorization()
        {
            ServiceSecurityContext serviceSecurityContext = ServiceSecurityContext.Current;
            bool flag = false;

            if (serviceSecurityContext == null)
            {
                ExTraceGlobals.DiagnosticsAggregationTracer.TraceError((long)this.GetHashCode(), "ServiceSecurityContext is null");
            }
            else if (serviceSecurityContext.WindowsIdentity == null)
            {
                ExTraceGlobals.DiagnosticsAggregationTracer.TraceError((long)this.GetHashCode(), "ServiceSecurityContext WindowsIdentity is null");
            }
            else if (!this.HasReadAccessInAd(serviceSecurityContext))
            {
                ExTraceGlobals.DiagnosticsAggregationTracer.TraceError <string>((long)this.GetHashCode(), "User {0} does not have Read access in AD", ServiceSecurityContext.Current.WindowsIdentity.Name);
            }
            else
            {
                flag = true;
            }
            if (!flag)
            {
                string empty = string.Empty;
                if (serviceSecurityContext != null && serviceSecurityContext.WindowsIdentity != null)
                {
                    string name = serviceSecurityContext.WindowsIdentity.Name;
                }
                throw DiagnosticsAggregationServiceImpl.NewFault(ErrorCode.AccessDenied, "Access is Denied");
            }
        }
Example #10
0
        public bool Authenticate(ServiceSecurityContext context, byte[] message)
        {
            Claim claim = null;

            if (context == null)
            {
                return(authenticationMode == PeerAuthenticationMode.None);
            }
            if (authenticationMode == PeerAuthenticationMode.Password)
            {
                if (!(context != null))
                {
                    throw Fx.AssertAndThrow("No SecurityContext attached in security mode!");
                }
                claim = FindClaim(context);
                return(PeerSecurityHelpers.Authenticate(claim, this.credManager.Password, message));
            }
            else
            {
                if (message != null)
                {
                    PeerExceptionHelper.ThrowInvalidOperation_UnexpectedSecurityTokensDuringHandshake();
                }
                return(true);
            }
        }
        public static string GetClientCredentials()
        {
            StringBuilder creds = new StringBuilder();

            IPrincipal             cp             = Thread.CurrentPrincipal;
            ServiceSecurityContext currentContext = ServiceSecurityContext.Current;

            if (currentContext == null)
            {
                creds.AppendFormat("Token identity: {0}" +
                                   "Principal identity: {1} with {2} Security context is null",
                                   WindowsIdentity.GetCurrent().Name + Environment.NewLine,
                                   cp.Identity.GetType(),
                                   (cp.Identity.Name == "" ? "Blank identity" : cp.Identity.Name + Environment.NewLine))
                ;
            }
            else
            {
                creds.AppendFormat("Token identity: {0}" +
                                   "Principal identity: {1} with {2} Security context is null" + Environment.NewLine +
                                   "Security context primary identity: {3} with {4}" +
                                   "Security context Windows identity: {5} with {6}",
                                   WindowsIdentity.GetCurrent().Name + Environment.NewLine,
                                   cp.Identity.GetType(),
                                   (cp.Identity.Name == "" ? "Blank identity" : cp.Identity.Name + Environment.NewLine),
                                   currentContext.PrimaryIdentity.GetType(),
                                   (currentContext.PrimaryIdentity.Name == "" ? "Blank identity" : currentContext.PrimaryIdentity.Name) + Environment.NewLine,
                                   currentContext.WindowsIdentity.GetType(),
                                   (currentContext.WindowsIdentity.Name == "" ? "Blank identity" : currentContext.WindowsIdentity.Name)
                                   );
            }
            return(creds.ToString());
        }
        void SetClaimsPrincipalToOperationContext(MessageRpc rpc)
        {
            ServiceSecurityContext securityContext = rpc.SecurityContext;

            if (!rpc.HasSecurityContext)
            {
                SecurityMessageProperty securityContextProperty = rpc.Request.Properties.Security;
                if (securityContextProperty != null)
                {
                    securityContext = securityContextProperty.ServiceSecurityContext;
                }
            }

            if (securityContext != null)
            {
                object principal;
                if (securityContext.AuthorizationContext.Properties.TryGetValue(AuthorizationPolicy.ClaimsPrincipalKey, out principal))
                {
                    ClaimsPrincipal claimsPrincipal = principal as ClaimsPrincipal;
                    if (claimsPrincipal != null)
                    {
                        //
                        // Always set ClaimsPrincipal to OperationContext.Current if identityModel pipeline is used.
                        //
                        OperationContext.Current.ClaimsPrincipal = claimsPrincipal;
                    }
                    else
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.NoPrincipalSpecifiedInAuthorizationContext)));
                    }
                }
            }
        }
Example #13
0
        public void GetOrCreateNonSecureMessage()
        {
            Message m = Message.CreateMessage(MessageVersion.Default, "urn:myaction");
            SecurityMessageProperty p =
                SecurityMessageProperty.GetOrCreate(m);

            Assert.IsNull(p.InitiatorToken, "#1");
            Assert.IsNull(p.RecipientToken, "#2");
            Assert.IsNull(p.ProtectionToken, "#3");
            Assert.IsNull(p.TransportToken, "#4");
            Assert.IsNull(p.ExternalAuthorizationPolicies, "#5");
//			Assert.AreEqual (0, p.ExternalAuthorizationPolicies.Count, "#5");
            Assert.IsFalse(p.HasIncomingSupportingTokens, "#6");
            Assert.IsNotNull(p.IncomingSupportingTokens, "#6-2");
            Assert.AreEqual("_", p.SenderIdPrefix, "#6-3");
            ServiceSecurityContext ssc = p.ServiceSecurityContext;

            Assert.IsNotNull(ssc, "#7");

            // not sure if it is worthy of testing though ...
            GenericIdentity identity = ssc.PrimaryIdentity as GenericIdentity;

            Assert.IsNotNull(identity, "#8-1");
            Assert.AreEqual("", identity.Name, "#8-2");
            Assert.AreEqual("", identity.AuthenticationType, "#8-3");

            Assert.AreEqual(0, ssc.AuthorizationPolicies.Count, "#9");
            Assert.IsTrue(ssc.IsAnonymous, "#10");
        }
 private static SecurityMessageProperty CreateSecurityProperty(X509Certificate2 certificate)
 {
     AuthorizationContext authorizationContext = new X509AuthorizationContext(certificate);
     ServiceSecurityContext securityContext = new ServiceSecurityContext(authorizationContext);
     SecurityMessageProperty securityProperty = new SecurityMessageProperty();
     securityProperty.ServiceSecurityContext = securityContext;
     return securityProperty;
 }
Example #15
0
        protected override IPrincipal GetPrincipal(ServiceSecurityContext context)
        {
            var userName = context.PrimaryIdentity.Name;
            var identity = new GenericIdentity(userName);
            var roles    = RolePrivider.GetRolesForUser(userName);

            return(new GenericPrincipal(identity, roles));
        }
Example #16
0
        void OnFailed(IPeerNeighbor neighbor)
        {
            lock (ThisLock)
            {
                this.state = PeerAuthState.Failed;
                this.timer.Cancel();
                this.host = null;
            }
            if (DiagnosticUtility.ShouldTraceError)
            {
                PeerAuthenticationFailureTraceRecord record = null;
                String          remoteUri     = "";
                PeerNodeAddress remoteAddress = neighbor.ListenAddress;
                if (remoteAddress != null)
                {
                    remoteUri = remoteAddress.EndpointAddress.ToString();
                }
                OperationContext opContext = OperationContext.Current;
                if (opContext != null)
                {
                    remoteUri = opContext.IncomingMessageProperties.Via.ToString();
                    ServiceSecurityContext secContext = opContext.ServiceSecurityContext;
                    if (secContext != null)
                    {
                        record = new PeerAuthenticationFailureTraceRecord(
                            meshId,
                            remoteUri,
                            secContext.AuthorizationContext.ClaimSets[0], null);

                        if (DiagnosticUtility.ShouldTraceError)
                        {
                            TraceUtility.TraceEvent(
                                TraceEventType.Error,
                                TraceCode.PeerNodeAuthenticationFailure,
                                SR.GetString(SR.TraceCodePeerNodeAuthenticationFailure),
                                record,
                                this,
                                null);
                        }
                    }
                }
                else
                {
                    record = new PeerAuthenticationFailureTraceRecord(meshId, remoteUri);
                    if (DiagnosticUtility.ShouldTraceError)
                    {
                        TraceUtility.TraceEvent(TraceEventType.Error,
                                                TraceCode.PeerNodeAuthenticationTimeout,
                                                SR.GetString(SR.TraceCodePeerNodeAuthenticationTimeout),
                                                record,
                                                this,
                                                null);
                    }
                }
            }
            neighbor.Abort(PeerCloseReason.AuthenticationFailure, PeerCloseInitiator.LocalNode);
        }
        /// <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 = GlobalApplication.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);
        }
        public void Anonymous()
        {
            ServiceSecurityContext c = ServiceSecurityContext.Anonymous;

            Assert.IsNotNull(c.AuthorizationContext, "#1");
            Assert.AreEqual(0, c.AuthorizationPolicies.Count, "#2");
            Assert.IsTrue(c.IsAnonymous, "#3");
            // FIXME: test PrimaryIdentity
        }
Example #19
0
        public static void SetupThreadActiveProperty(ServiceSecurityContext Context)
        {
            //The ServiceSecurityContext contains the UserName at this point so an active property is not required
            //the property can be set directly
            //Setup Active Properties
            string Username = new CurrentUserHelper(Context).ToString();

            log4net.LogicalThreadContext.Properties["username"] = Username;
        }
Example #20
0
        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.ErrorException("Error processing OAuth messages.", ex);
                }

                return false;
            }).GetAwaiter().GetResult());
        }
Example #21
0
        /// <summary>
        /// Throws a System.Security.SecurityException at run time if the security requirement is not met.
        /// </summary>
        public void Demand()
        {
            // It's always possible for a sloppy (or malicious) programmer to call a method that demands claims.  If that method has not set up a security context
            // properly, then we won't be able to satisify the request for claims.
            ServiceSecurityContext serviceSecurityContext = ServiceSecurityContext.Current;

            if (serviceSecurityContext == null)
            {
                throw new SecurityException(Properties.Resources.InvalidSecurityContextError);
            }

            // If the premissions require the user to be authenticated, then throw a security exception.
            if (this.isAuthenticated && !ServiceSecurityContext.Current.PrimaryIdentity.IsAuthenticated)
            {
                throw new SecurityException(Properties.Resources.PrincipalNotAuthenticatedError);
            }

            // The authorization context has the claims that were established for this thread.
            AuthorizationContext authorizationContext = serviceSecurityContext.AuthorizationContext;

            // If claims have been asserted for this method, then we're going to check whether the available claims meet the criteria of the claims requested by the
            // called method.
            if (!this.isUnrestricted)
            {
                // There are several sets of claims that the current security context possesses.  We are going to check each one to see if the issuer is the same
                // and, if it is, we'll then check to see if all of the claims required by the method match any of the claims offered by the security context.  If
                // the security context possesses all the required claims, then the method can be called.
                Boolean areClaimsSatisfied = false;
                foreach (ClaimSet claimSet in authorizationContext.ClaimSets)
                {
                    if (this.requiredClaims.Issuer == claimSet.Issuer)
                    {
                        Boolean isMatchingSet = true;
                        foreach (Claim claim in this.requiredClaims)
                        {
                            if (!claimSet.ContainsClaim(claim))
                            {
                                isMatchingSet = false;
                                break;
                            }
                        }
                        if (isMatchingSet)
                        {
                            areClaimsSatisfied = true;
                            break;
                        }
                    }
                }

                // An exception is thrown if we can't find the required claims in the current security context.
                if (!areClaimsSatisfied)
                {
                    throw new FaultException <InsufficientClaimsFault>(new InsufficientClaimsFault(Properties.Resources.AccessDeniedInsufficientClaimsError));
                }
            }
        }
Example #22
0
        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);
        }
        internal virtual IAuthenticationInfo Authenticate(OperationContext operationContext)
        {
            ServiceSecurityContext serviceSecurityContext = operationContext.ServiceSecurityContext;

            if (serviceSecurityContext == null || serviceSecurityContext.IsAnonymous)
            {
                return(null);
            }
            return(new AuthenticationInfo(serviceSecurityContext.WindowsIdentity, serviceSecurityContext.PrimaryIdentity.Name));
        }
Example #24
0
        protected override IPrincipal GetPrincipal(ServiceSecurityContext context)
        {
            WindowsIdentity windowsIdentity = context.WindowsIdentity;

            if (null == windowsIdentity)
            {
                windowsIdentity = WindowsIdentity.GetAnonymous();
            }
            return(new WindowsPrincipal(windowsIdentity));
        }
Example #25
0
        public string Echo(string message)
        {
            Console.WriteLine("Echo called with: " + message);

            Console.WriteLine("The client is hitting endpoint: {0}", OperationContext.Current.IncomingMessageProperties.Via.AbsoluteUri);
            ServiceSecurityContext securityContext = OperationContext.Current.ServiceSecurityContext;

            Console.WriteLine("The client is: {0}", securityContext.IsAnonymous ? "anonymous" : securityContext.PrimaryIdentity.Name);
            return(message);
        }
        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 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);
        }
Example #28
0
        public getTimeResponse GetTime(GetTimeRequest IncomingMessage)
        {
            ServiceSecurityContext ssc = OperationContext.Current.ServiceSecurityContext;

            Console.WriteLine(ssc.PrimaryIdentity.Name + Environment.NewLine + ssc.PrimaryIdentity.AuthenticationType);
            getTimeResponse ret = new getTimeResponse();

            ret.getTimeResult          = new ReturnData();
            ret.getTimeResult.Greeting = "hi";
            return(ret);
        }
        // Returns the most privileged role this user belongs to
        static internal authorizationRole GetCurrentUserMostPrivilegedRole()
        {
            try
            {
                ServiceSecurityContext context         = OperationContext.Current.ServiceSecurityContext;
                WindowsIdentity        windowsIdentity = context.WindowsIdentity;
                var principal = new WindowsPrincipal(windowsIdentity);

                // Extract domain + role names to check for access privilege
                // The first item before '\' is the domain name - extract it
                string[] usernameSplit = windowsIdentity.Name.Split('\\');
                // Apend role names after the domain name
                string wcscmadminRole    = usernameSplit[0] + "\\" + "WcsCmAdmin";
                string wcscmoperatorRole = usernameSplit[0] + "\\" + "WcsCmOperator";
                string wcscmuserRole     = usernameSplit[0] + "\\" + "WcsCmUser";

                if (principal.IsInRole("Administrators"))
                {
                    Tracer.WriteUserLog("User({0}) belongs to Administrators group and hence belongs to WcsCmAdmin privilege role", windowsIdentity.Name);
                    return(authorizationRole.WcsCmAdmin);
                }

                // Is user in local WcsCmAdmin group or domain's WcsCmAdmin group?
                if (principal.IsInRole("WcsCmAdmin") || principal.IsInRole(wcscmadminRole))
                {
                    Tracer.WriteUserLog("User({0}) belongs to WcsCmAdmin privilege role", windowsIdentity.Name);
                    return(authorizationRole.WcsCmAdmin);
                }

                // Is user in local WcsCmOperator group or domain's WcsCmOperator group?
                if (principal.IsInRole("WcsCmOperator") || principal.IsInRole(wcscmoperatorRole))
                {
                    Tracer.WriteUserLog("User({0}) belongs to WcsCmOperator privilege role", windowsIdentity.Name);
                    return(authorizationRole.WcsCmOperator);
                }

                // Is user in local WcsCmUser group or domain's WcsCmUser group?
                if (principal.IsInRole("WcsCmUser") || principal.IsInRole(wcscmuserRole))
                {
                    Tracer.WriteUserLog("User({0}) belongs to WcsCmUser privilege role", windowsIdentity.Name);
                    return(authorizationRole.WcsCmUser);
                }
                // User not mapped to any standard roles
                Tracer.WriteWarning("GetCurrentUserMostPrivilegedRole: Current user({0}) not mapped to the standard WCS roles", windowsIdentity.Name);
                Tracer.WriteUserLog("GetCurrentUserMostPrivilegedRole: Current user({0}) not mapped to the standard WCS roles", windowsIdentity.Name);
            }
            catch (Exception ex)
            {
                Tracer.WriteError("User Authorization check exception  was thrown: " + ex);
            }

            // Return as unauthorized if the user do not belong to any of the category or if there is an exception
            return(authorizationRole.WcsCmUnAuthorized);
        }
 private static IPrincipal GetCustomPrincipal(ServiceSecurityContext securityContext)
 {
     if (securityContext.AuthorizationContext.Properties.TryGetValue(SecurityUtils.Principal, out object obj) && obj is IPrincipal customPrincipal)
     {
         return(customPrincipal);
     }
     else
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.NoPrincipalSpecifiedInAuthorizationContext));
     }
 }
Example #31
0
 public SecurityMessageProperty()
 {
     _securityContext = ServiceSecurityContext.Anonymous;
 }
Example #32
0
        internal MessageRpc(RequestContext requestContext, Message request, DispatchOperationRuntime operation,
            ServiceChannel channel, 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<object>.Allocate(operation.Parent.CorrelationCount);
            this.DidDeserializeRequestBody = false;
            this.Error = null;
            this.ErrorProcessor = null;
            this.FaultInfo = new ErrorHandlerFaultInfo(request.Version.Addressing.DefaultFaultAction);
            this.HasSecurityContext = false;
            this.Instance = null;
            this.MessageRpcOwnsInstanceContextThrottle = false;
            this.NextProcessor = null;
            this.NotUnderstoodHeaders = null;
            this.Operation = operation;
            this.OperationContext = operationContext;
            _paused = false;
            this.ParametersDisposed = false;
            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;
            _switchedThreads = !cleanThread;
            this.InputParameters = null;
            this.OutputParameters = null;
            this.ReturnParameter = null;
            _isInstanceContextSingleton = false;
            _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();
            }

            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);
                }
            }
        }