I've my custom implementation of Spring security in a Spring boot application. So I have my dependencies and I've a class named SecurityImpl which implements for me the login access.
When I get on the browser I'm correctly asked to login with an alert. When I login I have access to all of the #RequestMapping of my Spring Controller correctly. But I remain always logged. Even if I delete the JSESSIONID from my browser, when I make another http request, I am allowed and a new JSESSIONID is created and sent to my browser.
One weird thing is that even when I access with the login for the first time, even when the cookie is authomatically generated, the expiration date is: 1969-12-31T23:59:59.000Z
I've tried to invalidate the session, to delete the cookies from the server, to logout in various ways but nothing. Once logged, I am always allowed.
Here my SecurityImpl.java class which configurates my Spring Security:
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
#Configuration
#Component
public class SecurityImpl extends WebSecurityConfigurerAdapter implements AuthenticationProvider {
public static final String ROLE_ADMIN = "ROLE_ADMIN";
public static final String ROLE_USER = "ROLE_USER";
#Autowired UtenteDao utenteDao;
/* authentication provider part */
#Override
public Authentication authenticate(Authentication auth) throws AuthenticationException {
String username = auth.getName();
String password = auth.getCredentials().toString();
String ruolo = "";
Optional<Utente> utenteOptional = utenteDao.findByCodiceFiscaleAndPassword(username, password);
if(utenteOptional.isPresent()){
ruolo = utenteOptional.get().getRuolo();
}
if(ROLE_ADMIN.equals(ruolo)) {
List<GrantedAuthority> grantedAuths = new ArrayList<>();
grantedAuths.add(new SimpleGrantedAuthority(ROLE_USER));
grantedAuths.add(new SimpleGrantedAuthority(ROLE_ADMIN));
return new UsernamePasswordAuthenticationToken(username, password, grantedAuths);
} else if(ROLE_USER.equals(ruolo)){
List<GrantedAuthority> grantedAuths = new ArrayList<>();
grantedAuths.add(new SimpleGrantedAuthority(ROLE_USER));
return new UsernamePasswordAuthenticationToken(username, password, grantedAuths);
} else {
throw new BadCredentialsException("Autenticazione fallita");
}
}
#Override
public boolean supports(Class<?> auth) {
return auth.equals(UsernamePasswordAuthenticationToken.class);
}
/* websecurity adapter part: erase it if you don't want login alert but default spring login web page */
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(this); //this because it is either a WebSecurityAdapter than an AuthenticationProvider
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().authenticated()
.and()
.httpBasic()
.and()
.logout().clearAuthentication(true).logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/test")
.deleteCookies("JSESSIONID")
.invalidateHttpSession(true);
}
/* per non filtrare con il login alcuni path */
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/test");
}
}
It doesn't work: when I go to /logout I'm redirected to /test correctly but when I ask for a forbidden path I'm allowed without any login.
Then I tried some solution in my #RestController:
#RequestMapping("/logout")
public String logoutPage (UsernamePasswordAuthenticationToken token) {
token.eraseCredentials();
token.setAuthenticated(false);
SecurityContextHolder.getContext().setAuthentication(null);
return "<h1>Logout effettuato con successo.</h1>";
}
then I tried:
#RequestMapping(value = "/logout")
public String loadApp(HttpServletRequest request) {
HttpSession session= request.getSession(false);
SecurityContextHolder.clearContext();
if(session != null) {
session.invalidate();
}
return "<h1>Logout effettuato con successo.</h1>";
}
Then, as a desperate, I tried:
#RequestMapping("/logout")
public String logoutDo(HttpServletRequest request){
HttpSession session= request.getSession(false);
SecurityContextHolder.clearContext();
session= request.getSession(false);
if(session != null) {
session.invalidate();
}
for(Cookie cookie : request.getCookies()) {
cookie.setMaxAge(0);
}
return "<h1>Logout effettuato con successo.</h1>";
}
I tried to use these methods and contemporarily delete my cookie from the browser. I've also tried to preauthorize forbidden method with the annotation #PreAuthorize, in the case they would be allowed (when you open a new browser, before first login, they are NOT allowed even without #PreAuthorize, but when login is made, IS FOREVER!)
The problem was the absence of the usage of showForm(). Without it, yes I insert my credentials within a Javascript alert which is presented to me. But no logout is possible.
So the code changes this way:
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.httpBasic()
.and()
.logout().clearAuthentication(true).logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/test")
.deleteCookies("JSESSIONID")
.invalidateHttpSession(true);
}
Related
I want to allow access for unauthenticated only to a few paths: /everyone1/something1, /everyone2/something2 and /everyone3/**.
For the rest of the paths, I want only authenticated requests to be allowed.
For now, I have "class WebSecurityConfig extends WebSecurityConfigurerAdapter" with:
#Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
JwtAuthenticationFilter jwtAuthenticationFilter = new JwtAuthenticationFilter(
jwtUtils, this.accessCookie, this.selectedRoleScopeCookie);
httpSecurity.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
httpSecurity.cors().and().csrf().disable();
httpSecurity.authorizeRequests()
.antMatchers("/everyone1/something1", "/everyone2/something2", "/everyone3/**")
.permitAll()
.anyRequest().authenticated()
.and().httpBasic().disable();
}
and in "jwtAuthenticationFilter" I set authentication as:
private void setAuthentication2(String username, String someData, boolean authenticated) {
User user = new User(username, "", new ArrayList<>());
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user, null, new ArrayList<>());
if (!authenticated) {
authentication.setAuthenticated(false);
}
AuthenticationDetails authenticationDetails = new AuthenticationDetails(someData);
authentication.setDetails(authenticationDetails);
SecurityContextHolder.getContext().setAuthentication(authentication);
}
Unfortunately, the above configuration blocks every request, both authenticated and unauthenticated.
any help would be appreciated.
Thanks!
This method authorizes some paths for authenticated requests. What you need is:
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/everyone1/something1", "/everyone2/something2", "/everyone3/**");
}
Then anonymous requests can access this path.
I have problem with validating user credentials. When I give correct credentials first time everything goes OK but giving invalid credentials first and then give correct ones I get invalid credentials error. I use Postman Basic
Auth.
My config class:
#Configuration
#EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private UserService userService;
#Autowired
private CustomAuthenticationEntryPoint authenticationEntryPoint;
#Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable().authorizeRequests()
.antMatchers(HttpMethod.POST ,"/login").permitAll()
.antMatchers("/admin").hasAuthority("ADMIN")
.anyRequest().authenticated().and().exceptionHandling().authenticationEntryPoint(authenticationEntryPoint).and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.ALWAYS).and()
.logout()
.deleteCookies("remove")
.invalidateHttpSession(true);
http.rememberMe().disable();
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(this.userService)
.and().eraseCredentials(true);
}
#Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
And my controller class
#PostMapping
public ResponseEntity<?> loginButtonClicked(HttpServletRequest request) {
HttpSession session = request.getSession();
final String authorization = request.getHeader("Authorization");
String[] authorizationData=null;
if (authorization != null && authorization.startsWith("Basic")) {
// Authorization: Basic base64credentials
String base64Credentials = authorization.substring("Basic" .length()).trim();
String credentials = new String(Base64.getDecoder().decode(base64Credentials),
Charset.forName("UTF-8"));
// credentials = username:password
authorizationData = credentials.split(":", 2);
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(authorizationData[0], authorizationData[1],Arrays.asList(new SimpleGrantedAuthority("USER")));
User user = userService.findUserEntityByLogin(authorizationData[0]);
if(user != null && user.getFromWhenAcceptLoginAttempts() != null && (user.getFromWhenAcceptLoginAttempts()).isBefore(LocalDateTime.now())){
// Authenticate the user
Authentication authentication = authenticationManager.authenticate(authRequest);
SecurityContext securityContext = SecurityContextHolder.getContext();
securityContext.setAuthentication(authentication);
// Create a new session and add the security context.
session = request.getSession();
session.setAttribute("SPRING_SECURITY_CONTEXT", securityContext);
return new ResponseEntity<>(new LoginResponseObject(200,"ACCESS GRANTED. YOU HAVE BEEN AUTHENTICATED"), HttpStatus.OK);
}else{
session.getId();
SecurityContextHolder.clearContext();
if(session != null) {
session.invalidate();
}
return new ResponseEntity<>(new ErrorObject(403,"TOO MANY LOGIN REQUESTS","YOU HAVE ENTERED TOO MANY WRONG CREDENTIALS. YOUR ACCOUNT HAS BEEN BLOCKED FOR 15 MINUTES.", "/login"), HttpStatus.FORBIDDEN);
}
}else{
session.getId();
SecurityContextHolder.clearContext();
if(session != null) {
session.invalidate();
}
return new ResponseEntity<>(new ErrorObject(401,"INVALID DATA","YOU HAVE ENTERED WRONG USERNAME/PASSWORD CREDENTIALS", "/login"), HttpStatus.UNAUTHORIZED);
}
}
#Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
#Bean
public ObjectMapper objectMapper(){
return new ObjectMapper();
}
#Bean
public HttpSessionEventPublisher httpSessionEventPublisher() {
return new HttpSessionEventPublisher();
}
The problem is that the request is stored in cache due to your sessionCreationPolicy.
To avoid this problem, you could add .requestCache().requestCache(new NullRequestCache()) in your http security config to override the default request cache configuration, but be careful because this could create another side effect (it depends on your application).
In case you do not need the session, you can choose another session policy:
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).
Another alternative is to relay in Spring's BasicAuthenticationFilter. This filter does all the authentication logic for you. To enable it, you only have to add .httpBasic()in your http security configuration.
You may want to add a custom logic on authentication success/failure. In that case, you only have to create a custom filter (CustomBasicAuthenticationFilter) that extends BasicAuthenticationFilter class and overrides the methods onSuccessfulAuthentication()and onUnsuccessfulAuthentication(). You will not need to add .httpBasic() but you will need to insert your custom filter in the correct place:
.addFilterAfter(new CustomBasicAuthenticationFilter(authenticationManager), LogoutFilter.class).
Any of that 3 solutions will avoid your problem.
Try to write .deleteCookies("JSESSONID") in your SpringSecurityConfig class.
I add Spring Security to my Spring Boot application but after, authentication process server doesn't recognize the same user in next request. I use Angular 5 for UI and maybe this issue in UI side may be requested not include cookies. Help me, please understand why Spring Security doesn't recognize user with already logged in.
In web configuration:
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/rest/user/login").permitAll();
http.csrf().disable()
.authenticationProvider(authenticationProvider())
.exceptionHandling()
.authenticationEntryPoint(unauthorizedHandler)
.and()
.formLogin()
.permitAll()
.loginProcessingUrl("/rest/user/login")
.usernameParameter("username")
.passwordParameter("password")
.successHandler(logInSuccessHandler)
.failureHandler(authFailureHandler)
.and()
.logout().permitAll()
.logoutRequestMatcher(new AntPathRequestMatcher("/rest/user/logout", "POST"))
.logoutSuccessHandler(logoutHandler)
.and()
.sessionManagement()
.maximumSessions(1);
http.authorizeRequests().anyRequest().authenticated();
}
Session manager is activated .sessionManagement().maximumSessions(1);
And authentication complete successful my UserDetailsService implementation correctly return User object by login and password. But next request to this controller:
#GetMapping("/rest/list")
public RestList list() {
...
}
Redirect to :
#Component
public class UnauthorizedHandler implements AuthenticationEntryPoint {
#Override
public void commence(
HttpServletRequest request,
HttpServletResponse response,
AuthenticationException authException) throws IOException {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException.getMessage());
}
}
I have the logged in checker:
#Component
public class LoggedInChecker {
public User getLoggedInUser() {
User user = null;
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null) {
Object principal = authentication.getPrincipal();
// principal can be "anonymousUser" (String)
if (principal instanceof UserDetailsImpl) {
UserDetailsImpl userDetails = (UserDetailsImpl) principal;
user = userDetails.getUser();
}
}
return user;
}
}
I use this checker in UserService
#Service
public class UserServiceImpl implements UserService {
#Autowired
private UserRepository userRepository;
#Autowired
private LoggedInChecker loggedInChecker;
#Override
public User getUserByUsername(String username) {
return userRepository.findByUsername(username);
}
#Override
public List<String> getPermissions(String username) {
User user = userRepository.findByUsername(username);
return nonNull(user) ? user.getRoles().stream().map(Role::getRole).collect(toList()) : Lists.newArrayList();
}
#Override
public User getCurrentUser() {
return loggedInChecker.getLoggedInUser();
}
#Override
public Boolean isCurrentUserLoggedIn() {
// This place must call but nothing happening
return nonNull(loggedInChecker.getLoggedInUser());
}
}
I thought Spring automatically call my UserSevice for check authorization. But how to specify HttpSecurity for save information about the session?
In Angular side I use HttpClient:
#Injectable()
export class CoreApi {
private baseUrl = 'http://localhost:8080/rest/';
constructor(public http: HttpClient) {
}
public get(url: string = ''): Observable<any> {
return this.http.get(this.getUrl(url));
}
}
Maybe You know how to specify Spring Security for checking auth with LoggedInChecker or another way for this reslt, let me know. Thank You!
I have implemented the spring security with LDAP using Spring Boot. I'm able to successfully bind with my company LDAP server but with hard-coded values. This is the only way I can bind with my company LDAP server and proceed further since I do not know the Administrator/Generic UserDN or Password to make a successful bind. The company does not provide me the Admin credentials due to some confidential reasons.
I would like to set the UserDn and Password of the ContextSource with the username and password entered by the user in the login form. But the problem here is the SecurityConfig class is scanned at the time the Tomcat server is started and later after the login process the control does not come to the SecurityConfig class at all. How can I solve this problem? Need some assistance.
This is my SecurityConfig class:
#EnableWebSecurity
#Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private CustomAuthenticationFailureHandler customAuthFailureHandler;
#Autowired
private CustomAuthenticationSuccessHandler customAuthSuccessHandler;
#Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.authorizeRequests()
.anyRequest().fullyAuthenticated()
.and()
.formLogin()
.loginPage("/login").permitAll()
.loginProcessingUrl("/sign-in")
.usernameParameter("userid")
.passwordParameter("password")
.successHandler(customAuthSuccessHandler)
.failureHandler(customAuthFailureHandler)
.permitAll()
.and()
.logout()
.logoutSuccessUrl("/logout")
.permitAll()
.and()
.csrf().disable();
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(ldapAuthProvider());
}
#Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
#Bean
public AuthenticationProvider ldapAuthProvider() throws Exception {
DefaultSpringSecurityContextSource contextSource = new DefaultSpringSecurityContextSource("ldaps://some.domain.com:3269/");
contextSource.setUserDn("username#domain.com"); // Here I want to set the username from Login screen
contextSource.setPassword("password"); // also password from login screen
contextSource.afterPropertiesSet();
String userSearchFilter = "(sAMAccountName=username)"; // Here too I need to set username from login screen
LdapUserSearch ldapUserSearch = new FilterBasedLdapUserSearch("dc=domain,dc=com", userSearchFilter, contextSource);
BindAuthenticator bindAuth = new BindAuthenticator(contextSource);
bindAuth.setUserSearch(ldapUserSearch);
LdapAuthenticationProvider ldapAuthProvider = new LdapAuthenticationProvider(bindAuth);
return ldapAuthProvider;
}
}
I have created an AuthenticationProvider bean method and I'm setting it in the AuthenticationManagerBuilder. I also tried creating a CustomAuthenticationProvider but there again I had to check with the hard-coded username and password :(
I finally got it working.. :) I found what I want here . (Ali Miskeen's answer)
I tried with the CustomAuthenticationProvider approach itself but this time, I checked for authentication using the traditional JNDI LDAP approach. I also wanted to check for 3 different LDAP servers hence this approach best suited for my application.
Here is my complete CustomAuthenticationProvider implementation:
#Component
public class CustomAuthenticationProvider implements AuthenticationProvider {
private static final String AT_DOMAIN_COM = "#domain.com";
private static final String SINGLE_SPACE = " ";
#Value("${ldap.url.for.server1}")
private String ldapUrlForServer1; // url set in application.properties
#Value("${ldap.url.for.server2}")
private String ldapUrlForServer2;
#Value("${ldap.url.for.server3}")
private String ldapUrlForServer3;
#Value("${ldap.jndi.context.factory}")
private String ldapContextFactory;
#Value("${ldap.authentication.type}")
private String ldapAuthenticationType; // auth type is "simple"
#Override
public Authentication authenticate(Authentication auth) throws AuthenticationException {
String username = auth.getName();
String password = auth.getCredentials().toString();
if (isLdapRegisteredUser(username, password)) {
// use the credentials and authenticate against a third-party system
return new UsernamePasswordAuthenticationToken(username, password, new ArrayList<>());
} else {
return null;
}
}
boolean isLdapRegisteredUser(String username, String password) {
boolean result = false;
Hashtable<String, String> env = new Hashtable<>();
LdapContext ctx = null;
try {
env.put(Context.INITIAL_CONTEXT_FACTORY, ldapContextFactory);
env.put(Context.SECURITY_AUTHENTICATION, ldapAuthenticationType);
env.put(Context.SECURITY_PRINCIPAL, username + AT_DOMAIN_COM);
env.put(Context.SECURITY_CREDENTIALS, password);
// here I'm checking for 3 different LDAP servers
env.put(Context.PROVIDER_URL, ldapUrlForServer1 + SINGLE_SPACE + ldapUrlForServer2 + SINGLE_SPACE + ldapUrlForServer3);
ctx = new InitialLdapContext(env, null);
if (ctx != null) {
result = true;
String selectedLdapUrl = ctx.getEnvironment().get(Context.PROVIDER_URL).toString();
// do further operations with "ctx" if needed
System.out.println("selected LDAP url is: " + selectedLdapUrl);
System.out.println("Connection Successful!");
}
} catch(NamingException nex) {
nex.printStackTrace();
} finally {
if (ctx != null) {
try {
ctx.close();
} catch (Exception ex) {
}
}
}
return result;
}
#Override
public boolean supports(Class<?> auth) {
return auth.equals(UsernamePasswordAuthenticationToken.class);
}
}
And here is my SecurityConfig implementation:
#EnableWebSecurity
#Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private CustomAuthenticationProvider customAuthProvider;
#Autowired
private CustomAuthenticationFailureHandler customAuthFailureHandler;
#Autowired
private CustomAuthenticationSuccessHandler customAuthSuccessHandler;
#Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.authorizeRequests()
.antMatchers("/css/**").permitAll()
.antMatchers("/fonts/**").permitAll()
.antMatchers("/images/**").permitAll()
.antMatchers("/js/**").permitAll()
.anyRequest().fullyAuthenticated()
.and()
.formLogin()
.loginPage("/login").permitAll()
.loginProcessingUrl("/sign-in")
.usernameParameter("userid")
.passwordParameter("password")
.successHandler(customAuthSuccessHandler)
.failureHandler(customAuthFailureHandler)
.permitAll()
.and()
.logout()
.clearAuthentication(true)
.logoutSuccessUrl("/login").permitAll()
.deleteCookies("JSESSIONID")
.invalidateHttpSession(true)
.and()
.csrf().disable();
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(customAuthProvider);
}
}
Hope this helps :) Happy coding...
I use spring security in my project and I use custom authonticate. I save user from code.
#Override
public void saveUser(AuthLkUser lkUser) {
final List<GrantedAuthority> grantedAuths = new ArrayList<>();
GrantedAuthority grantedAuthority = new SimpleGrantedAuthority("ROLE_USER");
grantedAuths.add(grantedAuthority);
UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(lkUser.getMsisdn(), lkUser.getPricePlan(), grantedAuths);
SecurityContextHolder.getContext().setAuthentication(result);
}
It work normaly. But after succsessufull login, I can open login page again.
I need disable possibility open login page after succsessufull login. I tried this:
.antMatchers("/login", "/default/login").access("hasRole('ANONYMOUS')")
But user with "USER" role can open login page too.
I tried
#Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
#Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication auth) throws IOException, ServletException {
// initialization logic after login
// redirect
HttpSession session = request.getSession();
SavedRequest savedReq = (SavedRequest) session.getAttribute("SAVED_REQUEST");
if (savedReq == null) {
response.sendRedirect(request.getContextPath() + "/landing");
}
else {
response.sendRedirect(savedReq.getRedirectUrl());
}
}
}
and setup to config
#Autowired
private MyAuthenticationSuccessHandler myAuthenticationSuccessHandler;
.successHandler(myAuthenticationSuccessHandler)
But after succsessufull login this method not called.
How can I open main page if user is logined and tried open login page?
and why my myAuthenticationSuccessHandler not called?
it is my config
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private MyAuthenticationSuccessHandler myAuthenticationSuccessHandler;
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/", "/index").access("hasRole('USER')")
// .antMatchers("/login", "/default/login").access("hasRole('ANONYMOUS')")
.and()
.formLogin()
.loginPage("/login")
.loginProcessingUrl("/j_spring_security_check")
.successHandler(myAuthenticationSuccessHandler)
.permitAll();
http.csrf()
.disable()
.authorizeRequests()
.antMatchers("/resources/**", "/**").permitAll()
.anyRequest().permitAll()
.and();
}
}
I think you need to add a controller in which you need to check for login request whether User is already logged in or not. If not logged in than display login page else redirect to home page. Following is such sample controller:
#Controller
#RequestMapping("/")
public class IndexController {
#RequestMapping(value="/login",method = RequestMethod.GET)
public String index(){
if(SecurityUtils.isUserLoggedIn())
return "redirect:/home";
return "login";
}
}
And following is sample SecurityUtils.java class which is utility class having method to check whether user is logged in or not :
public class SecurityUtils {
public static boolean isUserLoggedIn(){
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if(null != authentication){
return (authentication.isAuthenticated() && !(authentication instanceof AnonymousAuthenticationToken));
}else{
return false;
}
}
}