29
Flask-GraphQL-Auth Documentation Release 1.1 devArtoria Nov 17, 2019

Flask-GraphQL-Auth Documentation · flask_graphql_auth.mutation_jwt_refresh_token_required(fn) A decorator to protect a mutation. If you decorate a mutation with this, it will ensure

  • Upload
    others

  • View
    12

  • Download
    0

Embed Size (px)

Citation preview

Flask-GraphQL-Auth DocumentationRelease 1.1

devArtoria

Nov 17, 2019

Contents

1 Installation 3

2 Basic Usage 5

3 Insert User Claims 9

4 Get JWT from header 13

5 API Documentation 175.1 Configuring Flask-GraphQL-Auth . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175.2 Protected query decorators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175.3 Protected mutation decorators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185.4 Utilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185.5 Fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19

6 Configuration Options 216.1 Options: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

7 Indices and tables 23

Index 25

i

ii

Flask-GraphQL-Auth Documentation, Release 1.1

Contents:

Contents 1

Flask-GraphQL-Auth Documentation, Release 1.1

2 Contents

CHAPTER 1

Installation

The easiest way to start working with this extension with pip:

$ pip install flask-graphql-auth

3

Flask-GraphQL-Auth Documentation, Release 1.1

4 Chapter 1. Installation

CHAPTER 2

Basic Usage

from flask import Flaskimport graphenefrom flask_graphql_auth import (

AuthInfoField,GraphQLAuth,get_jwt_identity,get_raw_jwt,create_access_token,create_refresh_token,query_jwt_required,mutation_jwt_refresh_token_required,mutation_jwt_required,

)from flask_graphql import GraphQLView

app = Flask(__name__)auth = GraphQLAuth(app)

app.config["JWT_SECRET_KEY"] = "something" # change this!app.config["REFRESH_EXP_LENGTH"] = 30app.config["ACCESS_EXP_LENGTH"] = 10

class MessageField(graphene.ObjectType):message = graphene.String()

class ProtectedUnion(graphene.Union):class Meta:

types = (MessageField, AuthInfoField)

@classmethoddef resolve_type(cls, instance, info):

return type(instance)

(continues on next page)

5

Flask-GraphQL-Auth Documentation, Release 1.1

(continued from previous page)

class AuthMutation(graphene.Mutation):class Arguments(object):

username = graphene.String()password = graphene.String()

access_token = graphene.String()refresh_token = graphene.String()

@classmethoddef mutate(cls, _, info, username, password):

return AuthMutation(access_token=create_access_token(username),refresh_token=create_refresh_token(username),

)

class ProtectedMutation(graphene.Mutation):class Arguments(object):

token = graphene.String()

message = graphene.Field(ProtectedUnion)

@classmethod@mutation_jwt_requireddef mutate(cls, _, info):

return ProtectedMutation(message=MessageField(message="Protected mutation works")

)

class RefreshMutation(graphene.Mutation):class Arguments(object):

refresh_token = graphene.String()

new_token = graphene.String()

@classmethod@mutation_jwt_refresh_token_requireddef mutate(self, _):

current_user = get_jwt_identity()return RefreshMutation(new_token=create_access_token(identity=current_user))

class Mutation(graphene.ObjectType):auth = AuthMutation.Field()refresh = RefreshMutation.Field()protected = ProtectedMutation.Field()

class Query(graphene.ObjectType):protected = graphene.Field(type=ProtectedUnion, token=graphene.String())

@query_jwt_requireddef resolve_protected(self, info):

return MessageField(message="Hello World!")(continues on next page)

6 Chapter 2. Basic Usage

Flask-GraphQL-Auth Documentation, Release 1.1

(continued from previous page)

schema = graphene.Schema(query=Query, mutation=Mutation)

app.add_url_rule("/graphql", view_func=GraphQLView.as_view("graphql", schema=schema, graphiql=True)

)

if __name__ == "__main__":app.run(debug=True)

Important: To make protected query or mutation with auth decorators, we have to make union withflask_graphql_auth.AuthInfoField to allow auth decorators return AuthInfoField when a problem occurs. Also, Ifyou want to assign union to mutation, you have to override resolve_type

To get token with auth mutation try this query:

mutation {auth(password: <any word>, username: <any word>) {

accessTokenrefreshToken

}}

To refresh the token with refresh mutation try this one:

mutation {refresh(refreshToken: <access token>) {

newToken}

}

To access a jwt_required protected query or mutation, all we have to do is send in the JWT in the query. By default,this is done with an mutation or query argument that looks like:

