> Markdown version of [Authentication Context](https://vaadin.com/docs/next/flow/security/spring/authentication-context). Section index: [llms.txt](https://vaadin.com/docs/next/flow/llms.txt)

# Authentication Context

In a Spring Security application, Vaadin provides the `AuthenticationContext` class to access the logged-in user, to check the user’s roles, and to log the user out. It’s a Spring bean, which you can inject into views and services. It provides the following methods:

| Method                                                       | Description                                                                                                                          |
| ------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------ |
| `isAuthenticated()`                                          | Checks whether a user is logged in. Spring Security’s anonymous user doesn’t count as logged in.                                     |
| `getAuthenticatedUser(Class)`                                | Returns the user object, such as `UserDetails`, as an `Optional`. Throws a `ClassCastException` if the user isn’t of the given type. |
| `getGrantedRoles()`                                          | Returns the roles of the user, without the role prefix: `ROLE_USER` is returned as `USER`.                                           |
| `hasRole()`, `hasAnyRole()`, `hasAllRoles()`                 | Check whether the user has the given roles. Give the roles without the role prefix.                                                  |
| `getGrantedAuthorities()`                                    | Returns the authorities of the user.                                                                                                 |
| `hasAuthority()`, `hasAnyAuthority()`, `hasAllAuthorities()` | Check whether the user has the given authorities.                                                                                    |
| `logout()`                                                   | Logs the user out through Spring Security, and redirects to the configured logout success URL.                                       |

`AuthenticationContext` doesn’t implement `java.io.Serializable` by design. Fields of views that reference it must therefore be `transient`.

## <a id="authenticated-user-information"></a>Authenticated User Information

The following example uses `AuthenticationContext` to retrieve the authenticated user’s information and render a button only if the user has the `ADMIN` role:

```java
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.html.H2;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.router.Route;
import com.vaadin.flow.server.auth.AnonymousAllowed;
import com.vaadin.flow.spring.security.AuthenticationContext;
import org.springframework.security.core.userdetails.UserDetails;

@Route(value = "my-view")
@AnonymousAllowed
public class MyView extends VerticalLayout {

    public MyView(AuthenticationContext authContext) {

        add(new H2("Everyone can see this"));

        // Ensure that the class used by getAuthenticatedUser() matches the object type created
        // by the authentication providers used in Spring Security.
        authContext.getAuthenticatedUser(UserDetails.class).ifPresent(user -> {
            add(new H2("Welcome " + user.getUsername()));
            if (authContext.hasRole("ADMIN")) { // Not "ROLE_ADMIN".
                add(new Button("Admin button"));
            } else {
                add(new H2("You are not an admin"));
            }
        });
    }
}
```

## <a id="log-out-capability"></a>Logging Out

To initiate logging out of a web application, you would typically provide a log-out button. Here’s an implementation of a log-out button shown on the header of the main layout that uses the `AuthenticationContext` component:

`MainLayout.java`

```java
@AnonymousAllowed // (1)
public class MainLayout extends AppLayout {

    private final transient AuthenticationContext authContext;

    public MainLayout(AuthenticationContext authContext) {
        this.authContext = authContext;

        H1 logo = new H1("Vaadin CRM");
        logo.addClassName("logo");
        HorizontalLayout
        header =
        authContext.getAuthenticatedUser(UserDetails.class)
                .map(user -> {
                    Button logout = new Button("Logout", click ->
                            this.authContext.logout());
                    Span loggedUser = new Span("Welcome " + user.getUsername());
                    return new HorizontalLayout(logo, loggedUser, logout);
                }).orElseGet(() -> new HorizontalLayout(logo));

        // Other page components omitted.

        addToNavbar(header);
    }
}
```

1. A layout needs an access annotation of its own, as described in [Parent Layouts](https://vaadin.com/docs/next/flow/security/access-control/annotations.md#parent-layouts). This layout hosts both public and protected views, so it allows anonymous access. Its header only shows the log-out button to authenticated users.

## <a id="checking-roles"></a>Checking Roles

`AuthenticationContext` also covers programmatic access checks elsewhere in the application, such as deciding whether to render a navigation item or to enable an action. Roles are given without the role prefix, which `AuthenticationContext` adds when comparing against the granted authorities, as described in [Roles & Authorities](https://vaadin.com/docs/next/flow/security/spring/roles-and-authorities.md). The following example shows a navigation item only to administrators:

```java
SideNav nav = new SideNav();
nav.addItem(new SideNavItem("Dashboard", DashboardView.class));
if (authContext.hasRole("ADMIN")) { // Not "ROLE_ADMIN".
    nav.addItem(new SideNavItem("Administration", AdminView.class));
}
```

Hiding a navigation item is a usability measure, not a security measure. The view it points to still needs its own access annotation, since a user can navigate there by entering the URL directly.

## <a id="custom-security-utilities"></a>Custom Security Utilities

`AuthenticationContext` covers what most applications need. If you want a security utility of your own — for example, to combine the user lookup with application-specific logic, such as loading your own user entity from a repository — you can build it directly on the Spring Security API. Here’s a basic example that shows the underlying calls:

`SecurityService.java`

```java
@Component
public class SecurityService {

    private static final String LOGOUT_SUCCESS_URL = "/";

    public Optional<UserDetails> getAuthenticatedUser() {
        Authentication authentication = SecurityContextHolder.getContext()
                .getAuthentication();
        if (authentication != null
                && authentication.getPrincipal() instanceof UserDetails userDetails) {
            return Optional.of(userDetails);
        }
        // Anonymous or no authentication.
        return Optional.empty();
    }

    public void logout() {
        UI.getCurrentOrThrow().getPage().setLocation(LOGOUT_SUCCESS_URL);
        SecurityContextLogoutHandler logoutHandler = new SecurityContextLogoutHandler();
        logoutHandler.logout(
                VaadinServletRequest.getCurrent().getHttpServletRequest(), null,
                null);
    }
}
```

You can inject the service into views in the same way as `AuthenticationContext`. Unlike `AuthenticationContext.logout()`, the `logout()` method in this example only clears the security context and redirects to a fixed URL. It doesn’t run the other logout handlers or the logout success URL configured for Spring Security.
