/** * Creates an {@link Authentication} object that represents this user. * <p> * This method checks with {@link SecurityRealm} if the user is a valid user that can login to the security realm. * If {@link SecurityRealm} is a kind that does not support querying information about other users, this will * use {@link LastGrantedAuthoritiesProperty} to pick up the granted authorities as of the last time the user has * logged in. * * @throws UsernameNotFoundException If this user is not a valid user in the backend {@link SecurityRealm}. * @since 1.419 */ public @Nonnull Authentication impersonate() throws UsernameNotFoundException { return this.impersonate(this.getUserDetailsForImpersonation()); }
/** * Note: if the token does not exist or does not match, we do not use {@link SecurityListener#fireFailedToAuthenticate(String)} * because it will be done in the {@link BasicHeaderRealPasswordAuthenticator} in the case the password is not valid either */ @Override public Authentication authenticate(HttpServletRequest req, HttpServletResponse rsp, String username, String password) throws ServletException { User u = BasicApiTokenHelper.isConnectingUsingApiToken(username, password); if(u != null) { Authentication auth; try { UserDetails userDetails = u.getUserDetailsForImpersonation(); auth = u.impersonate(userDetails); SecurityListener.fireAuthenticated(userDetails); } catch (UsernameNotFoundException x) { // The token was valid, but the impersonation failed. This token is clearly not his real password, // so there's no point in continuing the request processing. Report this error and abort. LOGGER.log(WARNING, "API token matched for user " + username + " but the impersonation failed", x); throw new ServletException(x); } catch (DataAccessException x) { throw new ServletException(x); } req.setAttribute(BasicHeaderApiTokenAuthenticator.class.getName(), true); return auth; } return null; }
UserDetails userDetails = u.getUserDetailsForImpersonation(); Authentication auth = u.impersonate(userDetails);