java.lang.NoSuchMethodError: '.authentication.UsernamePasswordAuthenticationToken .unauthenticated(java.lang.Object, java.lang.Object)' - spring

I am trying to login in spring boot MVC web application. but I am getting the below error.
java.lang.NoSuchMethodError: 'org.springframework.security.authentication.UsernamePasswordAuthenticationToken org.springframework.security.authentication.UsernamePasswordAuthenticationToken.unauthenticated(java.lang.Object, java.lang.Object)'
at org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.attemptAuthentication(UsernamePasswordAuthenticationFilter.java:81) ~[spring-security-web-5.7.1.jar:5.7.1]
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:227) ~[spring-security-web-5.7.1.jar:5.7.1]
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:217) ~[spring-security-web-5.7.1.jar:5.7.1]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.7.1.jar:5.7.1]
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:103) ~[spring-security-web-5.7.1.jar:5.7.1]
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:89) ~[spring-security-web-5.7.1.jar:5.7.1]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.7.1.jar:5.7.1]
at org.springframework.security.web.header.HeaderWriterFilter.doHeadersAfter(HeaderWriterFilter.java:90) ~[spring-security-web-5.7.1.jar:5.7.1]
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:75) ~[spring-security-web-5.7.1.jar:5.7.1]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.16.jar:5.3.16]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.7.1.jar:5.7.1]
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:112) ~[spring-security-web-5.7.1.jar:5.7.1]
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:82) ~[spring-security-web-5.7.1.jar:5.7.1]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.7.1.jar:5.7.1]
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:55) ~[spring-security-web-5.7.1.jar:5.7.1]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.16.jar:5.3.16]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.7.1.jar:5.7.1]
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:211) ~[spring-security-web-5.7.1.jar:5.7.1]
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:183) ~[spring-security-web-5.7.1.jar:5.7.1]
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:354) ~[spring-web-5.3.16.jar:5.3.16]
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:267) ~[spring-web-5.3.16.jar:5.3.16]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.58.jar:9.0.58]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.58.jar:9.0.58]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.3.16.jar:5.3.16]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.16.jar:5.3.16]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.58.jar:9.0.58]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.58.jar:9.0.58]
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.3.16.jar:5.3.16]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.16.jar:5.3.16]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.58.jar:9.0.58]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.58.jar:9.0.58]
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:94) ~[spring-web-5.3.16.jar:5.3.16]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.16.jar:5.3.16]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.58.jar:9.0.58]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.58.jar:9.0.58]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.3.16.jar:5.3.16]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.16.jar:5.3.16]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.58.jar:9.0.58]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.58.jar:9.0.58]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197) ~[tomcat-embed-core-9.0.58.jar:9.0.58]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) ~[tomcat-embed-core-9.0.58.jar:9.0.58]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:540) ~[tomcat-embed-core-9.0.58.jar:9.0.58]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135) ~[tomcat-embed-core-9.0.58.jar:9.0.58]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) ~[tomcat-embed-core-9.0.58.jar:9.0.58]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) ~[tomcat-embed-core-9.0.58.jar:9.0.58]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:359) ~[tomcat-embed-core-9.0.58.jar:9.0.58]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:399) ~[tomcat-embed-core-9.0.58.jar:9.0.58]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) ~[tomcat-embed-core-9.0.58.jar:9.0.58]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:889) ~[tomcat-embed-core-9.0.58.jar:9.0.58]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1735) ~[tomcat-embed-core-9.0.58.jar:9.0.58]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat-embed-core-9.0.58.jar:9.0.58]
at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191) ~[tomcat-embed-core-9.0.58.jar:9.0.58]
at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659) ~[tomcat-embed-core-9.0.58.jar:9.0.58]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-9.0.58.jar:9.0.58]
at java.base/java.lang.Thread.run(Thread.java:832) ~[na:na]
#Configuration
#ComponentScan(basePackages="com.matoshree")
#EnableGlobalMethodSecurity(prePostEnabled = true)
#EnableWebSecurity
public class WebSecurityMultiConfig {
#Order(1)
#Configuration
public static class RestConfiguration extends WebSecurityConfigurerAdapter {
#Autowired
private MatoshreeUserDetailsService userDetailsService;
#Autowired
private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
// #Autowired
// private JwtRequestFilter jwtRequestFilter;
#Autowired
private JwtProvider jwtProvider;
#Bean
public BCryptPasswordEncoder passwordEncoder() {
BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder(12);
//System.out.println("in WebSecurityConfig passwordEncoder bCryptPasswordEncoder:"+bCryptPasswordEncoder);
return bCryptPasswordEncoder;
}
#Override
protected void configure(HttpSecurity http) throws Exception {
System.out.println("WebSecurityMultiConfig RestConfiguration configure");
http
.antMatcher("/matoshree/**")
.cors()
.and()
.csrf().disable()
// dont authenticate this particular request
.authorizeRequests().antMatchers("/matoshree/rest/loginUserWithJWT",
"/matoshree/rest/GetTransKey","matoshree/rest/registeruser","matoshree/rest/updateFCMToken",
"matoshree/rest/validateOtp","matoshree/rest/generateOtp","matoshree/rest/loginuser").permitAll().
// all other requests need to be authenticated
anyRequest().authenticated()
.and()
// .addFilter(new JwtTokenFilter(userDetailsService,jwtProvider))
// .addFilter(new JwtTokenFilter(userDetailsService,jwtProvider))
//.anyRequest().authenticated().and().
// make sure we use stateless session; session won't be used to
// store user's state.
.exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).and().sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
// .csrf()
// .disable() // we don't need CSRF because our token is invulnerable
// .authorizeRequests()
// .antMatchers(HttpMethod.POST, SIGN_UP_URL).permitAll()
// .antMatchers(RESET_PASSWORD_URL).permitAll()
// .anyRequest().authenticated()
// .and()
// .addFilter(new JWTAuthenticationFilter(authenticationManager()))
// .addFilter(new JWTAuthorizationFilter(authenticationManager()))
// // this disables session creation on Spring Security
// .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
// Add a filter to validate the tokens with every request
http.addFilterBefore(new JwtTokenFilter(userDetailsService,jwtProvider), UsernamePasswordAuthenticationFilter.class);
}
#Override
public void configure(AuthenticationManagerBuilder authBuilder) throws Exception {
// authBuilder.authenticationProvider(CustomAuthenticationProvider );
authBuilder.userDetailsService(userDetailsService);
}
#Bean
public AuthenticationManager authenticationManagerBean() throws Exception{
System.out.println("in c authenticationManagerBean ");
return super.authenticationManagerBean();
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
// configure AuthenticationManager so that it knows from where to load
// user for matching credentials
// Use BCryptPasswordEncoder
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
}
// #Order(2)
// #Configuration
// public static class AskRestConfiguration extends WebSecurityConfigurerAdapter {
// #Autowired
// AuthenticationEntryPoint authenticationEntryPoint;
//
// #Override
// protected void configure(HttpSecurity http) throws Exception {
//// http
//// .antMatcher(ASKFAST_API + "/**")
//// .csrf().disable()
//// .authorizeRequests()
//// .anyRequest().authenticated()
//// .and()
//// .httpBasic()
//// .authenticationEntryPoint(authenticationEntryPoint)
//// .and()
//// .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) //We don't need sessions to be created.
//// ;
// }
// }
#Order(2)
#Configuration
public static class WebConfiguration extends WebSecurityConfigurerAdapter {
#Autowired
private MatoshreeUserDetailsService userDetailsService;
#Autowired
private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
#Bean
public BCryptPasswordEncoder passwordEncoder() {
BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder(12);
//System.out.println("in WebSecurityConfig passwordEncoder bCryptPasswordEncoder:"+bCryptPasswordEncoder);
return bCryptPasswordEncoder;
}
// #Bean
// public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
// http
// //.authorizeHttpRequests()
// .authorizeRequests()
// .antMatchers("/", "/home","/login","/goToLogin").permitAll()
// .anyRequest().authenticated()
// .and()
// .formLogin()
// .loginPage("/goToLogin")
// .permitAll()
// .and()
// .logout()
// .permitAll();
//
// return http.build();
// }
#Override
protected void configure(HttpSecurity http) throws Exception {
System.out.println("WebSecurityMultiConfig WebConfiguration configure");
http.exceptionHandling().accessDeniedPage("/403");
// http
// //.authorizeHttpRequests()
// .authorizeRequests()
// //.antMatchers("/", "/home","/login","/goToLogin").permitAll()
// .anyRequest().authenticated();
// http
// .csrf().disable()
// .antMatcher("/**").authorizeRequests()
// .antMatchers("/resources/**").permitAll()
// //.antMatchers("/**").hasRole("ADMIN")
// .anyRequest().authenticated()
// .and().formLogin();
//
// http.sessionManagement().maximumSessions(1).expiredUrl("/goToLogin");
// .and()
// .formLogin()
// .loginPage("/goToLogin")
// .permitAll()
// .and()
// .logout()
// .permitAll();
// http
// .antMatcher("/**")
// // .csrf().disable()
// // .authorizeRequests()
// //.and()
//// .authorizeRequests()
//// .antMatchers("/**/favicon.ico", "/**/*.css", "/**/*.js","/**/*.jpg", "/**/*.png", "/**/*.xlsx", "/fonts/**", "/logout").permitAll()
//// .antMatchers("/v2/api-docs", "/configuration/ui", "/swagger-resources/**", "/configuration/security", "/swagger-ui.html", "/webjars/**").permitAll()
// //.antMatchers( "/goToLogin","/home","/login","/goToRegistration","/registeruser","/search").permitAll()
// //.anyRequest().authenticated()
// // .and()
// .formLogin()
// .loginPage("/goToLogin")
// .permitAll()
// .and()
// .logout()
// .permitAll();
//////
http
.antMatcher("/**")
// .csrf()
//.and()
.csrf().disable()
.authorizeRequests()
// .antMatchers("/**/favicon.ico", "/**/*.css", "/**/*.js", "/**/*.png", "/**/*.xlsx", "/fonts/**", "/logout").permitAll()
// .antMatchers("/v2/api-docs", "/configuration/ui", "/swagger-resources/**", "/configuration/security", "/swagger-ui.html", "/webjars/**").permitAll()
.antMatchers("/goToLogin","/home","/login","/goToRegistration","/registeruser","/403"/*,"/goToSearch"*/).permitAll()
.antMatchers("/search","/goToSearch").hasAnyAuthority("ROLE_ADMIN", "ROLE_SSR","ROLE_CSR","ADMIN", "SSR","CSR")
//.antMatchers(RESET_PASSWORD_PAGE_URL, PRIVACY_POLICY).permitAll()
//.anyRequest().hasAnyRole("ROLE_ADMIN", "ROLE_SSR","ROLE_CSR")
.anyRequest().authenticated()
.and()
.formLogin()
.permitAll()
.loginPage("/login")
.usernameParameter("emailId")
.passwordParameter("password")
.loginProcessingUrl("/doLogin")
// .defaultSuccessUrl("/login_success")
// .failureUrl("/login_error")
// .successForwardUrl("/login_success_handler")
// .failureForwardUrl("/login_failure_handler")
//.permitAll()
//.defaultSuccessUrl(EMPLOYEE_MVC, true)
.and()
.logout()
.logoutSuccessUrl("/login?logout");
http
.sessionManagement()
.maximumSessions(1).sessionRegistry(sessionRegistry());
}
#Bean
public SessionRegistry sessionRegistry() {
return new SessionRegistryImpl();
}
#Override
public void configure(WebSecurity web) throws Exception {
web
.ignoring()
.antMatchers(
HttpMethod.GET,
"/",
"/*.html",
"/**/favicon.ico",
"/**/*.html",
"/**/*.css",
"/**/*.js",
"/**/*.xlsx",
"/**/*.png",
"/**/*.jpg"
) ;
}
#Bean
public DaoAuthenticationProvider authenticationProvider() {
System.out.println("WebSecurityMultiConfig WebConfiguration authenticationProvider userDetailsService:"+userDetailsService);
DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
authProvider.setUserDetailsService(userDetailsService);
authProvider.setPasswordEncoder(passwordEncoder());
return authProvider;
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
System.out.println("WebSecurityMultiConfig WebConfiguration configure auth:"+auth);
auth.authenticationProvider(authenticationProvider());
}
// #Autowired
// public void configureInMemoryAuthentication(AuthenticationManagerBuilder auth) throws Exception
// {
// // auth.inMemoryAuthentication().withUser("ankush.shejal04#gmail.com").password(passwordEncoder().encode("Ankush#123")).roles("CSR");
// auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
// }
// #Override
// public void configure(AuthenticationManagerBuilder authBuilder) throws Exception {
// // authBuilder.authenticationProvider(CustomAuthenticationProvider );
// authBuilder.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
//// authBuilder.inMemoryAuthentication()
//// .withUser("ankush.shejal04#gmail.com")
//// .password(passwordEncoder().encode("Ankush#123"))
//// .authorities("ROLE_CSR");
// }
#Bean
public AuthenticationManager authenticationManagerBean() throws Exception{
System.out.println("in c authenticationManagerBean ");
return super.authenticationManagerBean();
}
//
// #Autowired
// public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
// // configure AuthenticationManager so that it knows from where to load
// // user for matching credentials
// // Use BCryptPasswordEncoder
// auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
//// auth.inMemoryAuthentication()
//// .withUser("ankush.shejal04#gmail.com")
//// .password(passwordEncoder().encode("Ankush#123"))
//// .authorities("ROLE_CSR");
// }
}
}

