How redirect user to login page after try to execute ajax request if spring security session is timeout? - ajax

I have spring boot app with spring security. I need check redirect to login page if user make request after session time out. I have 2 page: login and index. On index page I get requests by Ajax.
I open index page. wait 30 sec. Try update page after Session timeout but I not redirect to login page. But if I try update page F5 spring redirect me to login page. But if I try make ajax request - it work find and I not redirect.
It is my configs:
http.authorizeRequests().
antMatchers("/css/**").permitAll()
.antMatchers("/", "/index/**").hasRole("USER")
.anyRequest().hasRole("USER")
.and()
.formLogin()
.loginPage("/login").permitAll().defaultSuccessUrl("/index")
.and()
.logout().logoutUrl("/logout").permitAll().logoutSuccessUrl("/login");
http.csrf()
.disable()
.authorizeRequests()
.antMatchers("/resources/**", "/**").permitAll()
.anyRequest().permitAll()
.and();
and button on index page:
<button type="button" class="btn btn-primary" onclick="reload()">show</button>
and js method:
function reload() {
table.ajax.reload(null, false);
}
When I press "show" button - my table send request to spring controller(Session already invalid) and controller return data and table update success/ But I need redirect user to login page.

http
.authorizeRequests()
.antMatchers("/css/**", "/resources/**").permitAll()
// ??? .antMatchers("/", "/index/**").hasRole("USER")
.anyRequest().hasRole("USER")
.and()
.formLogin()
.loginPage("/login").permitAll()
.defaultSuccessUrl("/index")
.and()
.logout()
.logoutUrl("/logout").permitAll().logoutSuccessUrl("/login")
.and()
.csrf()
.disable();
Can you try this ? and .antMatchers("/", "/index/**").hasRole("USER") is very confused.

Related

Excluding a specific page from Spring Security that is redirected from login page

I am having trouble while I am redirecting an authentication link from my login page. I added the link in to my login page in JSF like this:
<div>
Login via Testinium Cloud
</div>
My spring security configuration is like this:
and()
.authorizeRequests()
.antMatchers(DEFAULT_URL).permitAll()
.antMatchers("/javax.faces.resource/**").permitAll()
.antMatchers("/jsfPages/*").permitAll()
.antMatchers("/errorPages/*").permitAll()
.anyRequest().authenticated()
.and()
.exceptionHandling()
.accessDeniedHandler(jsfAccessDeniedHandler())
.authenticationEntryPoint(jsfAuthenticationEntryPoint())
.and()
.formLogin()
.loginPage(LOGIN_PAGE).permitAll()
.failureUrl(LOGIN_PAGE).permitAll()
.defaultSuccessUrl(DEFAULT_URL)
.successHandler(authSuccessHandler)
.and()
.logout()
.logoutUrl(LOGOUT_URL).permitAll()
.invalidateHttpSession(true)
.logoutSuccessHandler(logoutSuccessHandler)
.and()
.exceptionHandling().accessDeniedPage("/error/403.xhtml");
How could I redirect my link from login page without gettin an authentication error. I tried
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/api/v1/signup");
}
But it didn't work out for me. Thanks!
If you want to exclude a page from your spring security configuration without overriding web security, you can add 'not' method that is connected to 'antMatchers' method in your code with authenticated() method following like this:
.authorizeRequests()
.antMatchers(DEFAULT_URL).permitAll()
.antMatchers("/javax.faces.resource/**").permitAll()
.antMatchers("/jsfPages/*").permitAll()
.antMatchers("/errorPages/*").permitAll()
.antMatchers(LOGIN_TESTINIUM).not().authenticated()
.anyRequest().authenticated()
.and()

Spring WebSecurity how to use 2 loginForm

