Exemplo n.º 1
0
        /// <summary>
        /// Attempts to authorize the client issuing the request.
        /// </summary>
        /// <param name="actionContext">
        /// The action context.
        /// </param>
        public void AuthorizeUser(HttpActionContext actionContext)
        {
            Log.Verbose("SimpleWebTokenAuthAttribute.OnAuthorization");

            // Attempt to get credentials from the the client certificate.
            SecurityCredentials credentials = this.GetCredentialsFromAuthorizationHeader(actionContext);

            bool isAuthorized = false;

            if (credentials != null)
            {
                AuthPayload payload = Security.Authenticate(credentials);
                if (payload != null)
                {
                    if (Security.Authorize(payload, this.Roles))
                    {
                        isAuthorized = true;
                        Log.Verbose("User is authorized");
                    }
                    else
                    {
                        Log.Warn("Unauthorized user");
                    }
                }
            }

            if (!isAuthorized)
            {
                actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// The get user credentials from bing header.
        /// </summary>
        /// <param name="actionContext">
        /// The action context.
        /// </param>
        /// <returns>
        /// The <see cref="SecurityCredentials"/>.
        /// </returns>
        private SecurityCredentials GetCredentialsFromBingHeader(HttpActionContext actionContext)
        {
            SecurityCredentials  credentials = null;
            IEnumerable <string> headers;

            if (actionContext.Request.Headers != null &&
                actionContext.Request.Headers.TryGetValues(BingAuhtenticationHeader, out headers))
            {
                try
                {
                    string token = (from h in headers select h).FirstOrDefault();
                    if (!string.IsNullOrWhiteSpace(token))
                    {
                        credentials       = new SecurityCredentials();
                        credentials.Token = token;
                        credentials.SecurityProviderName = "lomo";
                    }
                }
                catch (Exception e)
                {
                    Log.Error(e, "Error While reading bing header");

                    throw;
                }
            }

            return(credentials);
        }
        /// <summary>
        /// The authenticate.
        /// </summary>
        /// <param name="credentials">
        /// The credentials.
        /// </param>
        /// <param name="flags">A general purpose flags set</param>
        /// <returns>
        /// The <see cref="AuthPayload"/>.
        /// </returns>
        public AuthPayload Authenticate(SecurityCredentials credentials, HashSet <string> flags = null)
        {
            AuthPayload result = null;

            if (SimpleWebTokenValidator.Validate(credentials.Token, ResourceNamespace, String.Format(ResourceTemplate, credentials.Name),
                                                 TrustedSigningKey) == true)
            {
                result = new AuthPayload(new CustomIdentity(credentials.Token, credentials.Name, credentials.SecurityProviderName));
            }

            return(result);
        }
Exemplo n.º 4
0
        /// <summary>
        /// The authenticate.
        /// </summary>
        /// <param name="credentials">
        /// The credentials.
        /// </param>
        /// <param name="flags">A general purpose flags set </param>
        /// <returns>
        /// The <see cref="AuthPayload"/>.
        /// </returns>
        public AuthPayload Authenticate(SecurityCredentials credentials, HashSet <string> flags = null)
        {
            AuthPayload result = null;

            // If the client certificate thumbprint is one of the registered thumbprints, create a CustomIdentity object for it.
            if (registeredThumbprints.ContainsKey(credentials.Token))
            {
                result = new AuthPayload(new CustomIdentity(credentials.Token, credentials.Name, credentials.SecurityProviderName));
            }

            return(result);
        }
Exemplo n.º 5
0
        /// <summary>
        /// Attempts to authorize the user for the request.
        /// </summary>
        /// <param name="actionContext">
        /// The action context.
        /// </param>
        public virtual void AuthorizeUser(HttpActionContext actionContext)
        {
            Log.Verbose("ApiAuthAttribute.OnAuthorization");

            string reason = string.Empty;

            // Attempt to get credentials from the HTTP authentication header. This could support application auth. or debug scenarios
            SecurityCredentials credentials = this.GetCredentialsFromAuthorizationHeader(actionContext);

            // If we did not have credentials specifed in the HTTP Authentication header
            if (credentials == null)
            {
                // Attempt to get credentials from the Bing authentication header.
                credentials = this.GetCredentialsFromBingHeader(actionContext);
            }

            bool isAuthorized = false;

            if (credentials != null)
            {
                AuthPayload payload = Security.Authenticate(credentials, this.Flags);
                if (payload != null)
                {
                    if (Security.Authorize(payload, this.Roles))
                    {
                        isAuthorized = true;
                        Log.Verbose("User is authorized");
                    }
                    else
                    {
                        Log.Warn("Unauthorized user");
                    }
                }
            }

            if (!isAuthorized)
            {
                if (this.AllowAnonymous)
                {
                    var roles = new[] { "reader" };
                    Security.SetAnonymous(roles);
                }
                else
                {
                    actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized)
                    {
                        ReasonPhrase =
                            reason
                    };
                }
            }
        }
        /// <summary>
        /// The authenticate.
        /// </summary>
        /// <param name="credentials">
        /// The credentials.
        /// </param>
        /// <param name="flags">A general purpose flags set</param>
        /// <returns>
        /// The <see cref="AuthPayload"/>.
        /// </returns>
        public AuthPayload Authenticate(SecurityCredentials credentials, HashSet <string> flags = null)
        {
            bool useExternalIdentity = flags != null && flags.Contains("UseExternalIdentity");
            var  sb = new StringBuilder();

            if (HttpContext.Current != null)
            {
                // The cookie "bo_referrer" has the publisher info that drove the user sign up to bing offers.
                // Add this publisher info to the user's source column in the db for new user
                var cookie = HttpContext.Current.Request.Cookies["bor"];
                if (cookie != null && !string.IsNullOrEmpty(cookie.Value))
                {
                    sb.Append(cookie.Value);
                    Log.Info(string.Format("bor cookie is : {0}", cookie.Value));
                }
                else
                {
                    Log.Info("bor Cookie is null");
                }

                cookie = HttpContext.Current.Request.Cookies["bof"];
                if (cookie != null && !string.IsNullOrEmpty(cookie.Value))
                {
                    sb.Append("#");
                    sb.Append(cookie.Value);
                    Log.Info(string.Format("bof cookie is : {0}", cookie.Value));
                }
                else
                {
                    Log.Info("bof Cookie is null");
                }
            }
            else
            {
                Log.Info("HttpContext is null");
            }

            if (!useExternalIdentity)
            {
                string       userSource   = sb.Length > 0 ? sb.ToString() : null;
                UserLocation userLocation = this.GetUserLocation();
                User         user         = this.usersDal.CreateOrGetUserByMsId(credentials.IdentificationCode, userSource, userLocation: userLocation);
                var          identity     = new CustomIdentity(user.Id, user.Name, "user_debug");
                return(new AuthPayload(identity));
            }

            return(new AuthPayload(new CustomIdentity(default(Guid), null, "user_debug", credentials.IdentificationCode)));
        }
Exemplo n.º 7
0
        /// <summary>
        /// The authenticate.
        /// </summary>
        /// <param name="credentials">
        /// The user credentials.
        /// </param>
        /// <param name="flags">the flags</param>
        /// <returns>
        /// The auth payload
        /// </returns>
        internal static AuthPayload Authenticate(SecurityCredentials credentials, HashSet <string> flags = null)
        {
            AuthPayload result = null;

            if (authorizers.ContainsKey(credentials.SecurityProviderName) == true)
            {
                ISecurityProvider securityProvider = authorizers[credentials.SecurityProviderName];
                result = securityProvider.Authenticate(credentials, flags);
            }
            else
            {
                Log.Warn("Unregistered security provider was specified: {0}", credentials.SecurityProviderName);
            }

            return(result);
        }
        /// <summary>
        /// The get user credentials from the client certificate.
        /// </summary>
        /// <param name="actionContext">
        /// The action context.
        /// </param>
        /// <returns>
        /// The <see cref="SecurityCredentials"/>.
        /// </returns>
        private SecurityCredentials GetCredentialsFromClientCertificate(HttpActionContext actionContext)
        {
            SecurityCredentials credentials = null;

            X509Certificate2 certificate = actionContext.Request.GetClientCertificate();

            if (certificate != null)
            {
                credentials       = new SecurityCredentials();
                credentials.Token = certificate.Thumbprint;
                credentials.SecurityProviderName = MutualSslSecurityProvider.Name;
                credentials.Name = certificate.Subject;
            }

            return(credentials);
        }
Exemplo n.º 9
0
        /// <summary>
        /// The get user credentials from the authorization header.
        /// </summary>
        /// <param name="actionContext">
        /// The action context.
        /// </param>
        /// <returns>
        /// The <see cref="SecurityCredentials"/>.
        /// </returns>
        private SecurityCredentials GetCredentialsFromAuthorizationHeader(HttpActionContext actionContext)
        {
            SecurityCredentials credentials = null;

            if (actionContext.Request.Headers != null && actionContext.Request.Headers.Authorization != null)
            {
                string token = actionContext.Request.Headers.Authorization.Parameter;
                credentials = new SecurityCredentials
                {
                    Token = token,
                    SecurityProviderName = actionContext.Request.Headers.Authorization.Scheme,
                    Name = Roles[0]
                };
            }

            return(credentials);
        }
Exemplo n.º 10
0
        /// <summary>
        /// The authenticate.
        /// </summary>
        /// <param name="credentials">
        /// The credentials.
        /// </param>
        /// <param name="flags">A general purpose flags set </param>
        /// <returns>
        /// The <see cref="AuthPayload"/>.
        /// </returns>
        public AuthPayload Authenticate(SecurityCredentials credentials, HashSet <string> flags = null)
        {
            bool useExternalIdentity = flags != null && flags.Contains("UseExternalIdentity");

            if (credentials == null)
            {
                // || string.IsNullOrWhiteSpace(credentials.IdentificationCode))
                throw new Exception("The LomoSecurityProvider.Authenticate() method was called with invalid Credentials.");
            }

            var externalIdentityInfo = Authentication.BingSocialAccessorRepository.GetUserAccountInfo(credentials.Token);

            if (externalIdentityInfo != null && externalIdentityInfo.UserId != null)
            {
                User user = null;
                if (!useExternalIdentity)
                {
                    user = this.CreateOrGetInternalUser(externalIdentityInfo);
                }

                Guid userId       = default(Guid);
                var  userName     = externalIdentityInfo.Name;
                var  emailAddress = externalIdentityInfo.UserEmail;
                if (user != null)
                {
                    userId = user.Id;
                    if (string.IsNullOrWhiteSpace(userName) && !string.IsNullOrWhiteSpace(user.Name))
                    {
                        userName = user.Name;
                    }

                    emailAddress = user.Email;
                }

                var identity = new CustomIdentity(userId, userName, SecurityProvider, externalIdentityInfo.UserId)
                {
                    EmailAddress = emailAddress
                };

                var payload = new AuthPayload(identity);
                return(payload);
            }

            return(null);
        }
Exemplo n.º 11
0
        /// <summary>
        /// The authenticate.
        /// </summary>
        /// <param name="credentials">
        /// The credentials.
        /// </param>
        /// <param name="flags">
        /// A general purpose flags set
        /// </param>
        /// <returns>
        /// The <see cref="AuthPayload"/>.
        /// </returns>
        public AuthPayload Authenticate(SecurityCredentials credentials, HashSet <string> flags = null)
        {
            AuthPayload result = null;

            if (credentials.Token != null)
            {
                LomoUserIdSecurityToken token = new LomoUserIdSecurityToken(
                    credentials.Token,
                    ConfigurationManager.AppSettings[AppSettingsKeys.SecureTokenSigningKey],
                    ConfigurationManager.AppSettings[AppSettingsKeys.SecureTokenPassword],
                    ConfigurationManager.AppSettings[AppSettingsKeys.SecureTokenSalt],
                    Convert.ToUInt64(ConfigurationManager.AppSettings[AppSettingsKeys.SecureTokenClockSkew]));

                var identity = new CustomIdentity(new Guid(token.UserId), null, credentials.SecurityProviderName);
                result = new AuthPayload(identity);
                result.CredentialAuthorizationParameters[Resource] = token.Resource;
                result.CredentialAuthorizationParameters[Action]   = token.Action;
            }

            return(result);
        }
Exemplo n.º 12
0
        /// <summary>
        /// The get user credentials from authorization header.
        ///     The header name is: Authentication
        ///     HttpHeader: Authentication bearer XXXXXXXXXXXXXXXXXXX
        /// </summary>
        /// <param name="actionContext">
        /// The action context.
        /// </param>
        /// <returns>
        /// The <see cref="SecurityCredentials"/>.
        /// </returns>
        private SecurityCredentials GetCredentialsFromAuthorizationHeader(HttpActionContext actionContext)
        {
            SecurityCredentials credentials = null;

            if (actionContext.Request.Headers != null && actionContext.Request.Headers.Authorization != null)
            {
                string token = actionContext.Request.Headers.Authorization.Parameter;
                credentials = new SecurityCredentials();

                // this should be an encrypted token.
                credentials.Token = token;

                // The HTTP authentication header has the form: Authentication: <scheme> token
                // We are using the scheme to select the security provider. This might not be a good idea for production
                // Once we figure out the scenarios we should support only a Provider for applications
                credentials.SecurityProviderName = actionContext.Request.Headers.Authorization.Scheme;
                credentials.IdentificationCode   = token;
                credentials.Name = token; // what do we use for a name?
            }

            return(credentials);
        }
        /// <summary>
        /// Attempts to authorize the client issuing the request.
        /// </summary>
        /// <param name="actionContext">
        /// The action context.
        /// </param>
        public void AuthorizeUser(HttpActionContext actionContext)
        {
            Log.Verbose("MutualSslAuthAttribute.OnAuthorization");

            // Attempt to get credentials from the the client certificate.
            SecurityCredentials credentials = this.GetCredentialsFromClientCertificate(actionContext);

            bool isAuthorized = false;

            if (credentials != null)
            {
                AuthPayload payload = Security.Authenticate(credentials);
                if (payload != null)
                {
                    if (Security.Authorize(payload, this.Roles))
                    {
                        isAuthorized = true;
                        Log.Verbose("User is authorized");
                    }
                    else
                    {
                        Log.Warn("Unauthorized user");
                    }
                }
                else
                {
                    Log.Warn("Unable to build auth payload while authenticating credentials.");
                }
            }
            else
            {
                Log.Warn("Unable to build credentials from client certificate.");
            }

            if (!isAuthorized)
            {
                actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
            }
        }