Generate JWT token in Django view on form submit without DRF - python

I would like to know how can I generate a JWT token in django based on some fields which I get from a form submit in the view. This toke is not used authentication in django but I need to pass this token back in response which will then be sent to another service using JavaScript.
I am not using DRF currently.
The flow will be something like
FrontEnd -> Form submit -> Django Backend generate JWT -> Send back to FrontEnd in response
Again this is not for authentication on django.
If someone can point me to a working example that will definitely help me out.
Regards,
M.

Found my answer.
Use the python library called pyjwt
code example (JWTvalid for 1 hour)
import jwt
import datetime
exp_time = datetime.datetime.now() + datetime.timedelta(hours=1)
JWT_PAYLOAD = {
"context": {
"user": {
"name": "My Name",
"email": "My Email",
},
"iss": "My ISS",
"exp": int(exp_time.timestamp()),
"iat": int(datetime.datetime.now().timestamp()),
}
}
jwt_token = jwt.encode(JWT_PAYLOAD, settings.JWT_SECRET, algorithm='HS256')

Related

Error validating in instagram api login with django

hi i have a problem in instagram api login im doing all that right as doc said but i have this error :
Error validating verification code. Please make sure your redirect_uri is identical to the one you used in the OAuth dialog request
its redirect once but when i want to make a post request it didnt work :
#api_view(["GET"])
def insta_call_back(request):
code = request.query_params.get("code")
user_id = request.query_params.get("state")
data = {
"client_id": settings.INSTAGRAM.get("client_id"),
"client_secret": settings.INSTAGRAM.get("client_secret"),
"grant_type": "authorization_code",
"redirect_uri": f"{settings.ONLINE_URL}api/insta_call_back",
"code": code
}
resp = requests.post("https://api.instagram.com/oauth/access_token/", data=data)
return Response({
"resp": resp.text
})
i write this code in python django

How to set username and password for basic auth in flask restx swagger?

Im trying to add basic Authorization to my flask rest-x application.
By referring to https://github.com/python-restx/flask-restx/issues/271 I have made code changes.
But here there is no clarity on how to set and a username and password. As well in the swagger UI i see the login for basic auth happens with any username and password.
I have tried searching multiple resources but could not get a way how to set username & password and authenticate it. Please help regarding the same.
Flask restx version: 0.5.1
try the following code
from flask_restx import Api
blueprint = Blueprint("api", __name__)
authorizations = {
"Authorization": {
"description": "Inputs: Basic \\email\\>",
"type": "apiKey",
"in": "header",
"name": "Authorization",
}
}
api = Api(
blueprint,
title="Dummy API",
version="1.0",
authorizations=authorizations,
security="Authorization",
)

Set up authentication/authorization with flask-jwt-extended + ariadne (graphql) + react

I'm trying to create an auth system for my react(nextjs) app with flask_JWT_extended + ariadne(graphql). I have succesfully set up the login mutation that retrieves the access and refresh token but I dont know how to properly integrate them into my app. I am aware the access token is used to make subsequent requests and the refresh token is used to maintain token freshness but I dont know how to implement it with this stack.
mutations.py
Here is my login mutation that returns the access_token and refresh_token. It works fine.
#mutation.field("login")
#convert_kwargs_to_snake_case
def resolve_login(_, info, username, password):
user = User.query.filter_by(username=username).first()
if user and user.check_password(password):
access_token = create_access_token(identity=username)
refresh_token = create_refresh_token(identity=username)
payload = {
"user": user,
"access_token": access_token,
"refresh_token": refresh_token,
}
return payload
core.py
Here are my JWT configs, from what I have gathered online I am supposed to do a check on the token on each api request to maintain its freshness but I dont know how to do that especially with python + ariadne. Here is a link with someone implementing it with nodejs: https://github.com/benawad/graphql-express-template/blob/22_advanced_jwt_auth/auth.js
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "postgresql://localhost/pinkle"
app.config["JWT_SECRET_KEY"] = "this_is_a_secret"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
JWTManager(app)
index.js
Here is my front end making the call to login the user, it returns the tokens but I dont know where to utilize the tokens or if I should save it in client side state and just make calls with the token.
function login({ username, password }) {
axios
.post('http://localhost:5000/graphql', {
query: `mutation {
login(username: "${username}", password: "${password}") {
user {
id
username
password
}
}
}`,
})
.then(result => {
console.log(result.data)
})
}
The Flask-JWT-Extended documentation includes examples of utilizing JWTs from JavaScript which might be helpful for you: https://flask-jwt-extended.readthedocs.io/en/stable/token_locations/