I created two login forms in Spring Web Security. (User, Admin) However, if login fails on the user login page, it returns to the user login page, but if the login fails on the admin login page, it will return to the user login page instead of the admin login page. Is there anything I am doing wrong?
httpSecurity
.csrf()
.disable()
.authorizeRequests()
.requestMatchers(PathRequest.toStaticResources().atCommonLocations())
.permitAll()
.antMatchers("/registerUser", "/saveUser", "/admin")
.permitAll()
.anyRequest()
.authenticated()
.and()
.formLogin()
.loginPage("/admin")
.loginProcessingUrl("/login-process")
.defaultSuccessUrl("/center", true)
.failureUrl("/Admin/admin?error=ture")
.failureHandler(failureHandler())
.permitAll();
httpSecurity.formLogin()
.loginPage("/login")
.loginProcessingUrl("/login-process")
.defaultSuccessUrl("/center", true)
//.failureUrl("/login")
.failureUrl("/login.html?error=true")
.permitAll()
.and()
.rememberMe()
.rememberMeParameter("remember-me")
.key(REMEMBER_ME_TOKEN)
.tokenValiditySeconds(Math.toIntExact(Duration.ofDays(30).getSeconds()))
.userDetailsService(userService);

Spring boot security: Requested url creates unwanted redis session