{protected(token: <access token>) {

... on MessageField {message

}}

}

mutation {protected(token: <access token>) {

message {... on MessageField {

message}

}}

}

7

Flask-GraphQL-Auth Documentation, Release 1.1

8 Chapter 2. Basic Usage

CHAPTER 3

Insert User Claims

from flask import Flaskimport graphenefrom flask_graphql_auth import (

AuthInfoField,GraphQLAuth,get_jwt_identity,get_raw_jwt,create_access_token,create_refresh_token,query_jwt_required,mutation_jwt_required,mutation_jwt_refresh_token_required,

)from flask_graphql import GraphQLView

app = Flask(__name__)auth = GraphQLAuth(app)

app.config["JWT_SECRET_KEY"] = "something" # change this!app.config["REFRESH_EXP_LENGTH"] = 30app.config["ACCESS_EXP_LENGTH"] = 10

user_claims = {"message": "VERI TAS LUX MEA"}

class MessageField(graphene.ObjectType):message = graphene.String()

class ProtectedUnion(graphene.Union):class Meta:

types = (MessageField, AuthInfoField)

@classmethod(continues on next page)

9

Flask-GraphQL-Auth Documentation, Release 1.1

(continued from previous page)

def resolve_type(cls, instance, info):return type(instance)

class AuthMutation(graphene.Mutation):class Arguments(object):

username = graphene.String()password = graphene.String()

access_token = graphene.String()refresh_token = graphene.String()

@classmethoddef mutate(cls, _, info, username, password):

return AuthMutation(access_token=create_access_token(username, user_claims=user_claims),refresh_token=create_refresh_token(username, user_claims=user_claims),

)

class ProtectedMutation(graphene.Mutation):class Arguments(object):

token = graphene.String()

message = graphene.Field(ProtectedUnion)

@classmethod@mutation_jwt_requireddef mutate(cls, _, info):

return ProtectedMutation(message=MessageField(message="Protected mutation works")

)

class RefreshMutation(graphene.Mutation):class Arguments(object):

token = graphene.String()

new_token = graphene.String()

@classmethod@mutation_jwt_refresh_token_requireddef mutate(self, _, info):

current_user = get_jwt_identity()return RefreshMutation(

new_token=create_access_token(identity=current_user, user_claims=user_claims

))

class Mutation(graphene.ObjectType):auth = AuthMutation.Field()refresh = RefreshMutation.Field()protected = ProtectedMutation.Field()

(continues on next page)

10 Chapter 3. Insert User Claims

Flask-GraphQL-Auth Documentation, Release 1.1

(continued from previous page)

class Query(graphene.ObjectType):protected = graphene.Field(

type=ProtectedUnion, message=graphene.String(), token=graphene.String())

@query_jwt_requireddef resolve_protected(self, info, message):

return MessageField(message=str(get_raw_jwt()))

schema = graphene.Schema(query=Query, mutation=Mutation)

app.add_url_rule("/graphql", view_func=GraphQLView.as_view("graphql", schema=schema, graphiql=True)

)

if __name__ == "__main__":app.run(debug=True)

Important: To make protected query or mutation with auth decorators, we have to make union withflask_graphql_auth.AuthInfoField to allow auth decorators return AuthInfoField when a problem occurs. Also, Ifyou want to assign union to mutation, you have to override resolve_type

11

Flask-GraphQL-Auth Documentation, Release 1.1

12 Chapter 3. Insert User Claims

CHAPTER 4

Get JWT from header

You can get JWT from header by use these decorators.

• query_header_jwt_required

• query_header_jwt_refresh_token_required

• mutation_header_jwt_required,

• mutation_jwt_header_refresh_token_required

This is example usage.

from flask import Flaskimport graphenefrom flask_graphql_auth import (

AuthInfoField,GraphQLAuth,get_jwt_identity,create_access_token,create_refresh_token,query_header_jwt_required,mutation_header_jwt_refresh_token_required,mutation_header_jwt_required,

)from flask_graphql import GraphQLView

app = Flask(__name__)auth = GraphQLAuth(app)

app.config["JWT_SECRET_KEY"] = "something" # change this!app.config["REFRESH_EXP_LENGTH"] = 30app.config["ACCESS_EXP_LENGTH"] = 10

class MessageField(graphene.ObjectType):message = graphene.String()

(continues on next page)

13

Flask-GraphQL-Auth Documentation, Release 1.1

(continued from previous page)

class ProtectedUnion(graphene.Union):class Meta:

types = (MessageField, AuthInfoField)

