SecurityUtils { public static boolean isAuthenticated() { SecurityContext securityContext = SecurityContextHolder.getContext(); Collection<? extends GrantedAuthority> authorities = securityContext.getAuthentication().getAuthorities(); if (authorities != null) { for (GrantedAuthority authority : authorities) { if (authority.getAuthority().equals(AuthoritiesConstants.ANONYMOUS)) { return false; } } } return true; } private  SecurityUtils(); static String getCurrentLogin(); static boolean isAuthenticated(); static boolean isUserInRole(String authority);  }
@Test public void testIsAuthenticated() { SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "admin")); SecurityContextHolder.setContext(securityContext); boolean isAuthenticated = SecurityUtils.isAuthenticated(); assertThat(isAuthenticated).isTrue(); }
@Test public void testAnonymousIsNotAuthenticated() { SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); Collection<GrantedAuthority> authorities = new ArrayList<>(); authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.ANONYMOUS)); securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("anonymous", "anonymous", authorities)); SecurityContextHolder.setContext(securityContext); boolean isAuthenticated = SecurityUtils.isAuthenticated(); assertThat(isAuthenticated).isFalse(); }