EzDevInfo.com

python-openid

OpenID library for Python

Errors with python-openid and Google Apps Federated Login

UPDATE

I managed to get it working although I'm not quite sure why ;) It seems like python-openid uses a POST-request to issue the openid mode=associate and for some reason Google doesn't like that. When I patched python-openid to use a GET-request instead everything worked fine. I'll continue my investigation and update this post when I have more information. Below is the diff for my change.

--- python-openid-2.2.1.orig/openid/consumer/consumer.py
+++ python-openid-2.2.1/openid/consumer/consumer.py
@@ -229,6 +229,20 @@
     # Process response in separate function that can be shared by async code.
     return _httpResponseToMessage(resp, server_url)

+def makeKVGet(request_message, server_url):
+    """Make a Direct Request to an OpenID Provider and return the
+    result as a Message object.
+
+    @raises openid.fetchers.HTTPFetchingError: if an error is
+        encountered in making the HTTP post.
+
+    @rtype: L{openid.message.Message}
+    """
+    # XXX: TESTME
+    resp = fetchers.fetch(request_message.toURL(server_url))
+
+    # Process response in separate function that can be shared by async code.
+    return _httpResponseToMessage(resp, server_url)

 def _httpResponseToMessage(response, server_url):
     """Adapt a POST response to a Message.
@@ -682,6 +696,7 @@
         return True

     _makeKVPost = staticmethod(makeKVPost)
+    _makeKVGet = staticmethod(makeKVGet)

     def _checkSetupNeeded(self, message):
         """Check an id_res message to see if it is a
@@ -1258,7 +1273,7 @@
             endpoint, assoc_type, session_type)

         try:
-            response = self._makeKVPost(args, endpoint.server_url)
+            response = self._makeKVGet(args, endpoint.server_url)
         except fetchers.HTTPFetchingError, why:
             oidutil.log('openid.associate request failed: %s' % (why[0],))
             return None

Old question, preserved for context

I've been trying desperately to get the trac-authopenid plugin to work but with no luck.

We use Google Apps Premier at work so I'm trying to get openid auth working with that. I think I've set up all the required stuff (XRDS and such) as far as google is concerned and I've gotten it to work fine with apache2 + mod-auth-openid as well as using it on other sites (SO for example).

But I can't seem to get it to work with trac-authopenid. I get redirected (via a form post, not a redirect as usual) to Google where I get to log in but when I return the plugin simply states that validation failed.

