RestAPI OAuth-Authentifizierung mit requests_oauthlib.OAuth1Session schlägt fehl

625 views
Skip to first unread message

Richard Neumann

unread,
Apr 4, 2014, 7:45:24 AM4/4/14
to immobilienscou...@googlegroups.com
Hallo zusammen,

ich implementiere gerade eine Schnittstelle für die RestAPI in Python 2.7.
Dazu benutze ich das Modul requests_oauthlib.
Wenn ich jedoch eine Session mit meinen Sandbox-Credentials erstelle und versuche eine Verbindung zur API herzustellen, bekomme ich einen ERROR 401 zurück.
Hier ein Auszug aus dem von mir verwendeten Code:

from requests_oauthlib import OAuth1Session

class IS24RestClient():
    __config
= None
   
   
def __init__(self):
       
self.__call_service()
       
   
def __call_service(self):#, url, request="", requestMethod="GET", multipart=''):
        session
= OAuth1Session(Config.CLIENT_KEY,
                                client_secret
=Config.CLIENT_SECRET,
                                resource_owner_key
=Config.RESOURCE_OWNER_KEY,
                                resource_owner_secret
=Config.RESOURCE_OWNER_SECRET)
       
        url
= Config.BASEURL+'user/testkunde/realestate'
       
print('URL: ' + url)
       
        response
= session.get(url)
       
print('RESPONSE: ' + str(response))Code hier eingeben...

Für Tipps zur Beseitigung des Problems wäre ich Dankbar.

Viele Grüße

Richard Neumann

Fabian Mielke | Team API

unread,
Apr 5, 2014, 10:46:59 PM4/5/14
to immobilienscou...@googlegroups.com
Hello Richard,

you have to play three legged oAuth for some requests. Before you do e.g. POST/PUT Real Estate requests against our API, you have to authenticate your application. How to do that, you can find an article in our Wiki: http://developerwiki.immobilienscout24.de/wiki/Customer-website_Tutorial#Authentification_and_Authorisation.

Regards, Fabian
Message has been deleted
Message has been deleted

Richard Neumann

unread,
Apr 7, 2014, 7:14:02 AM4/7/14
to immobilienscou...@googlegroups.com
Hi Fabian,

thanks for your swift reply.
I am already using the three-legged authentication with the aforementioned framework.
The token is stored in the Config.RESOURCE_OWNER_KEY variable and the respective key is stored in the Config.RESOURCE_OWNER_SECRET variable, which is handed over for signing by the default HMAC function to the framework.
Unfortunately this still does not work. Here's a full dump of the respective module, so that you can see what's inside the config class:
'''
Created on 31.03.2014

@author: Richard Neumann
'''

#
# TODO: Merge into interfaces.is24
#

import urllib
from requests_oauthlib import OAuth1Session

class Config():
    BASEURL
= 'http://rest.sandbox-immobilienscout24.de/restapi/api/offer/v1.0/'
    CLIENT_KEY
= 'testzugang[..]'
    CLIENT_SECRET
= 'ChKc[..]'
    RESOURCE_OWNER_KEY
= 'c4364b3[..]'
    RESOURCE_OWNER_SECRET
= 'U%2FtUlp[..]'


class IS24RestClient():
    __config
= None
   
   
def __init__(self):
       
self.__call_service()
       
   
def __call_service(self):

        session
= OAuth1Session(Config.CLIENT_KEY,
                                client_secret
=Config.CLIENT_SECRET,
                                resource_owner_key
=Config.RESOURCE_OWNER_KEY,
                                resource_owner_secret
=Config.RESOURCE_OWNER_SECRET)
       
        url
= Config.BASEURL+'user/testkunde/realestate'
       
print('URL: ' + url)
       
        response
= session.get(url)
       
print('RESPONSE: ' + str(response))