Related

How to disable multiple logins for same user in spring security + spring boot

I have the below spring configuration :-
#Override
protected void configure(HttpSecurity http) throws Exception
{
http
.csrf().disable()
.exceptionHandling()
.authenticationEntryPoint((request, response,
authException) ->
response.sendError(HttpServletResponse.SC_UNAUTHORIZED))
.and()
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS,
"/api/v2/customers/**").permitAll()
.antMatchers(HttpMethod.OPTIONS,
"/oauth/**").permitAll()
.antMatchers(HttpMethod.GET, "/saml/**").permitAll()
.antMatchers(HttpMethod.GET,
"/api/internal/v2/**").permitAll()
.antMatchers("/**").authenticated()
.antMatchers("/api/admin/**").authenticated()
.and()
.httpBasic()
.and()
.sessionManagement()
.maximumSessions(1)
.maxSessionsPreventsLogin(true)
.sessionRegistry(SR);
}
I was expecting sessionManagement().maximumSessions(1) to disable multiple login for the same user. It is working, but first user logout the application, so i am trying login in another browser but it showing This account is already using by someone.
Try this. you are not clearing/ closing the previous session properly.
#EnableWebMvcSecurity
#Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/expired").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.sessionManagement()
.maximumSessions(1)
.expiredUrl("/expired")
.maxSessionsPreventsLogin(true)
.sessionRegistry(sessionRegistry());
}
#Bean
public SessionRegistry sessionRegistry() {
SessionRegistry sessionRegistry = new SessionRegistryImpl();
return sessionRegistry;
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
// Register HttpSessionEventPublisher
#Bean
public static ServletListenerRegistrationBean httpSessionEventPublisher() {
return new ServletListenerRegistrationBean(new HttpSessionEventPublisher());
}
}
Missing is .expiredUrl("/expired").maxSessionsPreventsLogin(true)
.sessionRegistry(sessionRegistry());

