Example #1
0
        //Also shared by RequiredRoleAttribute and RequiredPermissionAttribute
        public static User AuthenticateBasicAuth(IHttpRequest req, IHttpResponse res)
        {
            var userCredentialsPair = req.GetBasicAuthUserAndPassword();
            var email    = userCredentialsPair.HasValue ? userCredentialsPair.Value.Key : String.Empty;
            var password = userCredentialsPair.HasValue ? userCredentialsPair.Value.Value : String.Empty;

            User user    = null;
            bool isValid = false;

            using (var session = NHibernateHelper.OpenSession())
            {
                using (var transaction = session.BeginTransaction())
                {
                    var userQuery = session.QueryOver <User>()
                                    .Where(table => table.Email == email)
                                    .And(table => table.Password == password);

                    user = userQuery.SingleOrDefault();

                    transaction.Commit();

                    isValid = (user != null);
                }
            }

            if (!isValid)
            {
                res.StatusCode = (int)HttpStatusCode.Unauthorized;
                res.EndServiceStackRequest();
            }

            return(user);
        }
Example #2
0
        public static ApiUser getUser(IHttpRequest request)
        {
            var    basicAuth = request.GetBasicAuthUserAndPassword();
            string key       = basicAuth.Value.Key;
            string api_token = basicAuth.Value.Value;

            if (key.Length != 13 || !key[6].Equals('-'))
            {
                throw new HttpError(HttpStatusCode.Forbidden, "Org/Instance is not correct.");
            }
            string[] split        = key.Split('-');
            string   org_key      = split[0];
            string   instance_key = split[1];

            if (api_token.Length != 32)
            {
                throw new HttpError(HttpStatusCode.Forbidden, "Token is not correct.");
            }
            ApiUser apiUser = new ApiUser(api_token);

            if (!apiUser.ValidateAccess(org_key, instance_key))
            {
                throw new HttpError(HttpStatusCode.Forbidden, "User is Inactive or does not have access to this Organization/Instance");
            }
            return(apiUser);
        }
        //Also shared by RequiredRoleAttribute and RequiredPermissionAttribute
        public static User AuthenticateBasicAuth(IHttpRequest req, IHttpResponse res)
        {
            var userCredentialsPair = req.GetBasicAuthUserAndPassword();
            var email = userCredentialsPair.HasValue ? userCredentialsPair.Value.Key : String.Empty;
            var password = userCredentialsPair.HasValue ? userCredentialsPair.Value.Value : String.Empty;

            User user = null;
            bool isValid = false;

            using (var session = NHibernateHelper.OpenSession())
            {
                using (var transaction = session.BeginTransaction())
                {
                    var userQuery = session.QueryOver<User>()
                        .Where(table => table.Email == email)
                        .And(table => table.Password == password);

                    user = userQuery.SingleOrDefault();

                    transaction.Commit();

                    isValid = (user != null);
                }
            }

            if (!isValid)
            {
                res.StatusCode = (int)HttpStatusCode.Unauthorized;
                res.EndServiceStackRequest();
            }

            return user;
        }
Example #4
0
 public void Authorize(IHttpRequest httpRequest, IHttpResponse httpResponse, object arg3)
 {
     var apikey = httpRequest.GetBasicAuthUserAndPassword();
     bool authorized = IsAuthorized(apikey);
     if (!authorized)
     {
         httpResponse.ReturnAuthRequired();
         return;
     }
     // Don't need to do anything if a valid API key
 }
 public static void AuthenticateIfBasicAuth(IHttpRequest req, IHttpResponse res)
 {
     var userPass = req.GetBasicAuthUserAndPassword();
     if (userPass != null)
     {
         var authService = req.TryResolve<AuthService>();
         authService.RequestContext = new HttpRequestContext(req, res, null);
         var response = authService.Post(new Auth.Auth {
             provider = BasicAuthProvider.Name,
             UserName = userPass.Value.Key,
             Password = userPass.Value.Value
         });
     }
 }
