Hey <@498057949541826571> I need guidance on how ...
# support-questions-legacy
h
Hey @rp_st I need guidance on how to dynamically add claims, such as email verification or roles, to the current user session's access token or frontend cookie without requiring a logout. My issue is when I introduce a new role to a user based on their userid, the changes don't take effect in the active session until the token expires and new one is created. I'd like to update the session claims in real-time without making the user log out and back in. How can this be achieved?
r
hey @himanshukukreja you can use
await session.fetchAndSetClaim(userroleclaim)
as shown in this doc: https://supertokens.com/docs/userroles/managing-roles-and-users
h
So I have used this already This will change the claims at backend (added the roles in my DB) but when I the o access the claim from session it is throwing me the invalid claim exception error. Also Can I do it by using
mergeIntoAccessTokenPayload
(for setting the custom claims into the payload) instead of
await session.fetch_and_set_claim(UserRoleClaim)
function . Will both functions do the same thing??
r
it should change the claim in the access token. Can i see the error message related to "throwing me the invalid claim exception error." ?
also, which backend sdk and which version of it are you using?
h
I am using supertokens-python v0.12.6 I have added this Admin role using this API (This API is being called from my admin dashboard and assigns the roles)
Copy code
@router.put("/user-role/{userId}")
async def assign_role(user_id:str, request_role: UserRole.UserRole,session: SessionContainer = Depends(verify_session()):
    role = request_role.role
    res = await add_role_to_user(user_id, role)
    if isinstance(res, UnknownRoleError):
        logger.error(f"{role} role doesn't Exists")
        raise HTTPException(status_code=404, detail=f"{role} role doesn't Exists")
    if res.did_user_already_have_role:
        logger.error(f"User already has {role} role")
        raise HTTPException(status_code=409, detail=f"User already has {role} role")
    await session.fetch_and_set_claim(UserRoleClaim)
    await session.fetch_and_set_claim(PermissionClaim)
    logger.info(f"Role {role} added to user {user_id}")
    return {"message": f"Role {role} added to user {user_id}"}
So this is my API which I want to protect
Copy code
@router.get("/test_claims")
async def test_excluded(session: SessionContainer = Depends(verify_session(override_global_claim_validators=lambda global_validators, session, user_context: global_validators + [UserRoleClaim.validators.includes("Admin")]))):
      return {"message": "Hello World"}
Now this API gives me this response (not particularly error but an invalid claim exception)
Copy code
{
  "message": "invalid claim",
  "claimValidationErrors": [
    {
      "id": "st-role",
      "reason": {
        "message": "wrong value",
        "expectedToInclude": "Admin",
        "actualValue": [
          "role1",
          "role2",
          "role3"
        ]
      }
    }
  ]
}
r
Can you show me the response headers of the api that updates the role?
h
Copy code
access-control-allow-credentials: true 
 access-control-expose-headers: front-token,front-token,front-token 
 content-length: 71 
 content-type: application/json 
 date: Thu,17 Aug 2023 08:37:25 GMT 
 front-token:  <front-token (jwt)>
 server: uvicorn 
 x-process-time: 1.3052849769592285
r
So it doesn’t have the new cookies.
@KShivendu can help here.
k
@himanshukukreja let me try to replicate this.
r
@KShivendu instead of trying to replicate it
Maybe @himanshukukreja can upload an example app that replicates it
What you can also try @himanshukukreja is to call await session.merge_into_access_token_payload in that api and see if that causes the response to have the set-cookie header
h
I have missed the access token in headers These are the correct response headers
Copy code
HTTP/1.1 200 OK
date: Thu, 17 Aug 2023 08:59:01 GMT
server: uvicorn
content-length: 72
content-type: application/json
front-token: <jwt front token>
access-control-expose-headers: front-token,front-token
set-cookie: sAccessToken=<jwt access token>; Domain=localhost; expires=Sat, 24 Jul 2123 08:59:02 GMT; HttpOnly; Path=/; SameSite=lax
access-control-allow-credentials: true
x-process-time: 1.306797981262207
set-cookie header is present in the response Also I tried to decode the access token from response headers from jwt.io The role claim was not present in it
r
What’s the result of calling add_role_to_user?
h
I have printed the result of add_role_to_user it was
<supertokens_python.recipe.userroles.interfaces.AddRoleToUserOkResult object at 0x000001D501ED3510>
r
Hmm. So adding the role succeeded
h
yes role was added in the db successfully It was also added to the session when session expires and then it got refreshed
r
The new sAccessToken in the response, that token doesn’t have the roles claim you added right? Can you confirm that?
h
yes it doesn't have the new claim
r
Can you remove the fetch and set claim call to the permissions one and just keep the the roles one. What happens?
h
Ok doing it
But Before that I want to inform you that the assign_role API is called by another user while I am passing the user_id of the user to whom I want to assign the role. So here two different users are involved
r
Oh right.
That’s why..
The fetch and set claim only affects the current user’s session
So what you are doing is offline update, and that only get reflected post session refreshing.
h
So it means If I update any claim of session using this offline update method be it role claim or email verification claim or 2FA claim it only reflects in the user's session whenever their session refreshes and I think session refreshes only when the refresh API calls and refresh api only calls when the current session of user expires
r
Yup.
But when using the claim validators, you can set a low time of max age. This will make it so that that user’s session is updated mere quickly. But of course, it means more db lookups
h
Will this be valid for email verification too ? As I have designed an api by which I can remotely change the email verification status of other users
r
Yea.
h
Is there are any resources or docs regarding this which I could refer??
h
👍
5 Views