@classmethoddef resolve_type(cls, instance, info):

return type(instance)

class AuthMutation(graphene.Mutation):class Arguments(object):

username = graphene.String()password = graphene.String()

access_token = graphene.String()refresh_token = graphene.String()

@classmethoddef mutate(cls, _, info, username, password):

return AuthMutation(access_token=create_access_token(username),refresh_token=create_refresh_token(username),

)

class ProtectedMutation(graphene.Mutation):class Arguments(object):

pass

message = graphene.Field(ProtectedUnion)

@classmethod@mutation_header_jwt_requireddef mutate(cls, _, info):

return ProtectedMutation(message=MessageField(message="Protected mutation works")

)

class RefreshMutation(graphene.Mutation):class Arguments(object):

pass

new_token = graphene.String()

@classmethod@mutation_header_jwt_refresh_token_requireddef mutate(cls, _):

current_user = get_jwt_identity()return RefreshMutation(new_token=create_access_token(identity=current_user))

class Mutation(graphene.ObjectType):auth = AuthMutation.Field()refresh = RefreshMutation.Field()

(continues on next page)

14 Chapter 4. Get JWT from header

Flask-GraphQL-Auth Documentation, Release 1.1

(continued from previous page)

protected = ProtectedMutation.Field()

class Query(graphene.ObjectType):protected = graphene.Field(type=ProtectedUnion)

@query_header_jwt_requireddef resolve_protected(self, info):

return MessageField(message="Hello World!")

schema = graphene.Schema(query=Query, mutation=Mutation)

app.add_url_rule("/graphql", view_func=GraphQLView.as_view("graphql", schema=schema, graphiql=True)

)

if __name__ == "__main__":app.run(debug=True)

15

Flask-GraphQL-Auth Documentation, Release 1.1

16 Chapter 4. Get JWT from header

CHAPTER 5

API Documentation

In here you will find the API for everything exposed in this extension.

5.1 Configuring Flask-GraphQL-Auth

class flask_graphql_auth.GraphQLAuth(app=None)An object used to hold JWT settings for the Flask-GraphQL-Auth extension.

Instances of GraphQLAuth are not bound to specific apps, so you can create one in the main body of yourcode and then bind it to your app in a factory function.

__init__(app=None)Create the GraphQLAuth instance. You can either pass a flask application in directly here to register thisextension with the flask app, or call init_app after creating this object (in a factory pattern). :param app: Aflask application

init_app(app)Register this extension with the flask app.

Parameters app – A flask application

5.2 Protected query decorators

flask_graphql_auth.query_jwt_required(fn)A decorator to protect a query resolver.

If you decorate an resolver with this, it will ensure that the requester has a valid access token before allowingthe resolver to be called. This does not check the freshness of the access token.

flask_graphql_auth.query_header_jwt_required(fn)A decorator to protect a query resolver.

17

Flask-GraphQL-Auth Documentation, Release 1.1

If you decorate an resolver with this, it will ensure that the requester has a valid access token before allowingthe resolver to be called. This does not check the freshness of the access token.

flask_graphql_auth.query_jwt_refresh_token_required(fn)A decorator to protect a query resolver.

If you decorate an query resolver with this, it will ensure that the requester has a valid refresh token beforeallowing the resolver to be called.

flask_graphql_auth.query_header_jwt_refresh_token_required(fn)A decorator to protect a query resolver.

If you decorate an query resolver with this, it will ensure that the requester has a valid refresh token beforeallowing the resolver to be called.

5.3 Protected mutation decorators

flask_graphql_auth.mutation_jwt_required(fn)A decorator to protect a mutation.

If you decorate a mutation with this, it will ensure that the requester has a valid access token before allowing themutation to be called. This does not check the freshness of the access token.

flask_graphql_auth.mutation_header_jwt_required(fn)A decorator to protect a mutation.

If you decorate a mutation with this, it will ensure that the requester has a valid access token before allowing themutation to be called. This does not check the freshness of the access token.

flask_graphql_auth.mutation_jwt_refresh_token_required(fn)A decorator to protect a mutation.

If you decorate a mutation with this, it will ensure that the requester has a valid refresh token before allowingthe mutation to be called.

5.4 Utilities

flask_graphql_auth.create_access_token(identity, user_claims=None)Create a new access token.

Parameters

• identity – The identity of this token, which can be any data that is json serializable. Itcan also be a python object

• user_claims – User made claims that will be added to this token. it should be dictionary.

Returns An encoded access token

flask_graphql_auth.create_refresh_token(identity, user_claims=None)Creates a new refresh token.