Example #6
0
        public override void Execute(IHttpRequest httpReq, IHttpResponse httpResp, object request)
        {
            var        basicAuth  = httpReq.GetBasicAuthUserAndPassword();
            ApiRequest apiRequest = request as ApiRequest;

            if (apiRequest == null)
            {
                //Custom Auth needed
                return;
            }

            string api_token = "";

            if (basicAuth == null)
            {
                api_token = httpReq.QueryString["api_token"];

                if (string.IsNullOrEmpty(api_token))
                {
                    httpResp.AddHeader(HttpHeaders.WwwAuthenticate, "Basic realm=\"/login\"");
                    throw new HttpError(HttpStatusCode.Unauthorized, "Invalid BasicAuth credentials");
                }
                else if (api_token.Length != 32)
                {
                    throw new HttpError(HttpStatusCode.Forbidden, "Token is not correct.");
                }
            }
            else
            {
                string key      = basicAuth.Value.Key;
                string password = basicAuth.Value.Value;
                if (string.IsNullOrEmpty(key) || string.IsNullOrEmpty(password))
                {
                    throw new HttpError(HttpStatusCode.Forbidden, "Token is not correct.");
                }
                if (key == "x")
                {
                    if (password.Length != 32)
                    {
                        throw new HttpError(HttpStatusCode.Forbidden, "Token is not correct.");
                    }
                    apiRequest.api_token = password;
                }
                else
                {
                    apiRequest.ApiUser = ApiUser.getUser(httpReq);
                }
            }
        }
Example #7
0
        public static void AuthenticateIfBasicAuth(IHttpRequest req, IHttpResponse res)
        {
            var userPass = req.GetBasicAuthUserAndPassword();

            if (userPass != null)
            {
                var authService = req.TryResolve <AuthService>();
                authService.RequestContext = new HttpRequestContext(req, res, null);
                var response = authService.Post(new Auth.Auth {
                    provider = BasicAuthProvider.Name,
                    UserName = userPass.Value.Key,
                    Password = userPass.Value.Value
                });
            }
        }
        public override void Execute(IHttpRequest req, IHttpResponse res, object requestDto)
        {
            if (AuthService.AuthConfigs == null)
            {
                throw new InvalidOperationException("The AuthService must be initialized by calling "
                                                    + "AuthService.Init to use an authenticate attribute");
            }

            var matchingOAuthConfigs = AuthService.AuthConfigs.Where(x =>
                                                                     this.Provider.IsNullOrEmpty() ||
                                                                     x.Provider == this.Provider).ToList();

            if (matchingOAuthConfigs.Count == 0)
            {
                res.WriteError(req, requestDto, "No OAuth Configs found matching {0} provider"
                               .Fmt(this.Provider ?? "any"));
                res.Close();
                return;
            }

            var userPass = req.GetBasicAuthUserAndPassword();

            if (userPass != null)
            {
                var authService = req.TryResolve <AuthService>();
                authService.RequestContext = new HttpRequestContext(req, res, requestDto);
                var response = authService.Post(new Auth.Auth {
                    provider = BasicAuthConfig.Name,
                    UserName = userPass.Value.Key,
                    Password = userPass.Value.Value
                });
            }

            using (var cache = req.GetCacheClient())
            {
                var sessionId = req.GetPermanentSessionId();
                var session   = sessionId != null?cache.GetSession(sessionId) : null;

                if (session == null || !matchingOAuthConfigs.Any(x => session.IsAuthorized(x.Provider)))
                {
                    res.StatusCode = (int)HttpStatusCode.Unauthorized;
                    res.AddHeader(HttpHeaders.WwwAuthenticate, "{0} realm=\"{1}\""
                                  .Fmt(matchingOAuthConfigs[0].Provider, matchingOAuthConfigs[0].AuthRealm));

                    res.Close();
                }
            }
        }
