Frage

I am using the authentication system provided as an example in the tornado documentation. When I want to combine it with AngularJS - AngularJS complains about a Cross-Origin Request.

How can I combine Tornado's authentication system and AngularJS?

Authentication Handlers

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)
War es hilfreich?

Lösung

I think you need to enable a cross origin request, wiki CORS for more info:

class BaseHandler(tornado.web.RequestHandler):
    def set_default_headers(self):
        self.set_header("Access-Control-Allow-Origin", "http://yoursite.com")

Also, it took me a while to figure this out, but normal sessions don't work when Angular is interacting with a RESTful API. What you want is to send credentials in the HTTP Authorisation header on each request. Check this out:

http://wemadeyoulook.at/en/blog/implementing-basic-http-authentication-http-requests-angular/

Hope that helps a bit!

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top