Hi, you can use requests.Session:
#in default
session = requests.Session()
url_login = 'http://..../api/login.json'
#requests.packages.urllib3.disable_warnings() # - uncomment if you use a
self-signed
cert over https
r = session.get(url_login, verify=True) #set verify=False if you use a
self-signed
cert over https
form = dict( username = 'user', password = 'password')
r = session.post(url_login, data = form)
if r.status_code==200: #server OK
response_data = json.loads(r.text)
logged_in = 'logged_in' in response_data.keys()
# if logged_in == True - session is authorized, so use
session.post/get ... to request api
#in api
@request.restful()
def login():
response.view = 'generic.json'
user = request.vars.username
password = request.vars.password
if auth.login_bare(user, password):
return dict(logged_in = 'yes')
# auth.requires_login() redirects to login form, but it's redundant for
api
# instead of auth.requires_login() you can write your own simple decorator:
def api_requires_login(f):
if auth.is_logged_in():
return f
raise HTTP(401) # or return something
On Tuesday, November 14, 2017 at 8:05:36 PM UTC+3, Carlos A. Armenta Castro
wrote:
>
> Hola Leandro, te escribo en español porque al ver tu nombre me parece que
> hablas castellano, corrigeme si me equivoco y te lo escribo en ingles,
>
>
>
> El lunes, 13 de noviembre de 2017, 7:14:00 (UTC-7), Leandro Sebastian
> Salgueiro escribió:
>
> I added then the requires_login to api controller and then i test both
>> URLs independently from browser, it works ok (login to web2py -> go to
>> /api/apps -> get my results) however if I do the GET request using
>> requests.get from default controller i get a* Non Authorized *message
>> and redirect to login form.
>>
>
> En este caso en tu código:
>
> def index():
> import requests
> json = requests.get(URL('api', 'apps', host=True))
>
>
> Lo que haces es iniciar otra sesión en tu misma APP pero no le estás
> enviando las credenciales para el Login, yo entiendo que cada ves que
> invocas a requests creas una nueva sesión entonces tienes que hacer Login
> cada vez.
>
> Me parece un poco extraño lo que haces en tu código porque si ya estás
> firmado no se porque buscas firmarte nuevamente. Te recomiendo abordar el
> problema de una manera distinta. Web2Py es Roca Solida en cuando a
> seguridad, no deberías preocuparte por problemas de seguridad una vez que
> ya estás firmado en tu App.
>
> Si necesitas seguridad Extra para tu APP, entonces te recomiendo usar JWT
> Tokens con Web2Py http://web2py.readthedocs.io/en/latest/tools.html
>
> jwt()[source]
>> <http://web2py.readthedocs.io/en/latest/_modules/gluon/tools.html#Auth.jwt>
>>
>> To use JWT authentication: 1) instantiate auth with:
>>
>> auth = Auth(db, jwt = {'secret_key':'secret'})
>>
>> where ‘secret’ is your own secret string.
>>
>> 1.
>>
>> Decorate functions that require login but should accept the JWT token
>> credentials:
>>
>> @auth.allows_jwt()@auth.requires_login()def myapi(): return 'hello %s' %
>> auth.user.email
>>
>>
>> Notice jwt is allowed but not required. if user is logged in, myapi is
>> accessible.
>>
>> 1. Use it!
>>
>> Now API users can obtain a token with
>>
>> http://.../app/default/user/jwt?username=...&password=....
>>
>> (returns json object with a token attribute) API users can refresh an
>> existing token with
>>
>> http://.../app/default/user/jwt?token=...
>>
>> they can authenticate themselves when calling http:/.../myapi
>> <http://web2py.readthedocs.io/.../myapi> by injecting a header
>>
>> Authorization: Bearer <the jwt token>
>>
>> Saludos y suerte con tu APP.
>
> HI,
>>
>> I have two controllers on the same app:
>>
>> TestApp
>> |
>> |---default.py
>> |---api.py
>>
>> api is a restful service that will call other services. For security
>> reasons I would like that all call to these services are passed by the api
>> restful. (it will work like a proxy in this case)
>>
>> I did try the following :
>>
>> in default.py :
>>
>> @auth.requires_login()
>> def index():
>> import requests
>> json = requests.get(URL('api', 'apps', host=True))
>> return {"json": json.content}
>>
>>
>> in api.py:
>>
>> import requests
>> apps_url = 'http://localhost:8091/apps'
>>
>>
>> @auth.requires_login()
>>
>> @request.restful()
>> def apps():
>> response.view = 'generic.json'
>> def GET(*args,**vars):
>> r = requests.get(apps_url)
>> return r
>> return dict(GET=GET)
>>
>>
>> If i test this without the api's login decorator everything works fine.
>> However I can access this restful from anywhere else...
>> I added then the requires_login to api controller and then i test both
>> URLs independently from browser, it works ok (login to web2py -> go to
>> /api/apps -> get my results) however if I do the GET request using
>> requests.get from default controller i get a* Non Authorized *message
>> and redirect to login form.
>>
>> what i'm missing here? i thought that if I was in the same app, auth
>> session would be shared among different controllers...
>>
>> any hint on this would be the most welcomed..
>> Thanks in advanced.
>> Leandro
>>
>>
>>
>>
--
Resources:
- http://web2py.com
- http://web2py.com/book (Documentation)
- http://github.com/web2py/web2py (Source code)
- https://code.google.com/p/web2py/issues/list (Report Issues)
---
You received this message because you are subscribed to the Google Groups
"web2py-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
For more options, visit https://groups.google.com/d/optout.