Lets say the login url is "/login".
There are two protected resources:
"/protected"
"/" which is a 302 redirect to "/protected"
When a unauthenticated user tries to access "/protected" he is being redirected to "/login". In background there is a session created, where SPRING_SECURITY_SAVED_REQUEST is stored in order to redirect user to the "/protected" url after successful login.
This is the default behaviour of spring security.
My issue:
Sessions are being created even when users call "/". So all the bots and penetration tests, which call the domain without valid login information do create sessions in the underlying redis layer.
How can I prevent these sessions from being created when there is no redirect request stored or at least limit them to a defined list of valid backend endpoints?
My security configuration:
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/password/forgot/**").permitAll()
.antMatchers("/password/reset/**").permitAll()
.antMatchers("/css/**").permitAll()
.antMatchers("/js/**").permitAll()
.antMatchers("/img/**").permitAll()
.antMatchers( "/favicon.ico").permitAll()
.antMatchers("/login").permitAll()
.anyRequest().fullyAuthenticated();
http
.formLogin()
.loginPage("/login")
.permitAll()
.successHandler(authSuccessHandler)
.and()
.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/login")
.deleteCookies("SESSION")
.clearAuthentication(true)
.invalidateHttpSession(true)
.permitAll();
http.sessionManagement()
.maximumSessions(1)
.and()
.sessionCreationPolicy(SessionCreationPolicy.NEVER);
http.headers().frameOptions().disable();
http.csrf().disable();
}
You could avoid having SPRING_SECURITY_SAVED_REQUEST created by setting NullRequestCache, but I guess that wouldn't work for your use case.
or at least limit them to a defined list of valid backend endpoints?
This could be done by providing a requestCache and setting the RequestMatcher -
final HttpSessionRequestCache requestCache = new HttpSessionRequestCache();
requestCache.setRequestMatcher(new AntPathRequestMatcher("/**"));
http
.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.anyRequest().authenticated()
.and()
.requestCache().requestCache(requestCache)
.and()...

Spring Security - Authentication issue

I am working on a web application & have opted to use spring Security. The idea is for the user to be authenticated to see the Home Page, if the user is not authenticated they are redirected to the login page. This login page also displays a link to a registration form, This part is working correctly.
However, I have encountered an issue when attempting to allow users to sign up via the registration link. The link to the registration form cannot be accessed if the user if not authenticated ("showRegistrationForm")
Can anyone provide insight to why this is occuring? I have Included the code snippet from my SecurityConfig below
#Override
protected void configure(HttpSecurity http) throws Exception {
//Restrict Access based on the Intercepted Servlet Request
http.authorizeRequests()
.antMatchers("/resources/**", "/register").permitAll()
.anyRequest().authenticated()
.antMatchers("/").hasRole("EMPLOYEE")
.antMatchers("/showForm/**").hasAnyRole("EMPLOYEE","MANAGER", "ADMIN")
.antMatchers("/save/**").hasAnyRole("MANAGER", "ADMIN")
.antMatchers("/delete/**").hasRole("ADMIN")
.and()
.formLogin()
// Show the custom form created for the below request mappings
.loginPage("/showSonyaLoginPage")
.loginProcessingUrl("/authenticateTheUser")
// No need to be logged in to see the login page
.permitAll()
.and()
// No need to be logged in to see the logout button.
.logout().permitAll()
.and()
.exceptionHandling().accessDeniedPage("/access-denied");
}
Change the code like below:
#Override
protected void configure(HttpSecurity http) throws Exception {
// Restrict Access based on the Intercepted Servlet Request
http.authorizeRequests()
.antMatchers("/showRegistrationForm/").permitAll()
.anyRequest().authenticated()
.antMatchers("/").hasRole("EMPLOYEE")
.antMatchers("/resources/").permitAll()
.antMatchers("/showForm/**").hasAnyRole("EMPLOYEE","MANAGER", "ADMIN")
.antMatchers("/save/**").hasAnyRole("MANAGER", "ADMIN")
.antMatchers("/delete/**").hasRole("ADMIN")
.and()
.formLogin()
// Show the custom form created for the below request mappings
.loginPage("/showSonyaLoginPage")
.loginProcessingUrl("/authenticateTheUser")
// No need to be logged in to see the login page
.permitAll()
.and()
// No need to be logged in to see the logout button.
.logout().permitAll()
.and()
.exceptionHandling().accessDeniedPage("/access-denied");
}
Moved down the below code:
anyRequest().authenticated()

Spring Boot, Spring Security specify redirect login url

At my Spring Boot application I need to implement a following scenario:
Anonymous User visits the following page: http://example.com/product-a.html
This User wants to ask a question about this product. It can be done at another page, located by the following address: http://example.com/product-a/ask. User press Ask Question button at the http://example.com/product-a.html and login/registration popup is shown. After successful login User should be automatically redirected to http://example.com/product-a/ask (but currently with a default Spring Security implementation User are redirecting back to the page originator http://example.com/product-a.html)
How to properly with Spring Boot/Spring Security implement/configure this redirect ?
UPDATED
This is my web security config:
#Override
protected void configure(HttpSecurity http) throws Exception {
// #formatter:off
http.addFilterBefore(new CorsFilter(), ChannelProcessingFilter.class);
http
.csrf().ignoringAntMatchers("/v1.0/**", "/logout")
.and()
.authorizeRequests()
.antMatchers("/oauth/authorize").authenticated()
//Anyone can access the urls
.antMatchers("/images/**").permitAll()
.antMatchers("/signin/**").permitAll()
.antMatchers("/v1.0/**").permitAll()
.antMatchers("/auth/**").permitAll()
.antMatchers("/actuator/health").permitAll()
.antMatchers("/actuator/**").hasAuthority(Permission.READ_ACTUATOR_DATA)
.antMatchers("/login").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.loginProcessingUrl("/login")
.failureUrl("/login?error=true")
.usernameParameter("username")
.passwordParameter("password")
.permitAll()
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessUrl(logoutSuccessUrl)
.permitAll();
// #formatter:on
}
I use OAuth2/JWT + Implicit Flow for AngularJS client
I think you should not use spring's default /login processing url, but create your own e.g /mylogin in a controller. And then you can inject the HttpServletRequest in the method and take the action based on the context of the request for example:
#PostMapping("/mylogin")
public ResponseEntity<> processingLogingURL(HttpServletRequest request){
// switch bases on the request URL after checking security off course
switch(request.getRequestURL()){
//redirect based on the caller URL
}
}
and finally change your .loginProcessingUrl("/login") to .loginProcessingUrl("/mylogin")

Resources