Spring Boot Security not ignoring directory using WebSecurity - spring

I am trying to ignore directory using websecurity.ignore. I have the following configuration.
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.antMatchers("/product_save").hasAuthority("ADMIN")
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll().and().csrf().disable()
.exceptionHandling().and()
.rememberMe()
.key("uniqueAndSecret")
.rememberMeCookieName("broman-remember-me")
.tokenValiditySeconds(60 * 60 * 24).and()
.sessionManagement().maximumSessions(1);
}
#Override
public void configure(WebSecurity web)throws Exception {
web.ignoring().antMatchers("/static/**");
}
}
The above configuration doesn't ignore.

Your code:
#Override
public void configure(WebSecurity web)throws Exception {
web.ignoring().antMatchers("/static/**");
}
will ignore all URLs that start with /static/** like http://localhost:8080/static/...
Spring Boot serves the content of the static folder by default. So if you have some folders or files in the static folder (like static resources related to customers and managers, etc..) you can ignore them one by one:
#Override
public void configure(WebSecurity web)throws Exception {
web.ignoring().antMatchers("/customers/**", "/managers/**", "/monitor.html");
}
This will ignore:
http://localhost:8080/customers/ - and all sub-URLs
http://localhost:8080/managers/ - and all sub-URLs
http://localhost:8080/monitor.html

Related

How to tune spring boot security configuration?

I enabled spring boot security, and added some urls to exclusion list (porperty security.ignored)
in application.yaml.
Now I want to add some new urls to exclusion list programmatically, in my configuration class.
How could i achieve this ?
PS I cannot edit yaml, I'm able to edit only configuration class.
If you are looking to exclude some url patterns in java instead of yaml or properties.
Example:
If you need to exclude,
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/login**").permitAll()
.antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
.antMatchers("/**").access("hasRole('ROLE_USER')")
.and()
.formLogin().loginPage("/login").failureUrl("/login?error")
.usernameParameter("username").passwordParameter("password")
.and()
.logout().logoutSuccessUrl("/login?logout")
.and()
.exceptionHandling().accessDeniedPage("/403")
.and()
.csrf();
}
If you need to ignore,
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/authFailure");
}
Hope this is useful.

Spring Security mapping uppercase in URL

I work on a JEE project, using the Spring Boot framework.
For the authentification, I use Spring Security, and I specified the pages in my template.
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/login").permitAll()
.antMatchers("/token", "/index", "/index.html", "/main", "/main.html", "/main2", "/main2.html", "/recent1", "/recent1.html", "/recent2", "/recent2.html").hasRole("USER");
http
.csrf()
.disable()
.formLogin()
.loginPage("/login")
.failureUrl("/login?error=true")
.defaultSuccessUrl("/index");
http
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/login");
}
The issue is that when I run the application and I wrote the URL with uppercase letters like: localhost:8080/INDEX.HTML or I add two letters localhost/index.httml, the page does appear without authantification.
If I understand correctly, here is the desired logic:
/login does not need to be secured by Spring Security (no roles are required)
All the other pages have to be secured with "USER" role.
To implement this, you could try the following:
#Override
public void configure(WebSecurity web) throws Exception {
// configuring here URLs for which security filters
// will be disabled (this is equivalent to using
// security="none")
web
.ignoring()
.antMatchers(
"/login"
)
;
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().hasRole("USER");
http.csrf().disable().formLogin()
.loginPage("/login").failureUrl("/login?error=true")
.defaultSuccessUrl("/index");
http.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/login");
}
So item 1 (no security on /login) is moved to configure(WebSecurity), and item 2 is left in the original configure(HttpSecurity).

questions for spring security config

I`ve tried to config Spring Security.
This is my sucurity config.
#Override
protected void configure(HttpSecurity http) throws Exception {
// #formatter:off
http.authorizeRequests()
.antMatchers("/api/**", "/denied**").permitAll()
.anyRequest().denyAll()
.and()
.exceptionHandling().accessDeniedPage("/denied")
.and()
.csrf().disable();
// #formatter:on
}
When I access url "localhost:8080/admin", I expect "/denied" page.
But it shows default 403 page provided spring security.
Is there any problem my configuration?
Update:
Change .anyRequest().denyAll() to .anyRequest().authenticated()
#Override
protected void configure(HttpSecurity http) throws Exception {
// #formatter:off
http.authorizeRequests()
.antMatchers("/api/**", "/denied**").permitAll()
.anyRequest().authenticated()
.and()
.exceptionHandling().accessDeniedPage("/denied")
.and()
.csrf().disable();
// #formatter:on
}
If u need to use requiresSecure(), just add .requiresChannel().anyRequest().requiresSecure().and() after .and()

Concurrent session management always redirecting to failureurl - Java Config

I am using Spring MVC with Spring Security ver4.0.1.RELEASE.
I was trying to control the concurrent user login to 1 and show an error message if user already logged In.
The Concurrent Session Management is working as expected but the expireUrl("") is not working. The .formLogin().loginPage("").failureUrl("") is always called instead of expireUrl(""). Please help.
Below is my SpringSecurityConfiguration.java which extends WebSecurityConfigurerAdapter
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/resources/**").permitAll()
.antMatchers("/", "/home").permitAll()
.antMatchers("/Access_Denied").permitAll()
.antMatchers("/login").permitAll()
.and().formLogin().loginPage("/login")
.failureUrl("/login?out=1")
.usernameParameter("userID").passwordParameter("password")
.and().csrf().and()
.logout()
.deleteCookies( "JSESSIONID" )
.logoutSuccessUrl( "/logout" )
.invalidateHttpSession( true )
.and().exceptionHandling().accessDeniedPage("/accessDenied.jsp")
.and()
.sessionManagement()
.maximumSessions(1)
expiredUrl("/login?time=1")
.sessionRegistry(sessionRegistry);
}
My Initializer class will looks like below -
protected Filter[] getServletFilters() {
return new Filter[] { new HiddenHttpMethodFilter() };
}
public void onStartup(ServletContext servletContext) throws ServletException {
super.onStartup(servletContext);
servletContext.addListener(new SessionListener());
servletContext.addListener(new CustomHttpSessionEventPublisher());
}
The below links provide extra info for this type of security configuration -
http://codehustler.org/blog/spring-security-tutorial-form-login-java-config/
https://gerrydevstory.com/2015/08/02/managing-spring-security-user-session/
Have you tried to move session management up on the chain?
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/resources/**").permitAll()
.antMatchers("/", "/home").permitAll()
.antMatchers("/Access_Denied").permitAll()
.antMatchers("/login").permitAll()
.and().sessionManagement()
.maximumSessions(1)
.expiredUrl("/login?time=1")
.sessionRegistry(sessionRegistry);
.and().formLogin().loginPage("/login")
.failureUrl("/login?out=1")
.usernameParameter("userID").passwordParameter("password")
.and().csrf().and()
.logout()
.deleteCookies( "JSESSIONID" )
.logoutSuccessUrl( "/logout" )
.invalidateHttpSession( true )
.and().exceptionHandling().accessDeniedPage("/accessDenied.jsp")
}

access static content in secured Spring Boot application

I have a standalone Spring Boot application with templates in /src/main/resources/templates and static content in /src/main/resources/static. I would like the static content to be accessible before authentication, so the CSS loads on the login page as well. Now it only loads after authentication. My security configuration looks like this:
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private static final Logger logger = Logger.getLogger(SecurityConfig.class);
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) {
try {
auth.inMemoryAuthentication()
...
} catch (Exception e) {
logger.error(e);
}
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.formLogin()
.defaultSuccessUrl("/projects", true)
.loginPage("/login")
.permitAll()
.and()
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout", "GET"))
.permitAll()
.and()
.authorizeRequests()
.antMatchers("/static/**").permitAll()
.anyRequest().authenticated();
}
}
The static content in classpath:/static is served at the root of the application (i.e. /*), whether or not the application is secure, so you need to match on specific paths underneath the root. Spring Boot permits all access by default to /js/**, /css/**, /images/** (see SpringBootWebSecurityConfiguration for details), but you may have switched that off (can't see the rest of your code).

Resources