12 Replies Latest reply on Nov 15, 2017 2:43 PM by mtdimich

    403 Unauthorized when using contents api to update a document's subject

    mtdimich

      Hello,

       

      I'm using the contents api to update the subject of a large number of hub documents.  As I go through, it appears all the documents where I'm not the original author receive a 403 Unauthorized error, and all the documents that I did author originally succeed.  However, when I use the UI, I can edit the subject of those documents where I'm not the original author. So I seem to have the appropriate level of permissions and I'm not just trying to update the wrong thing.

       

      Since my update works, I'm not sure if adding my python code here will help.  Any suggestions or starting places to look?  Is there something in the API I missed that I have to change if I'm not the author?

       

      <edit - 11/11/2017 - Here's my code.>

      # Function that updates the subject of a hub document
      # Return 0 - update Successful
      # Return 1 - Error on updateDocSubject
      # Return 2 - Update not needed.
      def updateDocSubject(token, jiveDocId, host):
          import json, urllib2,urllib,datetime, httplib
          from pprint import pprint
          print "***********************"
          print "Updating doc with ID: " + jiveDocId
          current_url = host + '/api/core/v3/contents/'+ jiveDocId
          print "Retrieving Data Sheet: " + current_url
          req = urllib2.Request(current_url)
          req.add_header('Accept', 'application/json')
          req.add_header('Authorization','Bearer ' + token)
          page = urllib2.urlopen(req)
          payload = page.read()
          payload = payload[payload.find('{'):]
          obj=json.loads(payload)
          print "Retrieved doc:" + obj["subject"]
          print "Found ref url of " + obj["resources"]["self"]["ref"]
          print "Found HTML link: " + obj["resources"]["html"]["ref"]
          print "Capable of methods " + ",".join(obj["resources"]["self"]["allowed"])
          print "Author: " + obj["author"]["displayName"]
          if "redacted string" not in obj["subject"]:
              newSubject = obj["subject"].replace("redacted string", "replacement redacted string")
              print "Setting the new Doc Title to: " + newSubject
              put_url = obj["resources"]["self"]["ref"]
              print 'updating...' + put_url
              putRequest=urllib2.Request(put_url)
              putRequest.add_header('Content-Type', 'application/json')
              putRequest.add_header('Authorization','Bearer ' + token)
              putRequest.get_method = lambda: 'PUT'
      
      
              myDocUpdateReq = {"subject" : newSubject, "type" : "document", "content": obj["content"]  }
              print "sending request..."
              #pprint(json.dumps(myDocUpdateReq))
              try:
                  response = urllib2.urlopen(putRequest, data=json.dumps(myDocUpdateReq))
                  if response.code == 200:
                      print "Update Successful"
                      return 0
              except urllib2.HTTPError, e:
                  print "Problem updating data sheet"
                  print ('HTTPError = ' + str(e.code))
                  print ('HTTPError = ' + str(e.reason))
                  # raise
              except urllib2.URLError, e:
                  print "Problem updating data sheet"
                  print ('URLError = ' + str(e.reason))
                  # raise
              except httplib.HTTPException, e:
                  print "Problem updating data sheet"
                  print ('HTTPException')
                  # raise
              except Exception:
                  import traceback
                  print ('generic exception: ' + traceback.format_exc())
                  raise
          else:
              print "Update not required"
              return 2
          return 1
      

       

       

      Thanks!

      Matt

        • Re: 403 Unauthorized when using contents api to update a document's subject
          jgoldhammer

          Matt,


          How do you update the subject? I think your code would help. 


          Thanks

          Jens

          • Re: 403 Unauthorized when using contents api to update a document's subject
            jgoldhammer

            And you could see on the document json in the   resources field which methods are allowed...

            • Re: 403 Unauthorized when using contents api to update a document's subject
              mtdimich

              Thanks, I did print that out and put is an option for each of the docs I was still having trouble with.  That's what was confusing, because it seemed to indicate it should be ok.  I would be more suspicious of my code except it works great on docs I originally authored, so it feels like either I need to treat those edits differently or for some reason that's no allowed via the API.

                • Re: 403 Unauthorized when using contents api to update a document's subject
                  jgoldhammer

                  Matt,

                  please try following approach:

                  - Read the document with a HTTP GET request /with path parameter contentId) via Jive REST API v3.14 → Content service

                  - Modify the subject on the json response of the first call! (and do not build up a new json)

                  - Update the document with a HTTP PUT request (with path parameter contentId) via Jive REST API v3.14 → Content service

                   

                  This makes sure that you only update the subject and do not modify the other fields by accident.

                   

                  Some more questions:

                  - Which user (especially which system permissions) is used to make this action?

                  - Can you make sure that you only update content of type document? You have an hardcoded value document in your json request..

                   

                  Maybe this helps.

                   

                  Thanks

                  Jens

                    • Re: 403 Unauthorized when using contents api to update a document's subject
                      mtdimich

                      Thanks Jens, I'll give it a try and let you know if it helps.

                      • Re: 403 Unauthorized when using contents api to update a document's subject
                        mtdimich

                        Hey Jens,

                         

                        Thanks again for this.  It did work to use the response from the GET, modify the subject and PUT to the same endpoint.  I had done that right away per the documentation but I think I had mixed up the endpoints. Here's the code update I made in case it's useful to someone. Any idea why building the minimum update request would cause that behavior?  I took the content straight from the response of the GET.

                         

                        Either way, thanks again!

                         

                        def updateDocSubject(token, jiveDocId, host):
                            import json, urllib2,urllib,datetime, httplib
                            from pprint import pprint
                            print "***********************"
                            print "Updating doc with contentID: " + jiveDocId
                            current_url = host + '/api/core/v3/contents/'+ jiveDocId
                            print "Retrieving Doc: " + current_url
                            req = urllib2.Request(current_url)
                            req.add_header('Accept', 'application/json')
                            req.add_header('Authorization','Bearer ' + token)
                            page = urllib2.urlopen(req)
                            payload = page.read()
                        
                            obj=json.loads(payload)
                        
                        
                            print "Retrieved doc:" + obj["subject"]
                            print "Found ref url of " + obj["resources"]["self"]["ref"]
                            print "Found HTML  obj["resources"]["html"]["ref"]
                            print "Capable of methods " + ",".join(obj["resources"]["self"]["allowed"])
                            print "Author: " + obj["author"]["displayName"]
                            if "REDACTED Text" not in obj["subject"]:
                                newSubject = obj["subject"].replace("redacted", "redacted2")
                                obj["subject"] = newSubject
                                print "Setting the new Doc Title to: " + obj["subject"]
                                put_url = obj["resources"]["self"]["ref"]
                                print 'updating...' + put_url
                                putRequest=urllib2.Request(put_url)
                                putRequest.add_header('Content-Type', 'application/json')
                                putRequest.add_header('Authorization','Bearer ' + token)
                                putRequest.get_method = lambda: 'PUT'
                                print "sending request..."
                                try:
                                    response = urllib2.urlopen(putRequest, data=json.dumps(obj))
                                    if response.code == 200:
                                        print "Update Successful"
                                        return 0
                                except urllib2.HTTPError, e:
                                    print "Problem updating data sheet"
                                    print ('HTTPError = ' + str(e.code))
                                    print ('HTTPError = ' + str(e.reason))
                                    # raise
                                except urllib2.URLError, e:
                                    print "Problem updating data sheet"
                                    print ('URLError = ' + str(e.reason))
                                    # raise
                                except httplib.HTTPException, e:
                                    print "Problem updating data sheet"
                                    print ('HTTPException')
                                    # raise
                                except Exception:
                                    import traceback
                                    print ('generic exception: ' + traceback.format_exc())
                                    raise
                            else:
                                print "Update not required"
                                return 2
                            return 1
                        
                    • Re: 403 Unauthorized when using contents api to update a document's subject
                      mtdimich

                      Also - I added my code to the post.  Thanks for taking a look!

                      • Re: 403 Unauthorized when using contents api to update a document's subject
                        mtdimich

                        Also, sorry for not replying to your comments in the thread, the site through an auth error and said I could reply directly to your comments.

                        • Re: 403 Unauthorized when using contents api to update a document's subject
                          gsvivek

                          It's possible that the oAuth token you generated does not have the necessary privilege that you would have when you log in from the front end.

                           

                          Look at Step 5 here: How To Use OAuth 2.0 for REST API Calls to see if you are passing a user with the necessary privilege to generate the token. Alternatively, you can just pass your Jive credentials as basic auth in the header.