If i turn on debug logging I get this (I've replaced our domain name with example.com)

2010-01-27 12:21:15,811 Trac[authopenid] DEBUG: beginning OpenID authentication.
2010-01-27 12:21:16,866 Trac[authopenid] DEBUG: kvToSeq warning: Line 1 does not contain a colon: '<HTML>\n<HEAD>\n<TITLE>Not Implemented</TITLE>\n</HEAD>\n
2010-01-27 12:21:16,866 Trac[authopenid] DEBUG: kvToSeq warning: Line 2 does not contain a colon: '<HTML>\n<HEAD>\n<TITLE>Not Implemented</TITLE>\n</HEAD>\n
2010-01-27 12:21:16,866 Trac[authopenid] DEBUG: kvToSeq warning: Line 3 does not contain a colon: '<HTML>\n<HEAD>\n<TITLE>Not Implemented</TITLE>\n</HEAD>\n
    ... snipped, repeats until line 9...
2010-01-27 12:21:16,867 Trac[authopenid] DEBUG: openid.associate request failed: bad status code from server https://www.google.com/a/example.com/o8/ud?be=
2010-01-27 12:21:16,868 Trac[authopenid] DEBUG: _get_trust_root href: /trac
2010-01-27 12:21:16,868 Trac[authopenid] DEBUG: _get_trust_root abs_href: https://developer.example.com/trac
2010-01-27 12:21:16,868 Trac[authopenid] DEBUG: _get_trust_root href: /trac
2010-01-27 12:21:16,868 Trac[authopenid] DEBUG: _get_trust_root abs_href: https://developer.example.com/trac
2010-01-27 12:21:16,869 Trac[authopenid] DEBUG: Generated checkid_setup request to https://www.google.com/a/example.com/o8/ud?be=o8 using stateless mode.
2010-01-27 12:21:18,068 Trac[main] DEBUG: Dispatching <Request "GET u'/openidprocess'">
2010-01-27 12:21:18,075 Trac[session] DEBUG: Retrieving session for ID '25a842642693232301aad341'
2010-01-27 12:21:18,078 Trac[authopenid] DEBUG: Error attempting to use stored discovery information: <openid.consumer.consumer.TypeURIMismatch: Required ty
2010-01-27 12:21:18,078 Trac[authopenid] DEBUG: Attempting discovery to verify endpoint
2010-01-27 12:21:18,078 Trac[authopenid] DEBUG: Performing discovery on http://example.com/openid?id=113663311178245814720
2010-01-27 12:21:18,121 Trac[authopenid] DEBUG: Received id_res response from https://www.google.com/a/example.com/o8/ud?be=o8 using association AOQobUefon
2010-01-27 12:21:18,121 Trac[authopenid] DEBUG: Using OpenID check_authentication
2010-01-27 12:21:18,121 Trac[authopenid] DEBUG: op_endpoint
2010-01-27 12:21:18,121 Trac[authopenid] DEBUG: claimed_id
2010-01-27 12:21:18,121 Trac[authopenid] DEBUG: identity
2010-01-27 12:21:18,122 Trac[authopenid] DEBUG: return_to
2010-01-27 12:21:18,122 Trac[authopenid] DEBUG: response_nonce
2010-01-27 12:21:18,122 Trac[authopenid] DEBUG: assoc_handle
2010-01-27 12:21:18,576 Trac[authopenid] DEBUG: kvToSeq warning: Line 1 does not contain a colon: '<HTML>\n<HEAD>\n<TITLE>Not Implemented</TITLE>\n</HEAD>\n
2010-01-27 12:21:18,577 Trac[authopenid] DEBUG: kvToSeq warning: Line 2 does not contain a colon: '<HTML>\n<HEAD>\n<TITLE>Not Implemented</TITLE>\n</HEAD>\n
2010-01-27 12:21:18,577 Trac[authopenid] DEBUG: kvToSeq warning: Line 3 does not contain a colon: '<HTML>\n<HEAD>\n<TITLE>Not Implemented</TITLE>\n</HEAD>\n
    ... snipped, repeats until line 9...
2010-01-27 12:21:18,578 Trac[authopenid] DEBUG: check_authentication failed: bad status code from server https://www.google.com/a/example.com/o8/ud?be=o8: 501

I tried writing some code directly against the python-openid library in order to narrow it down a little but I'm clueless. I've been able to reproduce the error with this code snippet:

from openid.store.memstore import MemoryStore
from openid.consumer import consumer

session = { 'id' : 'foobar' }
store = MemoryStore()
consumer = consumer.Consumer(session, store)
consumer.begin('https://www.google.com/accounts/o8/site-xrds?hd=example.com')

Which consistently outputs

kvToSeq warning: Line 1 does not contain a colon: '<HTML>\n<HEAD>\n<TITLE>Not Implemented</TITLE>\n</HEAD>\n<BODY BGCOLOR="#FFFFFF" TEXT="#000000">\n<H1>Not Implemented</H1>\n<H2>Error 501</H2>\n</BODY>\n</HTML>\n'
kvToSeq warning: Line 2 does not contain a colon: '<HTML>\n<HEAD>\n<TITLE>Not Implemented</TITLE>\n</HEAD>\n<BODY BGCOLOR="#FFFFFF" TEXT="#000000">\n<H1>Not Implemented</H1>\n<H2>Error 501</H2>\n</BODY>\n</HTML>\n'
kvToSeq warning: Line 3 does not contain a colon: '<HTML>\n<HEAD>\n<TITLE>Not Implemented</TITLE>\n</HEAD>\n<BODY BGCOLOR="#FFFFFF" TEXT="#000000">\n<H1>Not Implemented</H1>\n<H2>Error 501</H2>\n</BODY>\n</HTML>\n'
... snip ...
openid.associate request failed: bad status code from server https://www.google.com/a/example.com/o8/ud?be=o8: 501

Some version numbers:

Python 2.6.2
trac-authopenid 0.1.6
python-openid 2.2.1

I'm at a complete loss and I could really use some help.


Source: (StackOverflow)

openid in pylons (not using authkit)

So I'm trying to authenticate users on a Pylons web application using openid. I don't want to use authkit, seeing as it is no longer maintained.

I'm currently trying to use python-openid (available from git at http://github.com/openid/python-openid) and having a hard time with it. The pylons framework isn't making it easy for me to interact with the python-openid classes, which are basically looking for instances of python's HTTPServer and SimpleCookie classes...

Any assistance available? Has anyone solved this problem? TIA.


Source: (StackOverflow)

Advertisements

Reliable method of getting username or realname from OpenID

The site I am developing supports sign-in with the default SimpleOpenIDSelector providers (the same providers that are listed on stackoverflow login page). While it works for simple sign-ins, my AX-required requests remain unfulfilled. For example, Blogger does not disclose first/last/friendly name through AX.

How can I ensure that I get a string that is the user's preferred name? What are the possible workarounds or alternatives or standard methods of dealing with this?

I am using the latest python-openid library.


Source: (StackOverflow)

Import error with python-openid in django

I have a problem with using python-openid in my django project. If import anything from openid module I receive an exception in a runtime.

Environment:


Request Method: GET
Request URL: http://127.0.0.1:8000/

Django Version: 1.4
Python Version: 2.7.1
Installed Applications:
('django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.messages',
 'django.contrib.staticfiles')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware')


Traceback:
File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in get_response
  101.                             request.path_info)