This is what I get, when I call the API with my respective credentials provided by IS24:
Python 2.7.5 (default, Feb 19 2014, 13:47:28)
[GCC 4.8.2 20131212 (Red Hat 4.8.2-7)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from restapi import IS24RestClient
>>> rc = IS24RestClient()
URL
: http://rest.sandbox-immobilienscout24.de/restapi/api/offer/v1.0/user/testkunde/realestate
RESPONSE
: <Response [401]>
>>>



Since I still get an ERROR 401, I think, that there's something wrong with my credentials or the signing.

Maybe you can give me another hint.


Best regards,

Richard

Fabian Mielke | Team API

unread,
Apr 7, 2014, 10:59:41 AM4/7/14
to immobilienscou...@googlegroups.com
Hallo Richard,

keinen Schimmer warum ich dir auf englisch geantwortet habe. Meinetwegen können wir auf deutsch weitermachen ;)

Ich bin immer noch der Meinung, dass es an der korrekten Authentifizierung der Applikation liegt, denn dafür geben wir den 401er aus. Wenn Berechtigungen nicht stimmen, bekommst du in der Regel 403. Du kannst mir gerne deinen API-Key zusenden, ich überprüfe die Berechtigungen. 

Schicke mir dazu auch bitte deinen Usernamen mit dem du dich auf der Sandbox einloggst. Momentan versuchst du den Request mit "testkunde", ist dein Username wirklich "testkunde". Versuch es mal mit "me", wenn du auf der Sandbox eingeloggt bist.

Was für einen Request machst du? Schicke bitte mal URL, Header und Body.

Hast du deinen Request mal über den Playground versucht? Wie sieht es da aus?

MfG Fabian

Richard Neumann

unread,
Apr 9, 2014, 11:36:42 AM4/9/14
to immobilienscou...@googlegroups.com
Hallo Fabian,

danke für die Antwort und die Zugangsdaten. :-)
Ich hatte bis dato die Zugangsdaten einer Partnerfirma verwendet.
Da es mit dem requests_oauthlib Modul allgemeine Probleme zu geben scheint, habe ich nun rauth verwendet.
Bei dem folgenden Code:
'''
Created on 31.03.2014

@author: Richard Neumann
'''
#
# TODO: Merge into interfaces.is24
#
from rauth import OAuth1Service


class IS24RestClient():
    __config = None
   
    def __init__(self):
        self.__call_service()
       
    def __call_service(self):
       
        is24rest = OAuth1Service(
            name='is24rest',
            consumer_key='testzugang-homeinfoKey',
            consumer_secret='<veryverysecret>',
            request_token_url='http://rest.immobilienscout24.de/restapi/security/oauth/request_token',
            access_token_url='http://rest.immobilienscout24.de/restapi/security/oauth/access_token',
            authorize_url='http://rest.immobilienscout24.de/restapi/security/oauth/confirm_access',
            base_url='http://rest.immobilienscout24.de/restapi/api')

        request_token, request_token_secret = is24rest.get_request_token('oauth_callback=oob')
        print("\n\nFOO:\n")
        print(str(request_token) + ' / ' + str(request_token_secret))



bekomme ich nun folgende Rückmeldung:

homiectl: KeyError('Decoder failed to handle oauth_token with data as returned by provider. A different decoder may be needed. Provider returned: <html><head><title>Apache Tomcat/7.0.52 - Error report</title><style><!--H1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} H2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} H3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} BODY {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} B {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} P {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;}A {color : black;}A.name {color : black;}HR {color : #525D76;}--></style> </head><body><h1>HTTP Status 405 - </h1><HR size="1" noshade="noshade"><p><b>type</b> Status report</p><p><b>message</b> <u></u></p><p><b>description</b> <u>The specified HTTP method is not allowed for the requested resource.</u></p><HR size="1" noshade="noshade"><h3>Apache Tomcat/7.0.52</h3></body></html>',)
         
for help use --help

Das sieht schon 'besser' aus als zuvor. Aber der ERROR 405 irritiert mich noch und die Tatsache, dass das Decoding fehl schlägt.

Danke schonmal für deine Zeit.

Viele Grüße

Richard

Fabian Mielke | Team API

unread,
Apr 10, 2014, 8:44:08 AM4/10/14
to immobilienscou...@googlegroups.com
Hallo Richard,