Example #9
0
        public static ApiUser getUser(IHttpRequest request)
        {
            var    basicAuth = request.GetBasicAuthUserAndPassword();
            string key       = basicAuth.Value.Key;
            string api_token = basicAuth.Value.Value;

            if (key.IndexOf('-') < 6)
            {
                throw new HttpError(HttpStatusCode.Forbidden, "Org/Instance is not correct.");
            }
            string[] split        = key.Split('-');
            string   org_key      = split[0];
            string   instance_key = split[1];

            return(getUser(api_token, org_key, instance_key));
        }
        //Also shared by RequiredRoleAttribute and RequiredPermissionAttribute
        public static void AuthenticateIfBasicAuth(IHttpRequest req, IHttpResponse res)
        {
            //Need to run SessionFeature filter since its not executed before this attribute (Priority -100)
            SessionFeature.AddSessionIdToRequestFilter(req, res, null); //Required to get req.GetSessionId()

            var userPass = req.GetBasicAuthUserAndPassword();
            if (userPass != null)
            {
                var authService = req.TryResolve<AuthService>();
                authService.RequestContext = new HttpRequestContext(req, res, null);
                var response = authService.Post(new Auth.Auth {
                    provider = BasicAuthProvider.Name,
                    UserName = userPass.Value.Key,
                    Password = userPass.Value.Value
                });
            }
        }
Example #11
0
        private void AddClientDetails(IHttpRequest req, IHttpResponse res, object requestDto)
        {
            ITokenRequest request = requestDto as ITokenRequest;

            if (request == null)
            {
                return;
            }

            KeyValuePair <string, string>?clientdetails = req.GetBasicAuthUserAndPassword();

            if (clientdetails != null)
            {
                request.client_id       = clientdetails.Value.Key;
                request.client_password = clientdetails.Value.Value;
            }
        }
        //Also shared by RequiredRoleAttribute and RequiredPermissionAttribute
        public static void AuthenticateIfBasicAuth(IHttpRequest req, IHttpResponse res)
        {
            //Need to run SessionFeature filter since its not executed before this attribute (Priority -100)
            SessionFeature.AddSessionIdToRequestFilter(req, res, null); //Required to get req.GetSessionId()

            var userPass = req.GetBasicAuthUserAndPassword();

            if (userPass != null)
            {
                var authService = req.TryResolve <AuthService>();
                authService.RequestContext = new HttpRequestContext(req, res, null);
                var response = authService.Post(new Auth.Auth {
                    provider = BasicAuthProvider.Name,
                    UserName = userPass.Value.Key,
                    Password = userPass.Value.Value
                });
            }
        }
        public override void Execute(IHttpRequest req, IHttpResponse res, object requestDto)
        {
            if (AuthService.AuthConfigs == null) throw new InvalidOperationException("The AuthService must be initialized by calling "
                 + "AuthService.Init to use an authenticate attribute");

            var matchingOAuthConfigs = AuthService.AuthConfigs.Where(x =>
                            this.Provider.IsNullOrEmpty()
                            || x.Provider == this.Provider).ToList();

            if (matchingOAuthConfigs.Count == 0)
            {
                res.WriteError(req, requestDto, "No OAuth Configs found matching {0} provider"
                    .Fmt(this.Provider ?? "any"));
                res.Close();
                return;
            }

            var userPass = req.GetBasicAuthUserAndPassword();
            if (userPass != null)
            {
                var authService = req.TryResolve<AuthService>();
                authService.RequestContext = new HttpRequestContext(req, res, requestDto);
                var response = authService.Post(new Auth.Auth {
                    provider = BasicAuthConfig.Name,
                    UserName = userPass.Value.Key,
                    Password = userPass.Value.Value
                });
            }

            using (var cache = req.GetCacheClient())
            {
                var sessionId = req.GetPermanentSessionId();
                var session = sessionId != null ? cache.GetSession(sessionId) : null;

                if (session == null || !matchingOAuthConfigs.Any(x => session.IsAuthorized(x.Provider)))
                {
                    res.StatusCode = (int)HttpStatusCode.Unauthorized;
                    res.AddHeader(HttpHeaders.WwwAuthenticate, "{0} realm=\"{1}\""
                        .Fmt(matchingOAuthConfigs[0].Provider, matchingOAuthConfigs[0].AuthRealm));

                    res.Close();
                }
            }
        }
