简体   繁体   中英

Error 401 When calling the Sitefinity WCF Web Services

I've Started Developing with Sitefinity 8.1 and I need to access to Sitefinity's WCF Web Services (eg ~\\Sitefinity\\Services\\Ecommerce\\Catalog\\ProductService.svc)

I've tryed to access them like any other Web Service, but I get a 401 error. After searching on the web and Sitefinity Forum I Found a couple of things.

  1. I need to Authenticate Before I Use the Services [1& 2]

  2. The Claim-Based Authentication is the default Authentication

  3. The url used to authenticate is /Sitefinity/Services/Security/Users.svc/authenticate [1 & 2]

  4. I also found a snippet provided by Ivan Dimitrov where he codes the authentication Code [3]

  5. Client Api it's worthless to authenticate and allow the request to web services

  6. Its needed a STS to Authenticate and it is integrated in my Sitefinity Installation [2] “You may be wondering where this STS is. By default the logic is integrated in your Sitefinity application and can be found under~/Sitefinity/SWT. [2]

    After I Read this information I adapted the code provided by Ivan Dimitrov [3] and coded the Call to the ~\\Sitefinity\\Services\\Ecommerce\\Catalog\\ProductService.svc. And I got 401 error.

'The remote server returned an error: (401) Unauthorized' is a result of wrong credentials, However I tested the same credentials with the Client Api, Through SecurityManager class and I get the “UserLoggingReason.Succes”, so the credentials are Correct.

The Strange fact is that I don't have any ~/Sitefinity/SWT folder. May that be the root of my problems?

I'm Using ASP.NET MVC, and I'm doing the request from a Web Api Controller. And this is the adapted Code:

public static bool AuthenticateRequest(string membershipProvider, string userName, string password, bool rememberMe, ApiController controller)
{

    var jsonData = String.Format(credentialsFormat, membershipProvider, userName, password, rememberMe.ToString().ToLower());
    var credentials = Encoding.UTF8.GetBytes(jsonData);
    string result = InvokeWebMethod(usersServiceUrl, authenticateMethod, "POST", credentials, controller);
    switch (result)
    {
        case "0":
            return true;
        default:
            return false;
    }

}

public static string InvokeWebMethod(string serviceUrl, string methodName, string httpMethod, byte[] data, ApiController controller)
{

    var request = (HttpWebRequest)WebRequest.Create(String.Concat(sitefinityHost, serviceUrl, methodName));
    request.Method = httpMethod;
    request.ContentType = "application/json";
    request.CookieContainer = new CookieContainer();

    if (cookies != null)
    {
        foreach (Cookie cookie in cookies)
            if (!cookie.Expired)
                request.CookieContainer.Add(cookie);
    }

    if (data != null)
    {
        request.ContentLength = data.Length;
        using (var writer = request.GetRequestStream())
        {
            writer.Write(data, 0, data.Length);
        }
    }


    using (var response = (HttpWebResponse)request.GetResponse()) //The error is here
    {
        cookies = response.Cookies;
        using (var reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
        {
              var cookie = new HttpCookie("customCookie", "cookieVal")
            {
                Expires = DateTime.Now.AddDays(1),
                Domain = controller.Request.RequestUri.Host,
                Path = "/"
            };
            HttpContext.Current.Response.SetCookie(cookie);

            return reader.ReadToEnd();
        }
    }
}

(I also Changed the sitefinityHost to my machine)

Are all of my 6 premises correct or something have changed?

What could be the cause of 401?

Thank you very much,

References (The Most relevants):

[1] How to Authenticate ( http://www.sitefinity.com/blogs/svetlayankova/posts/svetla-yankovas-blog/2011/11/01/getting_started_with_restful_services_in_sitefinity )

[2] How to Authenticate ( http://www.sitefinity.com/blogs/svetla-yankovas-blog/2013/01/02/working-with-restful-services-part-2-claims-authentication-and-designing-service-calls )

[3] Authentication Code ( http://www.sitefinity.com/developer-network/forums/general-discussions-/windows-authentication#1655610 )

timw255 has written a REST client for Sitefinity. It is available here: https://github.com/timw255/timw255.Sitefinity.RestClient

The method below logs the user in he is using RestSharp (very help library)

 private void SignIn()
    {
        RestRequest request = new RestRequest("Sitefinity/Authenticate", Method.GET);

        IRestResponse response = _restClient.Execute(request);

        switch (response.StatusCode)
        {
            case HttpStatusCode.OK:
                request = new RestRequest("Sitefinity/Authenticate/SWT?realm={realm}&redirect_uri={redirectUri}&deflate=true", Method.POST);

                request.AddUrlSegment("realm", _baseUrl);
                request.AddUrlSegment("redirectUri", "/Sitefinity");

                request.AddParameter("wrap_name", _username, ParameterType.GetOrPost);
                request.AddParameter("wrap_password", _password, ParameterType.GetOrPost);
                request.AddParameter("sf_persistent", "true", ParameterType.GetOrPost);

                response = _restClient.Execute(request);

                switch (response.StatusCode)
                {
                    case HttpStatusCode.OK:
                        if (response.ResponseUri.AbsolutePath == "/Sitefinity/SignOut/selflogout")
                        {
                            SelfLogout();
                        }
                        break;
                    case HttpStatusCode.Unauthorized:
                        throw new SitefinityException("Invalid username or password");
                    default:
                        break;
                }
                break;
            case HttpStatusCode.Redirect:
                throw new NotImplementedException("External STS not supported");
            default:
                break;
        }
    }

File: https://github.com/timw255/timw255.Sitefinity.RestClient/blob/master/timw255.Sitefinity.RestClient/SitefinityRestClient.cs

The SWT folder isn't an actual file system folder it is a route.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM