Python flask_jwt_extended.create_access_token() Examples

The following are 22 code examples of flask_jwt_extended.create_access_token(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module flask_jwt_extended , or try the search function .
Example #1
Source File: test_query_string.py    From flask-jwt-extended with MIT License 7 votes vote down vote up
def test_custom_query_paramater(app):
    app.config['JWT_QUERY_STRING_NAME'] = 'foo'
    test_client = app.test_client()

    with app.test_request_context():
        access_token = create_access_token('username')

    # Insure 'default' query paramaters no longer work
    url = '/protected?jwt={}'.format(access_token)
    response = test_client.get(url)
    assert response.status_code == 401
    assert response.get_json() == {'msg': 'Missing "foo" query paramater'}

    # Insure new query_string does work
    url = '/protected?foo={}'.format(access_token)
    response = test_client.get(url)
    assert response.status_code == 200
    assert response.get_json() == {'foo': 'bar'} 
Example #2
Source File: login_user_controller.py    From TensorHive with Apache License 2.0 6 votes vote down vote up
def login(user):
    try:
        current_user = User.find_by_username(user['username'])
        assert User.verify_hash(user['password'], current_user.password), \
            R['login']['failure']['credentials']
    except NoResultFound:
        content = {'msg': R['not_found']}
        status = 404
    except AssertionError as error_message:
        content = {'msg': str(error_message)}
        status = 401
    except Exception:
        content = {'msg': G['internal_error']}
        status = 500
    else:
        content = {
            'msg': R['login']['success'].format(username=current_user.username),
            'access_token': create_access_token(identity=current_user.id, fresh=True),
            'refresh_token': create_refresh_token(identity=current_user.id)
        }
        status = 200
    finally:
        return content, status 
Example #3
Source File: test_asymmetric_crypto.py    From flask-jwt-extended with MIT License 6 votes vote down vote up
def test_asymmetric_cropto(app):
    test_client = app.test_client()

    with app.test_request_context():
        hs256_token = create_access_token('username')
        app.config['JWT_ALGORITHM'] = 'RS256'
        rs256_token = create_access_token('username')

    # Insure the symmetric token does not work now
    access_headers = {'Authorization': 'Bearer {}'.format(hs256_token)}
    response = test_client.get('/protected', headers=access_headers)
    assert response.status_code == 422
    assert response.get_json() == {'msg': 'The specified alg value is not allowed'}

    # Insure the asymmetric token does work
    access_headers = {'Authorization': 'Bearer {}'.format(rs256_token)}
    response = test_client.get('/protected', headers=access_headers)
    assert response.status_code == 200
    assert response.get_json() == {'foo': 'bar'} 
Example #4
Source File: endpoint.py    From lost with MIT License 6 votes vote down vote up
def post(self):
        dbm = access.DBMan(LOST_CONFIG) 
        identity = get_jwt_identity()
        user = dbm.get_user_by_id(identity)
        expires = datetime.timedelta(minutes=LOST_CONFIG.session_timeout)
        expires_refresh = datetime.timedelta(minutes=LOST_CONFIG.session_timeout + 2)
        if FLASK_DEBUG:
            expires = datetime.timedelta(days=365)
            expires_refresh = datetime.timedelta(days=366)
        if user:
            access_token = create_access_token(identity=user.idx, fresh=True, expires_delta=expires)
            refresh_token = create_refresh_token(user.idx, expires_delta=expires_refresh)
            ret = {
                'token': access_token,
                'refresh_token': refresh_token
            }
            dbm.close_session()
            return ret, 200
        dbm.close_session()
        return {'message': 'Invalid user'}, 401 
Example #5
Source File: endpoint.py    From lost with MIT License 6 votes vote down vote up
def post(self):
        # get data from parser
        data = login_parser.parse_args()
        dbm = access.DBMan(LOST_CONFIG)
        # find user in database
        if 'user_name' in data:
            user = dbm.find_user_by_user_name(data['user_name'])

        # check password
        if user and user.check_password(data['password']):
            dbm.close_session()
            expires = datetime.timedelta(minutes=LOST_CONFIG.session_timeout)
            expires_refresh = datetime.timedelta(minutes=LOST_CONFIG.session_timeout + 2)
            if FLASK_DEBUG:
                expires = datetime.timedelta(days=365)
                expires_refresh = datetime.timedelta(days=366)
            access_token = create_access_token(identity=user.idx, fresh=True, expires_delta=expires)
            refresh_token = create_refresh_token(user.idx, expires_delta=expires_refresh)
            return {
                'token': access_token,
                'refresh_token': refresh_token
            }, 200
        dbm.close_session()
        return {'message': 'Invalid credentials'}, 401 
Example #6
Source File: token.py    From full-stack-flask-couchbase with MIT License 6 votes vote down vote up
def route_login_access_token(username, password):
    bucket = get_default_bucket()
    user = authenticate_user(bucket, username, password)
    if not user:
        abort(400, "Incorrect email or password")
    elif not check_if_user_is_active(user):
        abort(400, "Inactive user")
    access_token_expires = timedelta(minutes=config.ACCESS_TOKEN_EXPIRE_MINUTES)
    return {
        "access_token": create_access_token(
            identity=username, expires_delta=access_token_expires
        ),
        "token_type": "bearer",
    }


# OAuth2 compatible token login, get an access token for future requests has a test in test_token 
Example #7
Source File: controllers.py    From Mastering-Flask-Web-Development-Second-Edition with MIT License 6 votes vote down vote up
def api():
    if not request.is_json:
        return jsonify({"msg": "Missing JSON in request"}), 400

    username = request.json.get('username', None)
    password = request.json.get('password', None)
    if not username:
        return jsonify({"msg": "Missing username parameter"}), 400
    if not password:
        return jsonify({"msg": "Missing password parameter"}), 400
    user = authenticate(username, password)
    if not user:
        return jsonify({"msg": "Bad username or password"}), 401

    # Identity can be any data that is json serializable
    access_token = create_access_token(identity=user.id)
    return jsonify(access_token=access_token), 200 
Example #8
Source File: controllers.py    From Mastering-Flask-Web-Development-Second-Edition with MIT License 6 votes vote down vote up
def api():
    if not request.is_json:
        return jsonify({"msg": "Missing JSON in request"}), 400

    username = request.json.get('username', None)
    password = request.json.get('password', None)
    if not username:
        return jsonify({"msg": "Missing username parameter"}), 400
    if not password:
        return jsonify({"msg": "Missing password parameter"}), 400
    user = authenticate(username, password)
    if not user:
        return jsonify({"msg": "Bad username or password"}), 401

    # Identity can be any data that is json serializable
    access_token = create_access_token(identity=user.id)
    return jsonify(access_token=access_token), 200 
Example #9
Source File: controllers.py    From Mastering-Flask-Web-Development-Second-Edition with MIT License 6 votes vote down vote up
def api():
    if not request.is_json:
        return jsonify({"msg": "Missing JSON in request"}), 400

    username = request.json.get('username', None)
    password = request.json.get('password', None)
    if not username:
        return jsonify({"msg": "Missing username parameter"}), 400
    if not password:
        return jsonify({"msg": "Missing password parameter"}), 400
    user = authenticate(username, password)
    if not user:
        return jsonify({"msg": "Bad username or password"}), 401

    # Identity can be any data that is json serializable
    access_token = create_access_token(identity=user.id)
    return jsonify(access_token=access_token), 200 
Example #10
Source File: controllers.py    From Mastering-Flask-Web-Development-Second-Edition with MIT License 6 votes vote down vote up
def api():
    if not request.is_json:
        return jsonify({"msg": "Missing JSON in request"}), 400

    username = request.json.get('username', None)
    password = request.json.get('password', None)
    if not username:
        return jsonify({"msg": "Missing username parameter"}), 400
    if not password:
        return jsonify({"msg": "Missing password parameter"}), 400
    user = authenticate(username, password)
    if not user:
        return jsonify({"msg": "Bad username or password"}), 401

    # Identity can be any data that is json serializable
    access_token = create_access_token(identity=user.id)
    return jsonify(access_token=access_token), 200 
Example #11
Source File: controllers.py    From Mastering-Flask-Web-Development-Second-Edition with MIT License 6 votes vote down vote up
def api():
    if not request.is_json:
        return jsonify({"msg": "Missing JSON in request"}), 400

    username = request.json.get('username', None)
    password = request.json.get('password', None)
    if not username:
        return jsonify({"msg": "Missing username parameter"}), 400
    if not password:
        return jsonify({"msg": "Missing password parameter"}), 400
    user = authenticate(username, password)
    if not user:
        return jsonify({"msg": "Bad username or password"}), 401

    # Identity can be any data that is json serializable
    access_token = create_access_token(identity=user.id)
    return jsonify(access_token=access_token), 200 
Example #12
Source File: token.py    From full-stack with MIT License 5 votes vote down vote up
def route_login_access_token(username, password):
    user = get_user_by_username(username, db_session)

    if not user or not verify_password(password, get_user_hashed_password(user)):
        abort(400, "Incorrect email or password")
    elif not user.is_active:
        abort(400, "Inactive user")
    access_token_expires = timedelta(minutes=config.ACCESS_TOKEN_EXPIRE_MINUTES)
    return {
        "access_token": create_access_token(
            identity=get_user_id(user), expires_delta=access_token_expires
        ),
        "token_type": "bearer",
    } 
Example #13
Source File: test_headers.py    From flask-jwt-extended with MIT License 5 votes vote down vote up
def test_default_headers(app):
    app.config
    test_client = app.test_client()

    with app.test_request_context():
        access_token = create_access_token('username')

    # Ensure other authorization types don't work
    access_headers = {'Authorization': 'Basic basiccreds'}
    response = test_client.get('/protected', headers=access_headers)
    expected_json = {'msg': "Bad Authorization header. Expected value 'Bearer <JWT>'"}
    assert response.status_code == 422
    assert response.get_json() == expected_json

    # Ensure default headers work
    access_headers = {'Authorization': 'Bearer {}'.format(access_token)}
    response = test_client.get('/protected', headers=access_headers)
    assert response.status_code == 200
    assert response.get_json() == {'foo': 'bar'}

    # Ensure default headers work with multiple field values
    access_headers = {'Authorization': 'Bearer {}, Basic creds'.format(access_token)}
    response = test_client.get('/protected', headers=access_headers)
    assert response.status_code == 200
    assert response.get_json() == {'foo': 'bar'}

    # Ensure default headers work with multiple field values in any position
    access_headers = {'Authorization': 'Basic creds, Bearer {}'.format(access_token)}
    response = test_client.get('/protected', headers=access_headers)
    assert response.status_code == 200
    assert response.get_json() == {'foo': 'bar'} 
Example #14
Source File: refresh_access_token_controller.py    From TensorHive with Apache License 2.0 5 votes vote down vote up
def generate():
    new_access_token = create_access_token(identity=get_jwt_identity(), fresh=False)
    content = {
        'msg': R['refresh']['success'],
        'access_token': new_access_token
    }
    return content, 200 
Example #15
Source File: general.py    From marvin with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def login(self):
        ''' Server-Side login to generate a new token '''

        result = {}

        # check the form
        form = processRequest(request=request)
        if form is None:
            result['error'] = 'Request has no form data!'
            return jsonify(result), 400

        # get username and password
        username = form.get('username', None)
        password = form.get('password', None)
        # return if no valid login form data
        if not username or not password:
            result['error'] = 'Missing username and/or password!'
            return jsonify(result), 400
        username = username.strip()
        password = password.strip()

        # validate the user with htpassfile or trac username
        is_valid, user, result = validate_user(username, password, request=request)

        # User code goes here
        if is_valid:
            user = get_db_user(username, password, dbsession=marvindb.session, user_model=marvindb.datadb.User, request=request)
            if user and user.check_password(password):
                # generate token if valid
                access_token = create_access_token(identity=user.username, fresh=True)
                return jsonify(access_token=access_token), 200
        else:
            msg = result['error'] if 'error' in result else ''
            result['error'] = 'Not valid login. Bad username or password. {0}'.format(msg)
            return jsonify(result), 401 
Example #16
Source File: main.py    From --Awesome-Python-- with GNU General Public License v3.0 5 votes vote down vote up
def refresh():
    return jsonify({
        'access_token': create_access_token(identity=get_jwt_identity())
    }) 
Example #17
Source File: main.py    From --Awesome-Python-- with GNU General Public License v3.0 5 votes vote down vote up
def auth():
    id = request.form['id']
    pw = request.form['pw']

    if id in user and user[id] == pw:
        return jsonify({
            'access_token': create_access_token(identity=id),
            'refresh_token': create_refresh_token(identity=id)
        }), 200

    else:
        return jsonify({
            'msg': 'Incorrect id or password'
        }), 401 
Example #18
Source File: views.py    From flask-realworld-example-app with MIT License 5 votes vote down vote up
def login_user(email, password, **kwargs):
    user = User.query.filter_by(email=email).first()
    if user is not None and user.check_password(password):
        user.token = create_access_token(identity=user, fresh=True)
        return user
    else:
        raise InvalidUsage.user_not_found() 
Example #19
Source File: views.py    From flask-realworld-example-app with MIT License 5 votes vote down vote up
def register_user(username, password, email, **kwargs):
    try:
        userprofile = UserProfile(User(username, email, password=password, **kwargs).save()).save()
        userprofile.user.token = create_access_token(identity=userprofile.user)
    except IntegrityError:
        db.session.rollback()
        raise InvalidUsage.user_already_registered()
    return userprofile.user 
Example #20
Source File: test_query_string.py    From flask-jwt-extended with MIT License 5 votes vote down vote up
def test_default_query_paramater(app):
    test_client = app.test_client()

    with app.test_request_context():
        access_token = create_access_token('username')

    url = '/protected?jwt={}'.format(access_token)
    response = test_client.get(url)
    assert response.status_code == 200
    assert response.get_json() == {'foo': 'bar'} 
Example #21
Source File: test_headers.py    From flask-jwt-extended with MIT License 5 votes vote down vote up
def test_custom_header_name(app):
    app.config['JWT_HEADER_NAME'] = 'Foo'
    test_client = app.test_client()

    with app.test_request_context():
        access_token = create_access_token('username')

    # Insure 'default' headers no longer work
    access_headers = {'Authorization': 'Bearer {}'.format(access_token)}
    response = test_client.get('/protected', headers=access_headers)
    assert response.status_code == 401
    assert response.get_json() == {'msg': 'Missing Foo Header'}

    # Insure new headers do work
    access_headers = {'Foo': 'Bearer {}'.format(access_token)}
    response = test_client.get('/protected', headers=access_headers)
    assert response.status_code == 200
    assert response.get_json() == {'foo': 'bar'}

    # Ensure new headers work with multiple field values
    access_headers = {'Foo': 'Bearer {}, Basic randomcredshere'.format(access_token)}
    response = test_client.get('/protected', headers=access_headers)
    assert response.status_code == 200
    assert response.get_json() == {'foo': 'bar'}

    # Ensure new headers work with multiple field values in any position
    access_headers = {'Foo': 'Basic randomcredshere, Bearer {}'.format(access_token)}
    response = test_client.get('/protected', headers=access_headers)
    assert response.status_code == 200
    assert response.get_json() == {'foo': 'bar'} 
Example #22
Source File: test_headers.py    From flask-jwt-extended with MIT License 4 votes vote down vote up
def test_custom_header_type(app):
    app.config['JWT_HEADER_TYPE'] = 'JWT'
    test_client = app.test_client()

    with app.test_request_context():
        access_token = create_access_token('username')

    # Insure 'default' headers no longer work
    access_headers = {'Authorization': 'Bearer {}'.format(access_token)}
    response = test_client.get('/protected', headers=access_headers)
    expected_json = {'msg': "Bad Authorization header. Expected value 'JWT <JWT>'"}
    assert response.status_code == 422
    assert response.get_json() == expected_json

    # Insure new headers do work
    access_headers = {'Authorization': 'JWT {}'.format(access_token)}
    response = test_client.get('/protected', headers=access_headers)
    assert response.status_code == 200
    assert response.get_json() == {'foo': 'bar'}

    # Ensure new headers work with multiple field values
    access_headers = {'Authorization': 'JWT {}, Basic creds'.format(access_token)}
    response = test_client.get('/protected', headers=access_headers)
    assert response.status_code == 200
    assert response.get_json() == {'foo': 'bar'}

    # Ensure new headers work with multiple field values in any position
    access_headers = {'Authorization': 'Basic creds, JWT {}'.format(access_token)}
    response = test_client.get('/protected', headers=access_headers)
    assert response.status_code == 200
    assert response.get_json() == {'foo': 'bar'}

    # Insure new headers without a type also work
    app.config['JWT_HEADER_TYPE'] = ''
    access_headers = {'Authorization': access_token}
    response = test_client.get('/protected', headers=access_headers)
    assert response.status_code == 200
    assert response.get_json() == {'foo': 'bar'}

    # Insure header with too many parts fails
    app.config['JWT_HEADER_TYPE'] = ''
    access_headers = {'Authorization': 'Bearer {}'.format(access_token)}
    response = test_client.get('/protected', headers=access_headers)
    expected_json = {'msg': "Bad Authorization header. Expected value '<JWT>'"}
    assert response.get_json() == expected_json
    assert response.status_code == 422