File "/Library/Python/2.7/site-packages/django/core/urlresolvers.py" in resolve
  298.             for pattern in self.url_patterns:
File "/Library/Python/2.7/site-packages/django/core/urlresolvers.py" in url_patterns
  328.         patterns = getattr(self.urlconf_module, "urlpatterns",               self.urlconf_module)
  File "/Library/Python/2.7/site-packages/django/core/urlresolvers.py" in urlconf_module
    323.             self._urlconf_module = import_module(self.urlconf_name)
  File "/Library/Python/2.7/site-packages/django/utils/importlib.py" in import_module
    35.     __import__(name)
  File "/Users/air/Desktop/givemecoin/givemecoin/urls.py" in <module>
    2. from givemecoin.views import hello, register, new_user_welcome, profile, payment
  File "/Users/air/Desktop/givemecoin/givemecoin/views.py" in <module>
    17. from openid.store.filestore import FileOpenIDStore

  Exception Type: ImportError at /
  Exception Value: No module named consumer.consumer

But python-openid is correctly installed in '/Library/Python/2.7/site-packages' and this dir in python path. And I can import openid module from command-line python.

Python 2.7.1, Mac OS X 10.7, python-openid 2.2.5.


Source: (StackOverflow)

FailureResponse on otherwise successful OpenID login: Server denied check_authentication

I'm testing OpenID authentication using python-openid on webpy's development web server. Through Yahoo! and myOpenID, I keep getting a failure response with the message Server denied check_authentication. The strange part is, I also receive the correct openid.identity.

