ajkavanagh / pyramid_jwtauth

JSON Web Token (JWT) Auth plugin for Pyramid
12 stars 9 forks source link

method accessibility #1

Closed espretto closed 9 years ago

espretto commented 9 years ago

i wanted to configure JWTAuthenticationPolicy#challenge as my default forbidden view as suggested in the comments. also i wanted to create an endpoint for the user to request a token by logging in. after the convenient config.include('pyramid_jwtauth') however i found no way to access the authentication policy instance from within my views which led me to do it like this:

def main(global_config, **settings):
    config = Configurator(settings=settings)

    author_policy = ACLAuthorizationPolicy()
    config.set_authorization_policy(author_policy)

    authen_policy = JWTAuthenticationPolicy.from_settings(settings, prefix='jwtauth.')
    config.set_authentication_policy(authen_policy)
    config.registry.JWT = lambda claims: authen_policy.encode_jwt(None, claims)
    config.add_forbidden_view(lambda request: authen_policy.challenge(request))

    config.add_view('login', '/account/login/')
    config.scan(__name__)
    ...

@view_config(route_name='login')
def login(request):
    user = ...
    if user is not None and user.check_password(request.json_body['password']):
        return Response(request.registry.JWT({'sub': user.id}))
    raise HTTPForbidden()

i'm not sure about the cleanliness and security of this approach. also, if you could point to where your plugin becomes reusable in the context of OAuth2!? ultimitely i'd like to offer multiple options for the user to login and grant my application access to Google Drive and/or Dropbox.

ajkavanagh commented 9 years ago

Sorry about the delay in answering. I'm not entirely sure I understand your question, but if its about accessing the policy then I do this in my code:

from pyramid.interfaces import IAuthenticationPolicy

...

    policy = request.registry.queryUtility(IAuthenticationPolicy)
    claims = policy.get_claims(request)
    # if the token is not an auth login token then we got unauthorised.
    if 'aud' not in claims or claims['aud'] != auth_utils.AUTH_LOGIN_JWT_AUD:
        raise HTTPUnauthorized()

The `get_claims(request) method is a custom method on the JWT policy.

As to reusability, that I don't really know. As I said in the readme, I basically copied https://github.com/mozilla-services/pyramid_macauth and https://github.com/mozilla-services/macauthlib and made it work with http://github.com/progrium/pyjwt -- but when I first wrote it, I was brand new to Pyramid!

You could have a look at https://github.com/mozilla-services/pyramid_multiauth which says that it will stack IAuthenticationPolicy objects?

ajkavanagh commented 9 years ago

Closing as no further activity from requester.