Reload user role after change without re-logging

后端 未结 1 763
小鲜肉
小鲜肉 2021-01-27 20:55

How to refresh logged in user role e.g. when it has been changed by admin user? I\'ve found the always_authenticate_before_granting security option (it\'s not inclu

相关标签:
1条回答
  • 2021-01-27 21:34

    Tl;dr I'm afraid you will have to introduce a mechanism of your own in order to make this work.

    The session token is stored inside the user's session. This will have quite an impact on your application's performance, because each time a call to the database will be required in order to check if the role had changed.

    So you will need a request listener which will compare database role with current user role, and if it is not same, replace the token in the session, this time with new role list, eg. (pseudo code):

    sessionUser = tokenStorage.token.user
    databaseUser = userRepository.find(sessionUser.id)
    
    if sessionUser.roles !== databaseUser.roles
        tokenStorage.setToken(new PostAuthenticationGuardToken(…))
    

    or use a cache as a flag carrier to notify the user about the change. This method is going to be much quicker for sure.

    sessionUser = tokenStorage.token.user
    
    // of course the flag has to be set when the user's role gets changed
    cacheToken = 'users.role_reload.' . sessionUser.id
    
    if cache.has(cacheToken)
        databaseUser = userRepository.find(sessionUser.id)
        tokenStorage.setToken(new PostAuthenticationGuardToken(…))
        cache.remove(cacheToken)
    

    Either way the user has to ask the application has there been role change, on each request.

    0 讨论(0)
提交回复
热议问题