我使用龙卷风文档中提供的身份验证系统作为示例。当我想将它与AngularJS结合使用时 - AngularJS会抱怨跨源请求。
如何结合Tornado的身份验证系统和AngularJS?
身份验证处理程序
class BaseHandler(tornado.web.RequestHandler):
def get_current_user(self):
user_json = self.get_secure_cookie("my_app")
if not user_json: return None
return tornado.escape.json_decode(user_json)
class AuthGoogleLoginHandler(BaseHandler, tornado.auth.GoogleMixin):
'''
The Google OAuth Handler.
The `AuthGoogleLoginHandler` redirects each accepted user
to the index /.
'''
@gen.coroutine
def get(self):
if self.get_argument("openid.mode", None):
user = yield self.get_authenticated_user()
self.set_secure_cookie("my_app",
tornado.escape.json_encode(user))
self.current_user = user
email = user.get('email')
try:
usr = models.User.objects.get(email=email)
except mongoengine.DoesNotExist as e:
# there is no user with the wished email address
# let's create a new one.
new_user = models.User()
new_user.email = user.get('email')
new_user.first_name = user.get('first_name')
new_user.last_name = user.get('last_name')
new_user.locale = user.get('locale')
new_user.save()
self.redirect(self.get_argument('next', '/'))
return
self.authenticate_redirect()
ProfileHandler
class ProfileHandler(BaseHandler):
'''
returns the username of the current user so that it can be used by the AngularJS Templates
'''
@tornado.web.authenticated
def get(self):
if not self.get_current_user():
response = json.dumps({"userdetails":"my dummy user"})
self.write(response)
# user actually exists
else:
response = json.dumps({"userdetails":self.get_current_user()})
self.write(response)
答案 0 :(得分:1)
我认为您需要启用跨源请求,wiki CORS以获取更多信息:
class BaseHandler(tornado.web.RequestHandler):
def set_default_headers(self):
self.set_header("Access-Control-Allow-Origin", "http://yoursite.com")
另外,我花了一段时间才弄清楚这一点,但是当Angular与RESTful API交互时,正常会话不起作用。您想要的是在每个请求的HTTP Authorization标头中发送凭据。看看这个:
http://wemadeyoulook.at/en/blog/implementing-basic-http-authentication-http-requests-angular/
希望有所帮助!