Implementing Vue RESTful API calls in Django within Django Templates with Session Authentication

I have a Django project that requires page refreshes any time I want to update the content. Currently it uses the built in Django Class Based Views, which in turn use Templates.
I want to start implementing some javascript calls to refresh tables/forms/modal windows with new data, mostly in response to button clicks. I'm trying to use Vue to accomplish this, and I have created a Django REST Framework backend to facilitate this.
I got a simple 'Hello world' vue class working where the data is hard coded into the data field of the Vue class. I can't seem to make the jump to getting data from the API though. I am getting an Unauthorized response. I am using vue-resource for the HTTP API call.
I have unit tests where I call the API from the DRF APITestCase using the self.client.get('api/path') and they work as expected (unauthorized when there is no authenticated user attached to request, authorized when there is).
I have debugged into the DRF Permission class to see why the request is being refused and it is because there is no authenticated User attached to the request.
I have added SessionAuthentication to the DEFAULT_AUTHENTICATION_CLASSES in settings.
My question is, how do I add an authenticated user to the request so that when the Vue method is called from within my webapp the API request will be authorized?
I'm not sure if this is complicating matters but I am using a custom user model within Django for authentication.
I am hoping to start off by implementing a few Vue controls throughout my website, for instance the tables and forms mentioned. I don't want to turn this into a single page app. I would like to continue using the Django views for user authentication.
My Vue code looks like so;
new Vue({
delimiters: ['${', '}$'],
el: '.events-table',
data: {
message: 'Hello Vue!',
demo: [
{ id: 5 },
{ id: 2 },
{ id: 3 },
],
events: [],
},
http: {
root: 'http://localhost:8000',
},
methods: {
getEvents: function () {
this.$http.get('api/eventlog/events/?format=json').then(
function (data, status, request) {
if (status == 200) {
this.events = data.body.results;
}
}
)
}
},
mounted: function () {
this.getEvents();
}
})
I changed the http property like so
http: {
root: window.location.origin,
},
and now it seems to recognise that the request is coming from an authenticated session.

Authenticating users using pusher in django

I am a bit confused on how does the Authentication works in Django using pusher i want to implement a one-to-one chatting system so i guess i will be using private channels that requires authentication before you can subscribe to the channel ... i read there that the endpoint is the url you want pusher to POST to, i added a url to test if it is working but every time the status returns 403 and it seems it doesn't enter the view i created to test it so any ideas ? here is a sample of my code :
message.html
var channel = pusher.subscribe('private-test');
channel.bind('message', function(data) {
var $message = $('<div class="message"/>').appendTo('#messages');
$('<span class="user"/>').text(data.user).appendTo($message);
$('<span/>').text(data.message).appendTo($message);
});;
Pusher.channel_auth_endpoint = 'test/';
Pusher.channel_auth_transport = 'ajax';
channel.bind('pusher:subscription_succeeded', function(status) {
alert(status);
});
channel.bind('pusher:subscription_error', function(status) {
alert(status);
});
Views.py:
def testUser(request,user_name):
print 'Test Passed'
return render_to_response('message.html', {
'PUSHER_KEY': settings.PUSHER_KEY,'channel_variable':request.user.id,'other_var':'3',
}, RequestContext(request))
when i checked the url it POSTs to, in my cmd i found it correct and it matched the one i put in urls.py but i still don't know why it does not enter my view
I don't know Django, but it seems highly likely that the framework is intercepting the call to prevent CSRF (Cross site resource forgery).
The Django docs talk about CSRF here:
https://docs.djangoproject.com/en/dev/ref/contrib/csrf/
As with a number of frameworks you'll need to provide a CSRF token as part of the XHR/AJAX call to the authentication endpoint, or override the framework interception (somehow).
Have a look at the auth section of the Pusher constructor options parameter. In there you'll find an example of how to pass a CSRF token.

Categories