MfG Fabian

Richard Neumann

unread,
Apr 16, 2014, 7:12:21 AM4/16/14
to immobilienscou...@googlegroups.com
Hallo Fabian,

nochmals Danke.
Das Wiki war mir bereits bekannt und ich habe mich bei der Authentifizierung meiner Software an diesem Leitfaden entlang gehangelt:
http://developerwiki.immobilienscout24.de/wiki/Authentication_Detailed
Mittlerweile bekomme ich auch über den Umweg mit der Benutzung eines Webbrowsers (und Bestätigen der Abfrage "

Eine Applikation möchte sich mit Ihrem Account verknüpfen")

einen OAuth-Verifier, mit dem ich dann ein Access-Token und ein Access-Token-Secret beziehen kann.
Allerdings kann ich mit dem Access-Token nicht wie beschrieben auf Ressourcen, wie beispielsweise:
http://rest.sandbox-immobilienscout24.de/restapi/api/account/v1.0/?_wadl&_type=xml
zugreifen. Ich bekomme hier einen ERROR 401.
Ein Beispiel zum Ablauf hier:
1) Beschaffen eines Access-Tokens
[neumannr@neumann-homeinfo homie]$ sudo /usr/local/sbin/homiectl -t goo
Request Token: 14524189-9998-4e1c-ae26-a7c4b0edf674
Request Token Secret: 06z92g2JucDWUZo5B7OCM9TszLSnzgwz4y3K5TyNt9OfNPobtNMzoFMJ2cyl0MELcd2Hqf9ib6qDpLIgJii/3gnZmH9TkVdmnC9g7XknlSY=
Visit https://rest.sandbox-immobilienscout24.de/restapi/security/oauth/confirm_access?oauth_token=14524189-9998-4e1c-ae26-a7c4b0edf674 in new browser window.
Enter oauth_verifier here: 6hYP6z
Access Token: 21b786bb-c784-4f60-a090-f1272d466295
Access Token Secret: GmvwP1wnmgPUpeYUNIWGR9GfDrr31W3pJ8R7V5DEWpWx+quWg8mHSs8EHVXmczocMmG0lyaJqP3VLXvuzdPb0V9KrgI4jGZtoj+obkrOpBw=
[neumannr@neumann-homeinfo homie]$

2) Versuch mit dem o.g. Acces-Token auf http://rest.sandbox-immobilienscout24.de/restapi/api/masterdata/v1.0/?_wadl&_type=xml zuzugreifen:
<Response [401]>

Viele Grüße

Richard

Richard Neumann

unread,
Apr 25, 2014, 5:55:35 AM4/25/14
to immobilienscou...@googlegroups.com
So, das Problem ist gelößt,

ich habe den Zugang nun mit einem anderen Link als http://rest.sandbox-immobilienscout24.de/restapi/api/masterdata/v1.0/?_wadl&_type=xml probiert, nämlich mit einem Testexposé von uns:
http://rest.sandbox-immobilienscout24.de/restapi/api/offer/v1.0/user/homeinfo.de/realestate/62409484
Und siehe da, es geht:

/usr/local/sbin/homiectl rest session
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<realestates:apartmentRent xmlns:ns2="http://rest.immobilienscout24.de/schema/platform/gis/1.0" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:common="http://rest.immobilienscout24.de/schema/common/1.0" xmlns:realestates="http://rest.immobilienscout24.de/schema/offer/realestates/1.0" id="62409484">
   
<externalId>1</externalId>
    <title>Testanzeige</
title>
   
<creationDate>2014-04-07T13:35:33.000+02:00</creationDate>
    <lastModificationDate>2014-04-24T13:54:13.000+02:00</
lastModificationDate>
   
<address>
       
<street>Melanchthtonstraße</street>
        <houseNumber>7</
houseNumber>
       
<postcode>30165</postcode>
        <city>Hannover</
city>
       
<wgs84Coordinate>
           
<latitude>52.39768</latitude>
            <longitude>9.72186</
longitude>
       