Spring Security Concurrent Session Control

I am trying to restrict user session to one at a time from anywhere. But it doesn't work. When I try to access the application with the same user on two navigator, I have access.
I noticed that when a user connects to the application on two different machines to start printing two different reports, there is an print that comes out instead of the other.
Thanks for help.
My Security config class :
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
/*#Autowired
private DataSource dataSource;*/
private AccessDeniedHandler accessDeniedHandler;
private AuthenticationSuccessHandler authenticationSuccessHandler;
private AuthenticationFailureHandler authenticationFailureHandler;
private UserDetailsService userDetailsService;
#Autowired
public SecurityConfiguration(
#Qualifier("customAccessDeneiedHandler")AccessDeniedHandler accessDeniedHandler,
#Qualifier("customSuccessHandler")AuthenticationSuccessHandler authenticationSuccessHandler,
#Qualifier("customAuthenticationFailureHandler")AuthenticationFailureHandler authenticationFailureHandler,
#Qualifier("customUserDetailsService")UserDetailsService userDetailsService) {
this.accessDeniedHandler = accessDeniedHandler;
this.authenticationSuccessHandler = authenticationSuccessHandler;
this.authenticationFailureHandler = authenticationFailureHandler;
this.userDetailsService = userDetailsService;
}
/* (non-Javadoc)
* #see org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter#configure(org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder)
*/
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// TODO Auto-generated method stub
//super.configure(auth);
auth.userDetailsService(userDetailsService) //auth.userDetailsService(utilisateurDetailsService)
.passwordEncoder(passwordEncoder());
}
//Authorization
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
//.antMatchers("/").permitAll()
.antMatchers("/ajouterassure", "/ajouterattributaire", "/ajouterbeneficiaire", "/ajouterpiecejustificative",
"/creerbordereauemission", "/creerbehorscoordination", "/creerbordereaupaie", "/ajouteravance",
"/creerbeavanceannuelle")
.hasAnyRole("DGA", "DGAA", "DR", "DRA", "CC", "CCA", "CI", "AS", "GUICHET", "CE", "CAP", "ADMIN") //.hasRole("ADMIN")
.antMatchers("/ajoutercentre", "/ajouteretablissementpaie", "/ajoutertypepj", "/ajoutertypedette",
"/ajoutersexe", "/ajoutersituationbeneficiaire", "/ajoutercategoriebeneficiaire",
"/ajoutercategorieattributaire", "/ajouterrevalorisation").hasAnyRole("DGA", "ADMIN") //hasAnyRole("CAP", "ADMIN")
.antMatchers("/payerdecompte").hasAnyRole("CAISSIER", "ADMIN")
.antMatchers("/ajouterutilisateur").hasAnyRole("CI", "ADMIN")
.anyRequest().authenticated()
.and()
//.httpBasic()
.formLogin()
.loginPage("/login")
//.loginProcessingUrl("/login")
.usernameParameter("identifiant")
.passwordParameter("mot_de_passe")
.successHandler(authenticationSuccessHandler)
.failureHandler(authenticationFailureHandler)
//.defaultSuccessUrl("/")
.permitAll()
.and()
.logout().permitAll()
.and()
.sessionManagement() //Session controle concurence access
.maximumSessions(1)
.expiredUrl("/login?expired")
.sessionRegistry(sessionRegistry);
http.exceptionHandling().accessDeniedHandler(accessDeniedHandler);
//Session controle concurence access
//http.sessionManagement().maximumSessions(1);
}
/* (non-Javadoc)
* #see org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter#configure(org.springframework.security.config.annotation.web.builders.WebSecurity)
*/
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/resources/**", "/resources/templates/errors/**", "/static/**", "/css/**", "/images/**", "/var/signatures/**");
//web.ignoring().antMatchers("/static/**");
}
#Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
#Bean
public HttpSessionEventPublisher httpSessionEventPublisher() {
return new HttpSessionEventPublisher();
}
#Bean(name = "sessionRegistry")
public SessionRegistry sessionRegistry() {
return new SessionRegistryImpl();
}
#Autowired
#Lazy
private SessionRegistry sessionRegistry;
}
[Just in case someone finds it useful.]
Always add hashcode and equals methods in custom UserDetails class along with the below config in the spring security configuration class for the concurrent sessions to work.
protected void configure(HttpSecurity http) throws Exception
{
http.sessionManagement().maximumSessions(1);
}
#Bean
public HttpSessionEventPublisher httpSessionEventPublisher()
{
return new HttpSessionEventPublisher();
}
You need to just add .maxSessionsPreventsLogin(true) after maximumSessions(1) and it stop logging in from other places util session expires here. So your configure method should look like this :-
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
//.antMatchers("/").permitAll()
.antMatchers("/ajouterassure", "/ajouterattributaire", "/ajouterbeneficiaire", "/ajouterpiecejustificative",
"/creerbordereauemission", "/creerbehorscoordination", "/creerbordereaupaie", "/ajouteravance",
"/creerbeavanceannuelle")
.hasAnyRole("DGA", "DGAA", "DR", "DRA", "CC", "CCA", "CI", "AS", "GUICHET", "CE", "CAP", "ADMIN") //.hasRole("ADMIN")
.antMatchers("/ajoutercentre", "/ajouteretablissementpaie", "/ajoutertypepj", "/ajoutertypedette",
"/ajoutersexe", "/ajoutersituationbeneficiaire", "/ajoutercategoriebeneficiaire",
"/ajoutercategorieattributaire", "/ajouterrevalorisation").hasAnyRole("DGA", "ADMIN") //hasAnyRole("CAP", "ADMIN")
.antMatchers("/payerdecompte").hasAnyRole("CAISSIER", "ADMIN")
.antMatchers("/ajouterutilisateur").hasAnyRole("CI", "ADMIN")
.anyRequest().authenticated()
.and()
//.httpBasic()
.formLogin()
.loginPage("/login")
//.loginProcessingUrl("/login")
.usernameParameter("identifiant")
.passwordParameter("mot_de_passe")
.successHandler(authenticationSuccessHandler)
.failureHandler(authenticationFailureHandler)
//.defaultSuccessUrl("/")
.permitAll()
.and()
.logout().permitAll()
.and()
.sessionManagement() //Session controle concurence access
.maximumSessions(1)
.expiredUrl("/login?expired")
.sessionRegistry(sessionRegistry);
http.exceptionHandling().accessDeniedHandler(accessDeniedHandler);
//Session controle concurence access
//http.sessionManagement().maximumSessions(1);
}

User who is logged in simultaneously from different browser ... how to forcely logout the first user [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
User who is logged in simultaneously from different browser ... how to
forcely logout the first user
i added some code like security configuration details just check
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(
securedEnabled = true,
jsr250Enabled = true,
prePostEnabled = true
)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
CustomUserDetailsService customUserDetailsService;
#Autowired
private JwtAuthenticationEntryPoint unauthorizedHandler;
#Bean
public JwtAuthenticationFilter jwtAuthenticationFilter() {
return new JwtAuthenticationFilter();
}
#Override
public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
authenticationManagerBuilder
.userDetailsService(customUserDetailsService)
.passwordEncoder(passwordEncoder());
}
#Bean(BeanIds.AUTHENTICATION_MANAGER)
#Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
#Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors()
.and()
.csrf()
.disable()
.exceptionHandling()
.authenticationEntryPoint(unauthorizedHandler)
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/",
"/favicon.ico",
"/**/*.png",
"/**/*.gif",
"/**/*.svg",
"/**/*.jpg",
"/**/*.html",
"/**/*.css",
"/**/*.js")
.permitAll()
.antMatchers("/api/auth/**")
.permitAll()
.antMatchers("/api/user/checkUsernameAvailability", "/api/user/checkEmailAvailability")
.permitAll()
.antMatchers(HttpMethod.GET, "/api/polls/**", "/api/users/**")
.permitAll()
.anyRequest()
.authenticated();
// Add our custom JWT security filter
http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
}
}
i am thinking to tried with session but not working
Use can use maximumSessions(1) for this.
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.sessionManagement()
.maximumSessions(1)
.sessionRegistry(sessionRegistry())
.expiredUrl("/session-expired")
.and()
.sessionCreationPolicy(SessionCreationPolicy.ALWAYS)
.invalidSessionUrl("/")
.sessionFixation().none();
}

