Tomas Bisciak
Tomas Bisciak

Reputation: 2841

How to logout specific User in Spring ? Programatically

So i have application where users can log in via social networks or normal login. I want to be able to log into admin account and BAN a user, When i change status of user to Banned, I want to log him out via code! How can i achieve that?

I added Session listener

    @Component
public class SessionListener implements HttpSessionListener {

    private static int totalActiveSessions;
    List<HttpSession> sessionList = new ArrayList<>();

    public static int getTotalActiveSession() {
        return totalActiveSessions;
    }

    @Override
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {
        totalActiveSessions++;
        if (sessionList.contains(httpSessionEvent.getSession())) {
            sessionList.add(httpSessionEvent.getSession());
        }
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
        totalActiveSessions--;
        if (sessionList.contains(httpSessionEvent.getSession())) {
            sessionList.remove(httpSessionEvent.getSession());
        }
    }
}

While debugging - I dont know how to identify user, And also session seems to be created sooner then actually user logs in, just by visiting site, doesnt seem like proper way to do it.

Upvotes: 0

Views: 259

Answers (2)

aksappy
aksappy

Reputation: 3400

You could also use a Servlet Filter to filter all the requests and see whether the user is active or not. Let me know if you need an example.

Upvotes: 0

Mohit Sharma
Mohit Sharma

Reputation: 492

Create a meta user information model like

public class UserInfoContext implements Serializable {

private static final long serialVersionUID = 1L;

private String id;
private String name;
private String authType;

// more fields type of requirements

// Getter and Setters

// Constructor

}

At the time of both basic or OAuth authentication, put the meta information into this object and add this into the Session

UserInfoContext context = new UserInfoContext(id,name,type);

HttpSession session = request.getSession();
session.setAttributes("UserContext",context); 

The above session listener will be triggered when the session is created

You can get all the session list by setting getAllSessionList() in the SessionListener

public List<HttpSession> getAllSessionList(){
    return this.sessionList;
}

Suppose you want to ban a session and invalidate the user, when you are implementing the business logic get the particular session and invalidate it by using

session.invalidate();

Also tried to find the JSESSIONID id of the user and add it into the meta context class members, you can also need to invalidate it also

This may help you to get the required solution

Upvotes: 4

Related Questions