I've written a small standalone python script that's calling my django-based backend and everything is working fine with login and calling views requiring auth and so on.
A bit of code
def dostuff():
session = login(username, password)
license = add_license(session)
def _helper(self, url, cookie=None):
http = httplib2.Http()
if cookie:
headers = { "Cookie" : cookie }
else:
headers = {}
response, content = http.request(host + url, "GET", headers=headers, body="")
return response, content
def login(self, username, password):
url = "/license/login?username=%s&password=%s" % (username, password)
response, content = self._helper(url)
sessioncookie = response["set-cookie"]
customer_id = re.search("id=(?P<id>\d+)", content)
if response["status"] == "200":
return sessioncookie, customer_id.group("id")
def add_license(self, session):
cookie = session[0]
customer_id = int(session[1])-1
url = "/license/add_license?customer_id=%s" % customer_id
response, content = self._helper(url, cookie)
content = content[1:-1]
if response["status"] == "200": #ok
data = json.loads(content)
return data["fields"]
If I cahnge "GET" to "POST" I encounter the Django CSRF-error page(CSRF verification failed) in return. How can I send POST data to Django?
My login view in Django, do I need to do anything special to add the csrf token? My plan is to rewrite this to send json once things are working.
def my_login(request):
done, username = get_input(request, "username")
if not done:
return username
done, password = get_input(request, "password")
if not done:
return password
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return HttpResponse("Done, id=%s" % user.pk)
else:
return HttpResponse("User disabled")
else:
return HttpResponse("Invalid login")
I got it working and this is how I did it. Like suggested by toto_tico I worte a dummy view that I retrieve thought GET to get the CSRF token. At first it didn't send the csrf token over GET so I had to add the decorator ensure_csrf_cookie.
#ensure_csrf_cookie
def dummy(request):
return HttpResponse("done")
And then I handle login requests normally.
def my_login(request):
...handle login...
It turned out that just adding the cookie to the POST wasn't enough, I had to write a token to the POST data as well.
def _helper(self, url, method="POST"):
req = urllib2.Request(host + url)
self.cookieMgr.add_cookie_header(req)
try:
if method == "GET":
response = self.opener.open(req)
else:
for cookie in self.cookieMgr:
if cookie.name == "csrftoken":
csrf = cookie.value
values = { "csrfmiddlewaretoken" : csrf}
params = urllib.urlencode(values)
response = self.opener.open(req, params)
code = response.getcode()
info = response.info()
content = response.read()
return code, info, content
except urllib2.HTTPError as ex:
print str(ex)
sys.exit(1)
def get_csrf(self):
url = "/license/dummy"
self._helper(url, method="GET")
def login(self, username, password):
self.get_csrf()
url = "/license/login?username=%s&password=%s" % (username, password)
code, info, content = self._helper(url)
if code == 200:
#done!
You have to add the csrftoken cookie value when you make a request to Django. Alternatively you can add #csrf_exempt to your Django backend to accept those requests.
Start reading about CSFR and ajax. I usually do the following with the code provided:
Create a csfr.js file
Paste the code in the csfr.js file
Reference the code in the template that needs it|
If you are using templates and have something like base.html where you extend from, then you can just reference the script from there and you don't have to worry any more in there rest of your programming. As far as I know, this shouldn't represent any security issue.
Related
I have the following code that sends requests to check JWT token, then authorize user and return authorized session with Access token, Refresh Token and Session ID.
#csrf_exempt
def new_login_view(request, *args, **kwargs):
def convert_data(req):
data = {
"email": req.data['username'],
"password": req.data['password'],
}
try:
data["language"] = request.LANGUAGE_CODE
except:
data["language"] = request.POST.get('language', 'en')
return data
if request.user.is_authenticated and not request.META.get('HTTP_X_AVOID_COOKIES'):
return HttpResponseRedirect(request.GET.get(KEY_NEXT, '/'))
if request.method == 'POST':
request_data = convert_data(request)
# request to Accounts API to check if user exists
response = send_service_request(EnumAuthUrls.sign_in.value,
json_data=request_data,
original_response=True)
if isinstance(response, dict):
return JsonResponse(response)
if response.status_code == 200:
tok_ac = response.headers.get(HEADER_ACCESS_KEY)
tok_ref = response.headers.get(HEADER_REFRESH_KEY)
# checking JWT token
user = ApiAuthenticationBackend().authenticate(request, tok_ac)
# creates session
data = login_session(request, response, user)
data['user_id'] = request.user.id
data['account_id'] = request.user.profile.account_id
data['balance'] = request.user.balance
if request.META.get('HTTP_X_AVOID_COOKIES'):
return JsonResponse(data)
response = AuthResponse(
data=data,
ssid=request.session.session_key,
access_token=tok_ac,
refresh_token=tok_ref,
)
return response
else:
return ErrorApiResponse(response.json())
service = urllib.parse.quote_plus(request.build_absolute_uri())
return HttpResponseRedirect(settings.ACCOUNTS_URL + f'login/?service={service}')
Here's the code of login_session fucntion:
def login_session(request: HttpRequest, response: HttpResponse, user):
request.user = user
request.session.create()
base_data = response.json().get(KEY_DATA)
return request.user.serialize(request, base_data, token=True)
And here's the class AuthResponse that is eventually based on HttpResponse:
class AuthResponse(SuccessResponse):
def __init__(self, data={}, ssid='', access_token: str = '', refresh_token: str = '', **kwargs):
super().__init__(data, **kwargs)
if ssid:
logger.debug(f'Setting {settings.SESSION_COOKIE_NAME}: {ssid}')
self.set_cookie(key=settings.SESSION_COOKIE_NAME,
value=ssid)
if access_token:
self.set_cookie(key=settings.ACCESS_KEY_COOKIE_NAME,
value=access_token)
if refresh_token:
self.set_cookie(key=settings.REFRESH_KEY_COOKIE_NAME,
value=refresh_token)
The problem is that looks everything good on the browser side, I get all needed cookies (access token, refresh token and session id) however after trying logging in I get redirected to the main page.
There was problem in the beginning with setting cookies, but then I found out that I should not use SESSION_COOKIE_DOMAIN if it's local. Thus all cookies came up without problem but it didn't resolve situation with authorization.
While setting cookies with self.set_cookie() I tried to use secure=True, samesite='Lax', httponly=True, and all other parameters but it didn't help.
Does anyone knows what else I can try in order to fix it?
Well, I found what was wrong!
There was middleware that supposed to check token from another service. However it was checking old token, instead of new one.
So once I changed it and started to check new token - it was working just fine.
So if there's no other solutions, make sure you have checked middleware or other code where it could affect on whole system.
guys. I have been searching all over the internet but I could not get what is the problem with my code. I am actually a Frontend developer. However, I am trying to learn Python Flask for backend part of my project.
Here is the code for login endpoint and another one which can be accessed only after we are logged in.
#app.route("/login", methods=['GET', 'POST'])
def login():
if request.method == 'POST':
phone_number = request.form.get("phone_number")
password = request.form.get("password")
user = Auth.query.filter_by(phone_number=phone_number).first()
if user and check_password_hash(user.password, password):
userlogin = UserLogin().create(user)
rm = True if request.form.get('remainme') else False
login_user(user, remember=rm)
access_token = create_access_token(identity=phone_number)
response = jsonify(access_token=access_token, role=user.role)
set_access_cookies(response, access_token)
response.headers.add('Access-Control-Allow-Origin', 'http://localhost:3000')
response.headers['Access-Control-Allow-Credentials'] = 'true'
return response
else:
return jsonify(status=False), 401
return redirect(url_for("all_tours"))
#app.route("/admin/all_tours")
#jwt_required()
def all_tours():
all_tours = Tour.query.filter_by(owner=get_jwt_identity()).all()
response = jsonify(all_tours=[i.serialize for i in all_tours])
response.headers.add('Access-Control-Allow-Origin', 'http://localhost:3000')
return response
When I try to send request to use all_tours endpoint, I get
msg: "Missing cookie \"access_token_cookie\""
Have no idea what is wrong.
I even tried to add these lines into def all_tours():
access_token = request.headers['Authorization'].replace("Bearer ", "")
set_access_cookies(response, access_token)
But still useless. Could you please help me to get an idea how to fix it, please?
I have a problem I am not able to solve. I want to make use of http cookies in flask. This is the code from documentation:
#app.route('/token/auth', methods=['POST'])
def login():
username = request.json.get('username', None)
password = request.json.get('password', None)
if username != 'test' or password != 'test':
return jsonify({'login': False}), 401
# Create the tokens we will be sending back to the user
access_token = create_access_token(identity=username)
refresh_token = create_refresh_token(identity=username)
# Set the JWT cookies in the response
resp = jsonify({'login': True})
set_access_cookies(resp, access_token)
set_refresh_cookies(resp, refresh_token)
return resp, 200
I use flask_restx which automatically turns the response into JSON, so that jsonify in the first example is not needed. However, still still need to jsonify it, because i can not use set_access_cookie on a dictionary. This results at the end in a nested response like this jsonify(jsonify(x))
#api.route("/login")
class UserLogin(Resource):
def post(self):
"""Allows a new user to login with his email and password"""
email = request.get_json()["email"]
password = request.get_json()["password"]
user = User.query.filter_by(email=email).one_or_none()
if user is None:
return {"message": "user does not exist"}, 404
user = user.format()
if bcrypt.check_password_hash(pw_hash=user["password"], password=password):
if user["active"]:
resp = jsonify({"login": True})
access_token = create_access_token(identity=user)
refresh_token = create_refresh_token(user)
set_access_cookies(resp, access_token)
set_refresh_cookies(resp, refresh_token)
return resp, 200
# return (
# {"access_token": access_token, "refresh_token": refresh_token},
# 200,
# )
else:
return {"message": "User not activated"}, 400
else:
return {"message": "Wrong credentials"}, 401
This is the error: TypeError: Object of type Response is not JSON serializable
Any ideas how can I overcome this?
Was able to solve it like this:
data = dict(login=True)
resp = make_response(jsonify(**data), 200)
access_token = create_access_token(identity=user)
refresh_token = create_refresh_token(user)
set_access_cookies(resp, access_token)
set_refresh_cookies(resp, refresh_token)
return resp
I am using Django - ldap authentication in my project . Once if the user is authenticated , i need to set a cookie and return as a response to the server .
def post(self,request):
userData = json.loads(request.body)
username = userData.get('username')
password = userData.get('password')
oLdap = LDAPBackend()
if username == "admin" and password == "admin":
User_Grps = "AdminLogin"
else:
try:
User = oLdap.authenticate(username=username,password=password)
if User is not None:
User_Grps = User.ldap_user.group_dns
else:
User_Grps = "Check your username and password"
except ldap.LDAPError:
User_Grps = "Error"
return HttpResponse(User_Grps)
How to add a cookie to the response and send it with a the User_Grps to the client
response = HttpResponse(User_Grps)
response.set_cookie(key, value)
return response
That's it.
This is my view that I want to be tested.
def logIn(request):
"""
This method will log in user using username or email
"""
if request.method == 'POST':
form = LogInForm(request.POST)
if form.is_valid():
user = authenticate(username=form.cleaned_data['name'],password=form.cleaned_data['password'])
if user:
login(request,user)
return redirect('uindex')
else:
error = "Nie prawidlowy login lub haslo.Upewnij sie ze wpisales prawidlowe dane"
else:
form = LogInForm(auto_id=False)
return render_to_response('login.html',locals(),context_instance=RequestContext(request))
And here's the test
class LoginTest(unittest.TestCase):
def setUp(self):
self.client = Client()
def test_response_for_get(self):
response = self.client.get(reverse('logIn'))
self.assertEqual(response.status_code, 200)
def test_login_with_username(self):
"""
Test if user can login wit username and password
"""
user_name = 'test'
user_email = 'test#test.com'
user_password = 'zaq12wsx'
u = User.objects.create_user(user_name,user_email,user_password)
response = self.client.post(reverse('logIn'),data={'name':user_name,'password':user_password},follow=True)
self.assertEquals(response.request.user.username,user_name)
u.delete()
And when i run this test i got failure on test_login_with_username:
AttributeError: 'dict' object has no attribute 'user'
When i use in views request.user.username in works fine no error this just fails in tests. Thanks in advance for any help
edit:Ok I replace the broken part with
self.assertEquals(302, response.status_code)
But now this test breaks and another one too.
AssertionError: 302 != 200
Here is my code for the view that now fail. I want email and username to be unique.
def register(request):
"""
Function to register new user.
This function will have to care for email uniqueness,and login
"""
if request.method == 'POST':
error=[]
form = RegisterForm(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
email = form.cleaned_data['email']
if form.cleaned_data['password'] == form.cleaned_data['password_confirmation']:
password = form.cleaned_data['password']
if len(User.objects.filter(username=username)) == 0 and len(User.objects.filter(email=email)) == 0:
#email and username are bouth unique
u = User()
u.username = username
u.set_password(password)
u.email = email
u.is_active = False
u.is_superuser = False
u.is_active = True
u.save()
return render_to_response('success_register.html',locals(),context_instance=RequestContext(request))
else:
if len(User.objects.filter(username=username)) > 0:
error.append("Podany login jest juz zajety")
if len(User.objects.filter(email=email)) > 0:
error.append("Podany email jest juz zajety")
else:
error.append("Hasla nie pasuja do siebie")
#return render_to_response('register.html',locals(),context_instance=RequestContext(request))
else:
form = RegisterForm(auto_id=False)
return render_to_response('register.html',locals(),context_instance=RequestContext(request))
And here is the test that priviously work but now it is broken
def test_user_register_with_unique_data_and_permission(self):
"""
Will try to register user which provided for sure unique credentials
And also make sure that profile will be automatically created for him, and also that he he have valid privileges
"""
user_name = 'test'
user_email = 'test#test.com'
password = 'zaq12wsx'
response = self.client.post(reverse('register'),{'username': user_name,'email':user_email,
'password':password,'password_confirmation':password},follow=True)
#check if code is 200
self.assertEqual(response.status_code, 200)
u = User.objects.get(username=user_name,email = user_email)
self.assertTrue(u,"User after creation coudn't be fetched")
self.assertFalse(u.is_staff,msg="User after registration belong to staff")
self.assertFalse(u.is_superuser,msg="User after registration is superuser")
p = UserProfile.objects.get(user__username__iexact = user_name)
self.assertTrue(p,"After user creation coudn't fetch user profile")
self.assertEqual(len(response.context['error']),0,msg = 'We shoudnt get error during valid registration')
u.delete()
p.delete()
End here is the error:
AssertionError: We shoudnt get error during valid registration
If i disable login test everything is ok. How this test can break another one? And why login test is not passing. I try it on website and it works fine.
The documentation for the response object returned by the test client says this about the request attribute:
request
The request data that stimulated the response.
That suggests to me one of two things. Either it's just the data of the request, or it's request object as it was before you handled the request. In either case, you would not expect it to contain the logged in user.
Another way to write your test that the login completed successfully would be to add follow=False to the client.post call and check the response code:
self.assertEquals(302, response.status_code)
This checks that the redirect has occurred.
response.request is not the HttpRequest object in the view you are expecting. It's a dictionary of data that stimulated the post request. It doesn't have the user attribute, hence the AttributeError
You could rewrite your test to:
use the RequestFactory class introduced in Django 1.3 and call logIn in your test directly instead of using client.post.
inspect client.session after the post to check whether the user has been logged in.
Why one failing test can break another
When you edited the question, you asked
How this test can break another one?
The test_login_with_username was failing before it reached u.delete, so the user created in that test was not deleted. That caused test_user_register_with_unique_data_and_permission because the user test already existed.
If you use the django.test.TestCase class, the database will be reset in between each test, so this wouldn't be a problem.