Spring security delete user - session still active

2020-07-20 04:23发布

问题:

I got a simple spring security application with a user administration. An admin should be able to create/update/delete users on the database (via hibernate).

If a user is updated, I am reloading the authentication of the user which is currently logged in. That's done with the following code (according to this example):

SecurityContextHolder.getContext().setAuthentication(updatedAuthentication);

My question is: What can I do if a user is deleted? If I delete a user, already active sessions remain active and I don't know how to update them. I can still navigate to every page I was able to go to before.

Is there a way to tell spring that a session should be revalidated or something like that? Did I miss anything important?

回答1:

On each request you should check your database for User existence. Steps :

  1. Take the userid from session, check it is in the database or not.
  2. If not in the database invalidate the session and redirect to login page again.
  3. Wrap those above two stpes in a method and call it on each request. (If common method is there use that or create e Listener)

Also you can check the following link if it helps. http://forum.spring.io/forum/spring-projects/security/35809-how-to-let-admin-to-force-user-to-logout

Another helpful link is http://docs.spring.io/spring-security/site/docs/3.1.x/reference/springsecurity-single.html#list-authenticated-principals



回答2:

SecurityContextRepository

From Spring Security 3.0, the job of loading and storing the security context is now delegated to a separate strategy interface

You can provide a NullSecurityContextRepository in order to avoid the storage of security context information.

I did something like this:

@EnableWebSecurity
public class CustomSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        // Other security configuration...

        http.securityContext().securityContextRepository(new NullSecurityContextRepository());
    }

}