Parameters

• identity – The identity of this token, which can be any data that is json serializable. Itcan also be a python object

• user_claims – User made claims that will be added to this token. it should be dictionary.

Returns An encoded refresh token

18 Chapter 5. API Documentation

Flask-GraphQL-Auth Documentation, Release 1.1

flask_graphql_auth.get_raw_jwt()In a protected endpoint, this will return the python dictionary which has all of the claims of the JWT that isaccessing the endpoint. If no JWT is currently present, an empty dict is returned instead.

flask_graphql_auth.get_jwt_identity()In a protected resolver or mutation, this will return the identity of the JWT that is accessing this endpoint. If noJWT is present,‘None‘ is returned instead.

flask_graphql_auth.get_jwt_claims()In a protected resolver or mutation, this will return the dictionary of custom claims in the JWT that is accessingthe endpoint. If no custom user claims are present, an empty dict is returned instead.

flask_graphql_auth.decode_jwt(encoded_token, secret, algorithm, identity_claim_key,user_claims_key)

Decodes an encoded JWT

Parameters

• encoded_token – The encoded JWT string to decode

• secret – Secret key used to encode the JWT

• algorithm – Algorithm used to encode the JWT

• identity_claim_key – expected key that contains the identity

• user_claims_key – expected key that contains the user claims

Returns Dictionary containing contents of the JWT

flask_graphql_auth.get_jwt_data(token, token_type)Decodes encoded JWT token by using extension setting and validates token type

Parameters

• token – The encoded JWT string to decode

• token_type – JWT type for type validation (access or refresh)

Returns Dictionary containing contents of the JWT

5.5 Fields

class flask_graphql_auth.AuthInfoField(*args, **kwargs)

5.5. Fields 19

Flask-GraphQL-Auth Documentation, Release 1.1

20 Chapter 5. API Documentation

CHAPTER 6

Configuration Options

You can change many options for how this extension works via

app.config[OPTION_NAME] = new_options

6.1 Options:

JWT_TOKEN_ARGUMENT_NAMEWhere to look for a JWT in resolver argumentJWT_ACCESS_TOKEN_EXPIRESHow long an access token should live before it expires. This takes a datetime.

timedelta, and defaults to 15 minutes. Can be set to False to disable expiration.JWT_REFRESH_TOKEN_EXPIRESHow long a refresh token should live before it expires. This takes a datetime.

timedelta, and defaults to 30 days. Can be set to False‘ to disable expiration.JWT_SECRET_KEY The secret key needed for symmetric based signing algorithms, such as HS*. If this is not

set, we use the flask SECRET_KEY value instead.JWT_IDENTITY_CLAIMClaim in the tokens that is used as source of identity. For interoperability, the JWT RFC

recommends using 'sub'. Defaults to 'identity' for legacy reasons.JWT_USER_CLAIMS Claim in the tokens that is used to store user claims. Defaults to 'user_claims'.

21

Flask-GraphQL-Auth Documentation, Release 1.1

22 Chapter 6. Configuration Options

CHAPTER 7

Indices and tables

• genindex

• modindex

• search

23

Flask-GraphQL-Auth Documentation, Release 1.1

24 Chapter 7. Indices and tables

Index

Symbols__init__() (flask_graphql_auth.GraphQLAuth

method), 17

AAuthInfoField (class in flask_graphql_auth), 19

Ccreate_access_token() (in module

flask_graphql_auth), 18create_refresh_token() (in module

flask_graphql_auth), 18

Ddecode_jwt() (in module flask_graphql_auth), 19

Fflask_graphql_auth (module), 17

Gget_jwt_claims() (in module flask_graphql_auth),

19get_jwt_data() (in module flask_graphql_auth), 19get_jwt_identity() (in module

flask_graphql_auth), 19get_raw_jwt() (in module flask_graphql_auth), 18GraphQLAuth (class in flask_graphql_auth), 17

Iinit_app() (flask_graphql_auth.GraphQLAuth

method), 17

Mmutation_header_jwt_required() (in module

flask_graphql_auth), 18mutation_jwt_refresh_token_required()

(in module flask_graphql_auth), 18mutation_jwt_required() (in module

flask_graphql_auth), 18

Qquery_header_jwt_refresh_token_required()

(in module flask_graphql_auth), 18query_header_jwt_required() (in module

flask_graphql_auth), 17query_jwt_refresh_token_required() (in

module flask_graphql_auth), 18query_jwt_required() (in module

flask_graphql_auth), 17

25