|
| 1 | +/* |
| 2 | + * Copyright 2000-2022 Vaadin Ltd. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); you may not |
| 5 | + * use this file except in compliance with the License. You may obtain a copy of |
| 6 | + * the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
| 12 | + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the |
| 13 | + * License for the specific language governing permissions and limitations under |
| 14 | + * the License. |
| 15 | + */ |
| 16 | +package com.vaadin.flow.spring.security; |
| 17 | + |
| 18 | +import java.io.IOException; |
| 19 | +import java.io.Serializable; |
| 20 | +import java.util.List; |
| 21 | +import java.util.Optional; |
| 22 | + |
| 23 | +import jakarta.servlet.ServletException; |
| 24 | +import jakarta.servlet.http.HttpServletRequest; |
| 25 | +import jakarta.servlet.http.HttpServletResponse; |
| 26 | +import org.slf4j.Logger; |
| 27 | +import org.slf4j.LoggerFactory; |
| 28 | +import org.springframework.security.authentication.AnonymousAuthenticationToken; |
| 29 | +import org.springframework.security.core.Authentication; |
| 30 | +import org.springframework.security.core.context.SecurityContext; |
| 31 | +import org.springframework.security.core.context.SecurityContextHolder; |
| 32 | +import org.springframework.security.web.authentication.logout.CompositeLogoutHandler; |
| 33 | +import org.springframework.security.web.authentication.logout.LogoutHandler; |
| 34 | +import org.springframework.security.web.authentication.logout.LogoutSuccessHandler; |
| 35 | + |
| 36 | +import com.vaadin.flow.component.UI; |
| 37 | +import com.vaadin.flow.server.VaadinServletRequest; |
| 38 | +import com.vaadin.flow.server.VaadinServletResponse; |
| 39 | + |
| 40 | +/** |
| 41 | + * The authentication context of the application. |
| 42 | + * <p> |
| 43 | + * An instance of this class is available for injection as bean in view and |
| 44 | + * layout classes. |
| 45 | + * |
| 46 | + * It allows to access authenticated user information and to initiate the logout |
| 47 | + * process. |
| 48 | + * |
| 49 | + * @author Vaadin Ltd |
| 50 | + * @since 23.3 |
| 51 | + */ |
| 52 | +public class AuthenticationContext implements Serializable { |
| 53 | + |
| 54 | + private static final Logger LOGGER = LoggerFactory |
| 55 | + .getLogger(AuthenticationContext.class); |
| 56 | + |
| 57 | + private transient LogoutSuccessHandler logoutSuccessHandler; |
| 58 | + |
| 59 | + private transient CompositeLogoutHandler logoutHandler; |
| 60 | + |
| 61 | + /** |
| 62 | + * Gets an {@link Optional} with an instance of the current user if it has |
| 63 | + * been authenticated, or empty if the user is not authenticated. |
| 64 | + * |
| 65 | + * Anonymous users are considered not authenticated. |
| 66 | + * |
| 67 | + * @param <U> |
| 68 | + * the type parameter of the expected user instance |
| 69 | + * @param userType |
| 70 | + * the type of the expected user instance |
| 71 | + * @return an {@link Optional} with the current authenticated user, or empty |
| 72 | + * if none available |
| 73 | + * @throws ClassCastException |
| 74 | + * if the current user instance does not match the given |
| 75 | + * {@code userType}. |
| 76 | + */ |
| 77 | + public <U> Optional<U> getAuthenticatedUser(Class<U> userType) { |
| 78 | + return getAuthentication().map(Authentication::getPrincipal) |
| 79 | + .map(userType::cast); |
| 80 | + } |
| 81 | + |
| 82 | + /** |
| 83 | + * Indicates whether a user is currently authenticated. |
| 84 | + * |
| 85 | + * Anonymous users are considered not authenticated. |
| 86 | + * |
| 87 | + * @return {@literal true} if a user is currently authenticated, otherwise |
| 88 | + * {@literal false} |
| 89 | + */ |
| 90 | + public boolean isAuthenticated() { |
| 91 | + return getAuthentication().map(Authentication::isAuthenticated) |
| 92 | + .orElse(false); |
| 93 | + } |
| 94 | + |
| 95 | + /** |
| 96 | + * Initiates the logout process of the current authenticated user by |
| 97 | + * invalidating the local session and then notifying |
| 98 | + * {@link org.springframework.security.web.authentication.logout.LogoutHandler}. |
| 99 | + */ |
| 100 | + public void logout() { |
| 101 | + HttpServletRequest request = VaadinServletRequest.getCurrent() |
| 102 | + .getHttpServletRequest(); |
| 103 | + HttpServletResponse response = VaadinServletResponse.getCurrent() |
| 104 | + .getHttpServletResponse(); |
| 105 | + Authentication auth = SecurityContextHolder.getContext() |
| 106 | + .getAuthentication(); |
| 107 | + |
| 108 | + final UI ui = UI.getCurrent(); |
| 109 | + logoutHandler.logout(request, response, auth); |
| 110 | + ui.accessSynchronously(() -> { |
| 111 | + try { |
| 112 | + logoutSuccessHandler.onLogoutSuccess(request, response, auth); |
| 113 | + } catch (IOException | ServletException e) { |
| 114 | + // Raise a warning log message about the failure. |
| 115 | + LOGGER.warn( |
| 116 | + "There was an error notifying the logout handler about the user logout", |
| 117 | + e); |
| 118 | + } |
| 119 | + }); |
| 120 | + } |
| 121 | + |
| 122 | + /** |
| 123 | + * Sets component to handle logout process. |
| 124 | + * |
| 125 | + * This method should be invoked after deserialization to refresh required |
| 126 | + * transient fields. |
| 127 | + * |
| 128 | + * @param logoutSuccessHandler |
| 129 | + * {@link LogoutSuccessHandler} instance, not {@literal null}. |
| 130 | + * @param logoutHandlers |
| 131 | + * {@link LogoutHandler}s list, not {@literal null}. |
| 132 | + */ |
| 133 | + void setLogoutHandlers(LogoutSuccessHandler logoutSuccessHandler, |
| 134 | + List<LogoutHandler> logoutHandlers) { |
| 135 | + this.logoutSuccessHandler = logoutSuccessHandler; |
| 136 | + this.logoutHandler = new CompositeLogoutHandler(logoutHandlers); |
| 137 | + } |
| 138 | + |
| 139 | + private static Optional<Authentication> getAuthentication() { |
| 140 | + return Optional.of(SecurityContextHolder.getContext()) |
| 141 | + .map(SecurityContext::getAuthentication) |
| 142 | + .filter(auth -> !(auth instanceof AnonymousAuthenticationToken)); |
| 143 | + } |
| 144 | + |
| 145 | + /* For testing purposes */ |
| 146 | + LogoutSuccessHandler getLogoutSuccessHandler() { |
| 147 | + return logoutSuccessHandler; |
| 148 | + } |
| 149 | + |
| 150 | + /* For testing purposes */ |
| 151 | + CompositeLogoutHandler getLogoutHandler() { |
| 152 | + return logoutHandler; |
| 153 | + } |
| 154 | + |
| 155 | +} |
0 commit comments