The same type of authentication works fine with Google (@ https://www.google.com/accounts/o8/ud...). On one hand, that gives me confidence that I'm doing something right, but on the other hand, the inconsistency confuses me.

return_to & trust_root are both localhost:8080, which may have something to do with it.

Here's the code I use to send the user to Yahoo! to authenticate:

  def POST(self):
    post_data = web.input()
    if post_data.has_key('openid_identifier'):
      openid_identifier = post_data.get('openid_identifier')
      c = Consumer(session, openid.store.memstore.MemoryStore())
      auth = c.begin(openid_identifier)
      auth_url = auth.redirectURL('http://localhost:8080', return_to='http://localhost:8080/authenticate')
      raise web.seeother(auth_url)
    return post_data

auth_url in this case is set to (formatted for easy reading):

https://open.login.yahooapis.com/openid/op/auth?
openid.assoc_handle=cYSO3wJSjQa3ewmRpaQz3YodzqjosP1ta.4TVzumqlLpAFM7oWci6K9bMKG4uuqZ.5m.fY7Wp8BWfQ1eR_soHWpJ6gCsKtxi_7Bqi22T5RUcMIuQBVjpGFSjc_kRY2k-&
openid.claimed_id=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&
openid.identity=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&
openid.mode=checkid_setup&
openid.ns=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0&openid.realm=http%3A%2F%2Flocalhost%3A8080&
openid.return_to=http%3A%2F%2Flocalhost%3A8080%2Fauthenticate%3Fjanrain_nonce%3D2010-10-08T02%253A56%253A04ZrxAI

Here's what the handler looks like at the return URL:

  def GET(self):
    data = web.input()
    c = Consumer(session, openid.store.memstore.MemoryStore())
    result = c.complete(dict(data), current_url='http://localhost:8080/authenticate')
    if result.status == SUCCESS:
      openid_identity = data.get('openid.identity')
      ...
    render = web.template.render('templates/', base='layout')
    return render.error(...)

result gets set to <openid.consumer.consumer.FailureResponse id=None message='Server denied check_authentication'>, and data (the query parameters on the return) are set like this:

<Storage {'openid.op_endpoint': u'https://open.login.yahooapis.com/openid/op/auth', 
'openid.sig': u'yCHffpHs2Whtw9p1gPzC+ToQJ0k=', 
'openid.ns': u'http://specs.openid.net/auth/2.0', 
'janrain_nonce': u'2010-10-08T02:56:04ZrxAIWh', 
'openid.return_to': u'http://localhost:8080/authenticate?janrain_nonce=2010-10-08T02%3A56%3A04ZrxAIWh', 
'openid.pape.auth_level.nist': u'0', 
'openid.claimed_id': u'https://me.yahoo.com/a/d3eEQZAWydfmtDwaGB2vBEVU4vIMLsez#1ac56', 
'openid.mode': u'id_res', 
'openid.realm': u'http://localhost:8080', 
'openid.response_nonce': u'2010-10-08T02:55:52ZRLNmEd7aWiaGWjHfhqEQs2Fxj3.nXdwciA--', 
'openid.signed': u'assoc_handle,claimed_id,identity,mode,ns,op_endpoint,response_nonce,return_to,signed,pape.auth_level.nist', 
'openid.identity': u'https://me.yahoo.com/a/d3eEQZAWydfmtDwaGB2vBEVU4vIMLsez', 
'openid.assoc_handle': u'cYSO3wJSjQa3ewmRpaQz3YodzqjosP1ta.4TVzumqlLpAFM7oWci6K9bMKG4uuqZ.5m.fY7Wp8BWfQ1eR_soHWpJ6gCsKtxi_7Bqi22T5RUcMIuQBVjpGFSjc_kRY2k-'}>

That sure doesn't look like a failure response to me. Notice that openid.identity is set. And yes, that is my OpenID identity on Yahoo!.

I'm not sure where to take this from here. Any words of advice?


Source: (StackOverflow)

Alternative for python-daemon on Windows

I'm trying to use a python library (python_openid) which depends upon python-daemon. The latter does not appear to work on Windows.

What alternatives have I got (short of installing Linux)?


Source: (StackOverflow)

Problems with Flask-openid in Python 3

I am trying to get Flask-openid working, but keep hitting this error when trying to log in

ValueError: Unicode strings with encoding declaration are not supported. Please use bytes input or XML fragments without declaration.

It happens when using this function

oid.try_login(openid, ask_for=['email', 'fullname', 'nickname'])

This is where the function is used:

@app.route('/login', methods=['GET', 'POST'])
@oid.loginhandler
def login():
    """Does the login via OpenID.  Has to call into `oid.try_login`
    to start the OpenID machinery.
    """
    # if we are already logged in, go back to were we came from
    if g.user is not None:
        app.logger.info('logged-in: ' + oid.get_next_url())
        return redirect(oid.get_next_url())
    if request.method == 'POST':
        openid = request.form.get('openid_identifier')
        if openid:
            app.logger.info(request.form)
            app.logger.info('logging-in: ' + oid.get_next_url())
            return oid.try_login(openid, ask_for=['email', 'fullname',
                                                  'nickname'])
    app.logger.info('not-logged-in: ' + oid.get_next_url())
    return render_template('login.html', next=oid.get_next_url(),
                           error=oid.fetch_error())

and actually seems to be an issue with lxml that Flask-openid uses:

  File "C:\Python33\lib\site-packages\openid\yadis\etxrd.py", line 69, in parseXRDS
    element = ElementTree.XML(text)
  File "lxml.etree.pyx", line 3012, in lxml.etree.XML (src\lxml\lxml.etree.c:67876) 
  File "parser.pxi", line 1781, in lxml.etree._parseMemoryDocument (src\lxml\lxml.etree.c:102435)

I have tried a couple of example projects on github, but they all have the same issue. Is there some way I can get Flask-openid to work in Python 3?


Source: (StackOverflow)

Yahoo! OpenID doesn't include Attribute Exchange info (using python-openid)

I'm using python-openid to successfully connect my python based site with OpenID. It works great with Google and it works with Yahoo! but with Yahoo! the Attribute Exchange doesn't seem to work. I only ever get the email address. firstname, lastname and country is always blank. I know the Yahoo! account (by that email address) has a firstname and lastname defined.

I use these parameters amongst the normal OpenID ones:

    'openid.ns.ax':'http://openid.net/srv/ax/1.0',
    'openid.ax.mode':'fetch_request',
    'openid.ax.required':'firstname,lastname,email,country',
    'openid.ax.type.firstname':'http://axschema.org/namePerson/first',
    'openid.ax.type.lastname':'http://axschema.org/namePerson/last',
    'openid.ax.type.email':'http://axschema.org/contact/email',
    'openid.ax.type.country':'http://axschema.org/contact/country/home',

Searching I found this answer but I'm not familiar with the PHP framework and its use of "counts". There is no such thing in the python-openid framework.


Source: (StackOverflow)