Spring Security(Third Edition)
上QQ阅读APP看书,第一时间看更新

The UserContext interface

Like most applications, our application requires us to interact with the currently logged-in user. We have created a very simple interface called UserContext to manage the currently logged-in user as follows:

    //src/main/java/com/packtpub/springsecurity/service/UserContext.java

public interface UserContext {
CalendarUser getCurrentUser();
void setCurrentUser(CalendarUser user);
}

This means that our application can call UserContext.getCurrentUser() to obtain the details of the currently logged-in user. It can also call UserContext.setCurrentUser(CalendarUser) to specify which user is logged in. Later in this chapter, we will explore how we can write an implementation of this interface that uses Spring Security to access our current user and obtain their details using SecurityContextHolder.

Spring Security provides quite a few different methods for authenticating a user. However, the net result is that Spring Security will populate o.s.s.core.context.SecurityContext with o.s.s.core.Authentication. The Authentication object represents all the information we gathered at the time of authentication (username, password, roles, and so on). The SecurityContext interface is then set on the o.s.s.core.context.SecurityContextHolder interface. This means that Spring Security and developers can use SecurityContextHolder to obtain information about the currently logged-in user. An example of obtaining the current username is illustrated as follows:

    String username = SecurityContextHolder.getContext()
.getAuthentication()
.getName();

It should be noted that null checks should always be done on the Authentication object, as this could be null if the user is not logged in.