在搜索代码之前,一定要阅读文档。 http://docs.djangoproject.com/en/1.2/topics/auth/#other-authentication-sources 也读取提供的Django源代码。
你想创造三件事情。
捕获令牌的中间件。这是大部分工作发生的地方。它检查令牌,验证它(通过与身份管理器确认),然后登录用户。
身份验证后端查找用户。这是一个存根。它所做的只是根据需要创建用户。您的身份管理器有详细信息。您只是在Django的本地数据库上缓存当前版本的用户。
这里是中间件(编辑)。
from django.contrib.auth import authenticate, login
class CookieMiddleware(object):
"""Authentication Middleware for OpenAM using a cookie with a token.
Backend will get user.
"""
def process_request(self, request):
if not hasattr(request, 'user'):
raise ImproperlyConfigured()
if "thecookiename" not in request.COOKIES:
return
token= request.COOKIES["thecookiename"]
# REST request to OpenAM server for user attributes.
token, attribute, role = identity_manager.get_attributes(token)
user = authenticate(remote_user=attribute['uid'][0])
request.user = user
login(request, user)
的identity_manager.get_attributes
是一个单独的类,我们写信给验证令牌和从IM源获取用户的详细信息。当然,这是为了测试目的而被嘲笑的。
这里有一个后端(编辑)
class Backend(RemoteUserBackend):
def authenticate(**credentials):
"""We could authenticate the token by checking with OpenAM
Server. We don't do that here, instead we trust the middleware to do it.
"""
try:
user= User.objects.get(username=credentials['remote_user'])
except User.DoesNotExist:
user= User.objects.create(username=credentials['remote_user'])
# Here is a good place to map roles to Django Group instances or other features.
return user
这不会发生重大变化的认证或授权的装饰。
为了确保这一点,我们实际上刷新了我们的 身份管理器中的用户和组信息。
请注意,中间件会针对每个请求运行。有时候,将令牌传递给支持的方法authenticate
是可以的。如果令牌存在于本地用户数据库中,则可以在不联系身份管理器的情况下继续进行请求。
然而,我们在身份管理器中有复杂的规则和超时,所以我们必须检查每个标记以确保它是有效的。一旦中间件确定令牌有效,我们就可以允许后端执行任何额外的处理。
这不是我们生活的代码(这是一个有点太复杂,使一个很好的例子。)
后端可以简化用户,_ = User.objects.get_or_create(用户名=凭证[“REMOTE_USER”] ) – 2013-03-07 23:43:10