Giter Site home page Giter Site logo

flask_cognito's Introduction

Flask-Cognito

Authenticate users based on AWS Cognito JWT.

Initialization

# configuration
app.config.update({
    'COGNITO_REGION': 'eu-central-1',
    'COGNITO_USERPOOL_ID': 'eu-central-1c3fea2',

    # optional
    'COGNITO_APP_CLIENT_ID': 'abcdef123456',  # client ID you wish to verify user is authenticated against
    'COGNITO_CHECK_TOKEN_EXPIRATION': False,  # disable token expiration checking for testing purposes
    'COGNITO_JWT_HEADER_NAME': 'X-MyApp-Authorization',
    'COGNITO_JWT_HEADER_PREFIX': 'Bearer',
})


# initialize extension
from flask_cognito import CognitoAuth
cogauth = CognitoAuth(app)

@cogauth.identity_handler
def lookup_cognito_user(payload):
    """Look up user in our database from Cognito JWT payload."""
    return User.query.filter(User.cognito_username == payload['username']).one_or_none()

Check Authentication

from flask_cognito import cognito_auth_required, current_user, current_cognito_jwt

@route('/api/private')
@cognito_auth_required
def api_private():
    # user must have valid cognito access or ID token in header
    # (accessToken is recommended - not as much personal information contained inside as with idToken)
    return jsonify({
        'cognito_username': current_cognito_jwt['username'],   # from cognito pool
        'user_id': current_user.id,   # from your database
    })

Restrict access by Cognito Group

from flask_cognito import cognito_auth_required, current_user, current_cognito_jwt

@route('/api/foo')
@cognito_auth_required
@cognito_group_permissions(['admin','developer'])
def api_private():
    # user must belongs to "admin" or "developer" groups
    return jsonify({
        'foo': "bar"
    })

Acknowledgements

flask_cognito's People

Contributors

aaronbrown1988 avatar adamszeptycki avatar antdking avatar cdominguezg avatar daniel-panhead avatar dependabot[bot] avatar iamgoinghomenow avatar itsakmak avatar maquchizi avatar mordigrip avatar nicokuyum avatar revmischa avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

flask_cognito's Issues

Broken Pypi link

Just to let you know, the homepage link on Pypi is broken. It points to: https://github.com/jetbridge/flask-cognito. Maybe you should also put a banner in the readme to point to Pypi?
Keep up the good work, cheers!

Using Flask_Cognito with add_url_rule()

Hi am very new to flask. How can one use this library with the add_url_rule() method for authentication?

app.add_url_rule(
'/example', #the endpoint
view_func=GraphQLView.as_view( #setting the view function
'lta',
#we set the schema that we generate
schema=schema,
#we say that we do want to use graphqli interface
graphiql=True))

Cognito with API keys

Hi,

Thank you for this helpful package.

I'm trying to integrate an API that wants to use the same endpoints as the web application does. Currently, with the auth required decorator, these methods expect a certain authentication header to be sent, and that to be valid with Cognito. Is there a way I can bypass the decorator by validating the API key instead of the authentication header?

Thanks

Request for a tutorial/updated readme

Hey, I came across flask_cognito and it seems like a really interesting and good project.

But, as a beginner, it is a bit complicated to understand how this package should be used.

For example: In the readme there is information about initialization with the following code:

@cogauth.identity_handler
def lookup_cognito_user(payload):
    """Look up user in our database from Cognito JWT payload."""
    return User.query.filter(User.cognito_username == payload['username']).one_or_none()

Here, it is really confusing and difficult to understand from where the User comes into play and also what the payload is. I am assuming it is a basic user model (as shown in this tutorial: https://realpython.com/token-based-authentication-with-flask/).

So, it would be great if you can update the readme to include kind of a step-by-step walkthrough.

If there is already an existing tutorial for this, could you please point me to it?

Thanks & Cheers!

Add a license

Hello,
Thanks for the repo, it is indeed very useful!

Have you considered adding a license such as MIT?

It would allow the usage of the library in projects which need consent from the owners to use them.

cognito_group_permissions not working

I'm trying to use the cognito_group_permissions decorator but isn't working...

Traceback (most recent call last):
File "main.py", line 5, in
from flask_cognito import CognitoAuth, cognito_group_permissions
ImportError: cannot import name 'cognito_group_permissions' from 'flask_cognito' (C:\Users\Cairo\anaconda3\envs\salt\lib\site-packages\flask_cognito.py)

Disable authorization during development

Hello!

Is there a flag or way to disable Authorization @cognito_auth_required globally during development? I don't want to remove all the decorators while testing on the postman.

Flask-cognito Error

Hi,
I am trying to Implement User Authentication in Flask using Amazon Cognito.
I am using python 3.9 and installed flask and flask-cognito

I'm encountering an issue while using flask_cognito in my Flask app. When running the app (python app.py), I'm getting the following ImportError:
ImportError: cannot import name '_request_ctx_stack' from 'flask' (/path/to/venv/lib/python3.9/site-packages/flask/init.py)

Any insights or solutions would be greatly appreciated.
Thank you!

Failed Authentication is overly verbose

Failed authentication attempts get logged at the Error level, with no way to configure it outside of disabling logging for the entire package.

Please provide a way to configure the Log Level for Auth issues, or set to Info level by default.

The rationale for this would be that an API Provider would not need to action a user entering their credentials incorrectly.


Lines affected:

To retain the exception details in the error, you can include it via exc_info:

log.info("Authentication Failed", exc_info=e)
log.info("Authentication Failed", exc_info=True)

COGNITO_JWT_HEADER_PREFIX Optional

Hi guys, I have a little question

if COGNITO_JWT_HEADER_PREFIX is optional i can set this in empty, but the code need to validate this,

in get_token we can to have something like this
if (len(parts) == 1): parts = ["", parts[0]]

before the validation

Thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.