在Web2py中使用JWT进行身份验证

时间:2020-10-15 18:17:01

标签: jwt web2py

我在控制器中使用web2py运行一个rest api,在那里我的jwt和令牌起作用。在模型中,我使用具有默认值的字段,但是由于auth.user为None,所以该字段从未自动填充。我试图手动将其初始化,但无法正常工作。

Sites.py:

if auth.user is None:
    auth = Auth(db, jwt = {'secret_key':'..hnv', 'user_param':"email"})
    #auth.jwt()
    auth.basic()
    #auth.user.update()

我也尝试在db.py中添加参数,但没有成功:

auth = Auth(db,jwt = {'secret_key':'...', 'user_param':"email"}, host_names=configuration.get('host.names'))

我期望太多还是做错了什么?

1 个答案:

答案 0 :(得分:1)

auth = Auth(db, jwt = {'secret_key':'...', 'user_param':"email"})

如果您如上所述使Auth无效(即添加JWT功能),则当带有JWT令牌的请求进入时,执行上述行时不会立即填充auth.user。而是仅在执行auth.user装饰器时(即在请求的控制器中)读取并填充@auth.allows_jwt()令牌。这意味着在具有DAL表定义的模型文件中,在通过auth.user授权的请求中,auth.user_id(以及auth.user_groupsNone)仍为auth JWT,因此您不能直接将这些值用作字段默认值。

作为替代,您可以将函数指定为字段默认值,该函数返回相关的db.define_table('mytable', ..., Field('created_by', default=lambda: auth.user_id)) 属性:

lambda

上面定义的@auth.allows_jwt()函数在定义表时不会被调用,只有在实际创建记录时才会被调用,这大概只会在用auth.user装饰的控制器中发生(因此,auth.user到那时将已被填充。)

另一种选择是通过在其中调用auth.allows_jwt来强制将auth = Auth(db, jwt = {'secret_key':'...', 'user_param':"email"}) if not auth.user: try: # If there is a token, this will populate `auth.user`, # `auth.user_id`, and `auth.user_groups` from the token data. auth.allows_jwt()(lambda: None)() except: # An error means the token is absent, expired, or invalid. pass 填充到模型文件中(它返回装饰器,但是由于我们没有将其用作装饰器,因此必须传递它一个无操作函数,然后调用返回的函数):

auth.user

执行完上述操作后,您可以使用auth.user_iddef age_in_5_years(age): return age + 5 my_age = age_in_5_years(20) dads_age = age_in_5_years(50) print(my_age) print(dads_age) 在模型定义中指定字段默认值。