</wgs84Coordinate>
        <geoHierarchy>
            <continent>
                <geoCodeId>1</
geoCodeId>
               
<fullGeoCodeId>1</fullGeoCodeId>
            </
continent>
           
<country>
               
<geoCodeId>276</geoCodeId>
                <fullGeoCodeId>1276</
fullGeoCodeId>
           
</country>
            <region>
                <geoCodeId>9</
geoCodeId>
               
<fullGeoCodeId>1276009</fullGeoCodeId>
            </
region>
           
<city>
               
<geoCodeId>17</geoCodeId>
                <fullGeoCodeId>1276009017</
fullGeoCodeId>
           
</city>
            <quarter>
                <geoCodeId>60</
geoCodeId>
               
<fullGeoCodeId>1276009017060</fullGeoCodeId>
            </
quarter>
           
<neighbourhood>
               
<geoCodeId>3241001000215</geoCodeId>
            </
neighbourhood>
       
</geoHierarchy>
    </
address>
   
<realEstateState>ACTIVE</realEstateState>
    <groupNumber>1</
groupNumber>
   
<attachments xlink:href="http://rest.sandbox-immobilienscout24.de/restapi/api/offer/v1.0/user/homeinfo.de/realestate/62409484/attachment"/>
   
<showAddress>false</showAddress>
    <contact id="59391004"/
>
   
<common:publishChannels>
       
<publishChannel id="10000" title="ImmobilienScout24"/>
   
</common:publishChannels>
    <apartmentType>ROOF_STOREY</
apartmentType>
   
<floor>2</floor>
    <lift>false</
lift>
   
<energyCertificate>
       
<energyCertificateCreationDate>FROM_01_MAY_2014</energyCertificateCreationDate>
        <energyEfficiencyClass>E</
energyEfficiencyClass>
   
</energyCertificate>
    <cellar>YES</
cellar>
   
<handicappedAccessible>NOT_APPLICABLE</handicappedAccessible>
    <condition>NO_INFORMATION</
condition>
   
<constructionYearUnknown>false</constructionYearUnknown>
    <constructionYear>1337</
constructionYear>
   
<heatingTypeEnev2014>GAS_HEATING</heatingTypeEnev2014>
    <energySourcesEnev2014>
        <energySourceEnev2014>ACID_GAS</
energySourceEnev2014>
   
</energySourcesEnev2014>
    <buildingEnergyRatingType>ENERGY_REQUIRED</
buildingEnergyRatingType>
   
<thermalCharacteristic>123</thermalCharacteristic>
    <energyConsumptionContainsWarmWater>NOT_APPLICABLE</
energyConsumptionContainsWarmWater>
   
<numberOfFloors>2</numberOfFloors>
    <usableFloorSpace>60.00</
usableFloorSpace>
   
<numberOfBedRooms>1</numberOfBedRooms>
    <numberOfBathRooms>1</
numberOfBathRooms>
   
<guestToilet>NOT_APPLICABLE</guestToilet>
    <baseRent>100.00</
baseRent>
   
<totalRent>123.00</totalRent>
    <serviceCharge>32.00</
serviceCharge>
   
<heatingCosts>42.00</heatingCosts>
    <heatingCostsInServiceCharge>YES</
heatingCostsInServiceCharge>
   
<petsAllowed>NO_INFORMATION</petsAllowed>
    <useAsFlatshareRoom>YES</
useAsFlatshareRoom>
   
<livingSpace>60.00</livingSpace>
    <numberOfRooms>3</
numberOfRooms>
   
<energyPerformanceCertificate>true</energyPerformanceCertificate>
    <builtInKitchen>true</
builtInKitchen>
   
<balcony>false</balcony>
    <certificateOfEligibilityNeeded>false</
certificateOfEligibilityNeeded>
   
<garden>true</garden>
    <courtage>
        <hasCourtage>NO</
hasCourtage>
   
</courtage>
</
realestates:apartmentRent>


Warum ich allerdings nicht auf die WADL Datei zugreifen kann, erschließt sich mir nicht.
Reply all
Reply to author
Forward
0 new messages