Example #14
0
        public void ProcessRequest(IHttpRequest request, IHttpResponse response, string operationName)
        {
            try
            {
                response.ContentType = "application/json";
                var basePath = request.GetBaseUrl();
                var result   = new SwaggerResourcesResponse
                {
                    BasePath   = basePath,
                    Apis       = new List <SwaggerResourceRef>(),
                    ApiVersion = _config.ApiVersion,
                    Info       = new SwaggerInfo
                    {
                        Title = _config.Title ?? "Ant-SOA-API",
                    }
                };

                if (_config.UseBasicAuth)
                {
                    var basicAuth = request.GetBasicAuthUserAndPassword();
                    if (basicAuth == null)
                    {
                        result.Info.Title = "Auth Error";
                        response.Write(result.ToJson());
                        response.EndRequest(true);
                        return;
                    }
                    else
                    {
                        var userName  = basicAuth.Value.Key;
                        var password  = basicAuth.Value.Value;
                        var localAuth = _config.GetLocalAuthModel();
                        if (!localAuth.UserName.Equals(userName) && !localAuth.Password.Equals(password))
                        {
                            result.Info.Title = "Auth Error";
                            response.Write(result.ToJson());
                            response.EndRequest(true);
                            return;
                        }
                    }
                }
                result.Apis.Add(new SwaggerResourceRef
                {
                    Path        = request.ResolveAbsoluteUrl("~/" + SwaggerApiService.RESOURCE_PATH),
                    Description = _config.HostConfig.MetadataMap.FirstOrDefault().Value.ServiceName
                });

                result.Apis = result.Apis.OrderBy(a => a.Path).ToList();
                if (ResourcesResponseFilter != null)
                {
                    ResourcesResponseFilter(result);
                }

                response.Write(result.ToJson());
                response.EndRequest(true);
            }
            catch (Exception)
            {
                response.EndRequestWithNoContent();
            }
        }
Example #15
0
 public static ApiUser getUser(IHttpRequest request)
 {
     var basicAuth = request.GetBasicAuthUserAndPassword();
     string key = basicAuth.Value.Key;
     string api_token = basicAuth.Value.Value;
     if (key.Length != 13 || !key[6].Equals('-'))
         throw new HttpError(HttpStatusCode.Forbidden, "Org/Instance is not correct.");
     string[] split = key.Split('-');
     string org_key = split[0];
     string instance_key = split[1];
     if (api_token.Length != 32)
         throw new HttpError(HttpStatusCode.Forbidden, "Token is not correct.");
     ApiUser apiUser = new ApiUser(api_token);
     if (!apiUser.ValidateAccess(org_key, instance_key))
         throw new HttpError(HttpStatusCode.Forbidden, "User is Inactive or does not have access to this Organization/Instance");
     return apiUser;
 }
Example #16
0
        public override void Execute(IHttpRequest httpReq, IHttpResponse httpResp, object request)
        {
            var basicAuth = httpReq.GetBasicAuthUserAndPassword();
            ApiRequest apiRequest = request as ApiRequest;
            if (apiRequest == null)
            {
                //Custom Auth needed
                return;
            }

            string api_token = "";

            if (basicAuth == null)
            {
                api_token = httpReq.QueryString["api_token"];

                if (string.IsNullOrEmpty(api_token))
                {
                    httpResp.AddHeader(HttpHeaders.WwwAuthenticate, "Basic realm=\"/login\"");
                    throw new HttpError(HttpStatusCode.Unauthorized, "Invalid BasicAuth credentials");
                }
                else if (api_token.Length != 32)
                    throw new HttpError(HttpStatusCode.Forbidden, "Token is not correct.");
            }
            else
            {
                string key = basicAuth.Value.Key;
                string password = basicAuth.Value.Value;
                if (string.IsNullOrEmpty(key) || string.IsNullOrEmpty(password))
                    throw new HttpError(HttpStatusCode.Forbidden, "Token is not correct.");
                if (key == "x")
                {
                    if (password.Length != 32)
                        throw new HttpError(HttpStatusCode.Forbidden, "Token is not correct.");
                    apiRequest.api_token = password;
                }
                else
                {
                    apiRequest.ApiUser = ApiUser.getUser(httpReq);
                }
            }
        }