14 Replies Latest reply on May 8, 2014 7:11 AM by amit.bhonsle

    REST API Authorization error

    vasylnakonechnyi

      Greetings.

       

      I've tried to build an application which should retreeve data from jive but when I tried to authorize - got 401 "Unauthorized" exception;

       

      Here is my authorization code:

      private static string GetAuthorizationResponceSession()
              {
              
                      HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://{my_domain}/api/core/v2/authentication/formlogin?username={login}&password={password}");
                      request.Method = "POST";
                      request.ContentType = "application/x-www-form-urlencoded";
                      WebResponse resp = request.GetResponse();
      
                      using(HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                      using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                      {
                         return reader.ReadToEnd();
                      }
             }
      
      
      
      

       

       

      This code was wroten according to :

      https://community.jivesoftware.com/casethread/192014#1070266

       

      beacuse before I've tried to get person object using next code:

       

         

              NetworkCredential myCredentials = new NetworkCredential("{my_login}", "{my_password}");
                      myCredentials.Domain ="https://{my_domain}/api/core/v2";
      
      
                      string cre = String.Format("{0}:{1}","{my_login}", "{my_password}");
      
      
                      byte[] bytes = Encoding.UTF8.GetBytes(cre);
      
      
                      string base64 = Convert.ToBase64String(bytes);
      
      
                    
                      System.Net.Http.HttpClientHandler jiveHandler = new System.Net.Http.HttpClientHandler();
                      jiveHandler.Credentials = myCredentials;
                      jiveHandler.PreAuthenticate = true;
                      jiveHandler.UseDefaultCredentials = true;
      
      
                      var httpClient = new System.Net.Http.HttpClient(jiveHandler);
                                     httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", base64);
      
      
                    
                      
                      System.Net.Http.HttpResponseMessage response = await httpClient.GetAsync(String.Format("https://{my_domain}/api/core/v2/people/{id_of_person}"));
      
      
                      if (response.IsSuccessStatusCode)
                      {
                        //procesing responce...
                      {
                     
      

       

       

      What I did wrong??

      Any ideas ?

        • Re: REST API Authorization error
          charyorde

          Hi,

           

          I think your url should be constructed like this:

           

          https://{username}:{password}@{my_domain}/api/core/v2/authentication/formlogin
            • Re: REST API Authorization error
              vasylnakonechnyi

              Noup...got error : "Invalid URI: The hostname could not be parsed.";

               

              even with converting in to base64 it still throw an error

                • Re: REST API Authorization error
                  charyorde

                  I'm reading this now: REST Reference : Authentication Service

                   

                  It reads "...and a request body containing username and password form parameters in the following format: "

                   

                  Have you tried sending the username and password as a request body instead of passing it as url parameter?

                    • Re: Re: REST API Authorization error
                      vasylnakonechnyi

                             tested this code according to link you gave:

                       

                      HttpWebRequest HttpWReq = (HttpWebRequest)WebRequest.Create(ConfigurationManager.AppSettings["JiveURL"] + "/api/core/v2/authentication/formlogin");
                      
                                      ASCIIEncoding encoding = new ASCIIEncoding();
                                      string stringData = "username=" + ConfigurationManager.AppSettings["JiveAccount"] + "&password=" + ConfigurationManager.AppSettings["JivePassword"];
                                      byte[] data = encoding.GetBytes(stringData);
                      
                      
                                      HttpWReq.Method = "PUT";
                                      HttpWReq.ContentLength = data.Length;
                                      HttpWReq.ContentType = "application/x-www-form-urlencoded";
                                      Stream newStream = HttpWReq.GetRequestStream();
                                      newStream.Write(data, 0, data.Length);
                                      newStream.Close();
                      
                                      using (HttpWebResponse response = (HttpWebResponse)HttpWReq.GetResponse())
                                      {
                                          using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                                          {
                                              return reader.ReadToEnd();
                                          }
                                      }
                      

                       

                       

                      Still got n error but  now it's 401 "Unauthorized" =( seems like it's problem in my jive settings ?

                • Re: REST API Authorization error
                  vasylnakonechnyi

                  Got changes...

                  with this code:

                   

                              System.Net.NetworkCredential nc = new NetworkCredential(jiveUserName, jivePassword);
                              CredentialCache cc = new CredentialCache();
                              cc.Add(new Uri(jiveUrl),"Basic", nc);
                  
                              WebRequest request = WebRequest.Create(jiveUrl);
                  
                              string authInfo = jiveUserName + ":" + jivePassword;
                              authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
                              request.Headers["Authorization"] = "Basic " + authInfo;
                              request.Credentials = cc;
                              request.PreAuthenticate = true;
                              request.Method = "POST";
                              request.ContentType = "application/json";
                  
                            using (var webResponse = request.GetResponse())
                              {
                                  using (var responseStream = webResponse.GetResponseStream())
                                  {
                                      return new StreamReader(responseStream).ReadToEnd();
                                  }
                              }
                  

                   

                  returns OK response but still whet trying to get jiveUrl/api/core/v2/people request with the same way... still got 401 Unauthorized. Who knows is there special settings for api in jive ??? or I still do something wrong ??

                  • Re: REST API Authorization error

                    As far as I know, you should be able to make a request to any endpoint in the v2 API by simply supplying the Authorization header with the correct credentials so that you have in the latest post looks correct. Perhaps try comenting out the request.Credentials = cc; section just to make sure it's not conflicting with the header you're manually setting there? Logging authInfo to make sure it's sending the correct string might also be helpful.

                     

                    I should mention the people endpoint doesn't exist in the v2 API.

                    • Re: REST API Authorization error
                      vasylnakonechnyi

                      I changed code:

                       

                      public bool Authorize(string jiveUrl, string jiveUserName, string jivePassword)
                              {
                                  var request = HttpWebRequest.Create(jiveUrl);
                      
                                  string authInfo = jiveUserName + ":" + jivePassword;
                                  authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
                                  request.Headers["Authorization"] = "Basic " + authInfo;
                                
                                  request.PreAuthenticate = true;
                                  request.Method = "POST";
                                 
                                  using (var webResponse = request.GetResponse())
                                  {
                                      SESSION_JIVE_ID =  webResponse.Headers["Set-Cookie"].ToString().Split(';').SingleOrDefault(x => x.Contains("JSESSIONID")).Split('=')[1].ToString() ;
                                  }
                      
                      
                                  return !String.IsNullOrWhiteSpace(SESSION_JIVE_ID);
                              }
                      
                              public void GetGroupsJson(string jiveUrl , string jiveUserName, string jivePassword)
                              {
                                  var request = HttpWebRequest.Create(jiveUrl + "/api/core/v2/groups");
                      
                      
                                  string authInfo = jiveUserName + ":" + jivePassword;
                                  authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
                                  request.Headers["Authorization"] = "Basic " + authInfo;
                                  request.Headers["JSESSIONID"] = SESSION_JIVE_ID;
                                            
                                  request.Method = "GET";
                                  request.ContentType = "application/json";
                      
                      
                                  using (var webResponse = request.GetResponse())
                                  {
                                      using (var responseStream = webResponse.GetResponseStream())
                                      {
                                          Console.WriteLine( new StreamReader(responseStream).ReadToEnd());
                                      }
                                  }
                               }
                      

                       

                       

                      so now I'm able to authorize and get JSESSIONID but when I trying to make request to "api/core/v2/groups" responce is : 401 Unauthorized

                       

                      I even did it without Authorization header in    second method (only with JSESSIONID) but still the same respomce...

                      • Re: REST API Authorization error

                        This seems to work for me.

                         

                        using System;
                        using System.Collections.Generic;
                        using System.Linq;
                        using System.Text;
                        using System.Net;
                        using System.IO;
                        
                        
                        namespace JiveTest
                        {
                            class Program
                            {
                                public static String jiveUrl = "https://<YOUR JIVE URL>";
                        
                        
                                static void Main(string[] args)
                                {
                                    JiveRequest("/api/core/v2/groups", "<USERNAME>", "<PASSWORD>");
                                    Console.WriteLine("Done");
                                }
                        
                        
                                public static string GenerateAuthorizationHeaderValue(string jiveUserName, string jivePassword)
                                {   
                                    return "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(jiveUserName + ":" + jivePassword));
                                }
                        
                        
                                public static void JiveRequest(string endpoint, string jiveUserName, string jivePassword)
                                {
                                    var request = HttpWebRequest.Create(jiveUrl + endpoint);
                                    request.Headers["Authorization"] = GenerateAuthorizationHeaderValue(jiveUserName, jivePassword);
                                    request.Method = "GET";
                                    request.ContentType = "application/json";
                        
                        
                                    using (var webResponse = request.GetResponse())
                                    {
                                        using (var responseStream = webResponse.GetResponseStream())
                                        {
                                            Console.WriteLine(new StreamReader(responseStream).ReadToEnd());
                                        }
                                    }
                                }
                            }
                        }
                        
                          • Re: REST API Authorization error
                            vasylnakonechnyi

                            =( it still don't work for me. this code is simmilar to my previous.... Thanks a lot Sonny now I understud that problem probably is in wrong settings of jive instance...

                              • Re: REST API Authorization error
                                baronzemm

                                https://MYDOMAINNAME/api/core/v2/authentication/formlogin?username=USERNAME&password=PASSWORD

                                2013-10-10 11_39_05-RESTClient.png

                                 

                                /*

                                * To change this template, choose Tools | Templates

                                * and open the template in the editor.

                                */

                                package org.jiveTest;

                                 

                                import com.sun.jersey.api.client.Client;

                                import com.sun.jersey.api.client.UniformInterfaceException;

                                import com.sun.jersey.api.client.WebResource;

                                import com.sun.jersey.core.util.MultivaluedMapImpl;

                                import javax.ws.rs.core.MultivaluedMap;

                                 

                                 

                                /**

                                * Jersey REST client generated for REST resource:authentication?_wadl&type=xml

                                * [authentication/formlogin]<br>

                                * USAGE:

                                * <pre>

                                *        JiveAuthClient client = new JiveAuthClient();

                                *        Object response = client.XXX(...);

                                *        // do whatever with response

                                *        client.close();

                                * </pre>

                                *

                                * @author 533864989

                                */

                                public class JiveAuthClient {

                                    private WebResource webResource;

                                    private Client client;

                                    private static final String BASE_URI = "http://localhost:8080/api/core/v2";

                                 

                                    public JiveAuthClient() {

                                        com.sun.jersey.api.client.config.ClientConfig config = new com.sun.jersey.api.client.config.DefaultClientConfig();

                                        client = Client.create(config);

                                        webResource = client.resource(BASE_URI).path("authentication/formlogin");

                                    }

                                 

                                    /**

                                     * @param responseType Class representing the response

                                     * @return response object (instance of responseType class)

                                     */

                                    public <T> T POST(Class<T> responseType, String username, String password) throws UniformInterfaceException {

                                        MultivaluedMap formData = new MultivaluedMapImpl();

                                        formData.add("username", username);

                                        formData.add("password", password);

                                        return webResource.post(responseType, formData);

                                    }

                                 

                                    public void close() {

                                        client.destroy();

                                    }

                                 

                                    public void setUsernamePassword(String username, String password) {

                                        client.addFilter(new com.sun.jersey.api.client.filter.HTTPBasicAuthFilter(username, password));

                                    }

                                  

                                }

                                 

                                .....

                                 

                                 

                                ClientResponse response = authClient.POST(ClientResponse.class, sUsername, sPassword);

                                 

                                The logon process is somewhat bound by what auth mechanism you use on your jive instance.

                                 

                                For example:

                                jive local username + password works fine

                                ldap works fine

                                 

                                ***NOTE****

                                If you use SAML it does not respect the SAML auth at all. It will continue to use your LDAP settings.

                                Just discovered this today...

                              • Re: REST API Authorization error
                                kasimirowicz

                                I searched for three hours, but your colde works for me, too! Thank you.