Spring Security, time before logout

I don't know why, maybe I write wrong code. My website does logout after a while.
I wrote in
application.properties
session.timeout.interval = 350000000 and
session.setMaxInactiveInterval = (60*60*24)
in form HTML I wrote
<form th:action="#{/login}" method="post"
authentication-success-handler-ref="authenticationSuccessHandler">
My code in Spring Security:
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Autowired
private UserDetailsService userDetailsService;
#Autowired
private UserRepository userRepository;
#Autowired
private DataSource dataSource;
#Override
protected void configure(final HttpSecurity httpSecurity) throws Exception {
httpSecurity
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/registration")
.permitAll()
.antMatchers(HttpMethod.POST, "/registration")
.permitAll()
.antMatchers("/css/**", "/js/**", "/img/**")
.permitAll()
.antMatchers("/cars/**")
.permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/")
.passwordParameter("password")
.permitAll()
.and().logout().logoutSuccessUrl("/")
.and()
.httpBasic()
.and()
.csrf().disable();
httpSecurity.rememberMe().rememberMeParameter("remember-me")
.rememberMeCookieName("my-remember-me")
.tokenRepository(persistentTokenRepository()).tokenValiditySeconds(86400000);
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
#Bean
public PasswordEncoder passwordEncoder() {
return new MyPasswordEncoder();
}
#Bean
public PersistentTokenRepository persistentTokenRepository() {
JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl();
tokenRepository.setDataSource(dataSource);
return tokenRepository;
}
I try use httpSecurity.addFilterBefore(authenticationFilter(), UsernamePasswordAuthenticationFilter.class) but I see logout again

Redirect in a filter with Spring Boot

In my configuration Spring Boot WebSecurityConfig have a filter that I need to see if the user has the expired password, if it is enabled on the application ..
#Configuration
#EnableWebMvcSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
IdentityService userDetailsService;
#Autowired
AccountFilter accountFilter;
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf()
.and()
.authorizeRequests()
.antMatchers("/login", "/recover-credntial",
"/logout", "/resources/**").permitAll()
.and()
.formLogin()
.loginPage("/login").failureUrl("/login?error")
.usernameParameter("username")
.passwordParameter("password")
.permitAll()
.and()
.logout()
.logoutSuccessUrl("/login?logout")
.permitAll()
.and()
.exceptionHandling()
.accessDeniedPage("/403")
.and().addFilterAfter(accountFilter, UsernamePasswordAuthenticationFilter.class);
}
#Override
protected void configure(AuthenticationManagerBuilder authManagerBuilder)
throws Exception {
authManagerBuilder.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
#Bean
#Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
#Bean
public PasswordEncoder passwordEncoder() {
PasswordEncoder encoder = new BCryptPasswordEncoder();
return encoder;
}
}
As you see I have .and().addFilterAfter(Account Filter, UsernamePasswordAuthenticationFilter.class); in the HTTP configuration.
How do I define my filter so that it can perform a redirect to the URL of some of my controller?
I'm using in Java Web Application 'Spring Boot' with Java Configuration, not file xml!
One approach would be as follows using ExceptionMappingAuthenticationFailureHandler. This will mean not using the servlet though.
Configuration
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.failureHandler(authenticationFailureHandler())
.and()
.logout()
.permitAll();
}
Authentication Failure Handler
#Bean
public AuthenticationFailureHandler authenticationFailureHandler() {
ExceptionMappingAuthenticationFailureHandler exceptionMappingAuthenticationFailureHandler = new ExceptionMappingAuthenticationFailureHandler();
Map<String, String> exMap = new HashMap<String, String>();
exMap.put("org.springframework.security.authentication.CredentialsExpiredException","/loginerror/credentialsexpired.htm");
exceptionMappingAuthenticationFailureHandler.setExceptionMappings(exMap);
return exceptionMappingAuthenticationFailureHandler;
}
Custom User Details Service
#Service
public class CustomUserDetailsService implements UserDetailsService {
#Autowired
private UserRepository userRepository;
#Override
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException {
// Check if Password Expired then throw
throw new CredentialsExpiredException("Expired");
}
}

Resources