Spring MVC Security Not Securing Views - java

The following example isn't correctly securing my views. The view are rendering and displaying they just aren't secured correctly.
The views live in WEB-INF/jsp and contain an Angular app with Angular Router.
I don't think that the Angular app nor the Router is the root cause so I haven't included them below. If they are, I will gladly supply the code.
I'm also using CustomUserDetailsService with H2, Data JPA, Hibernate, etc. I haven't included that since the main issue right now pertains to securing the routes as opposed to the actual authentication and persistence flow itself. Again, perhaps those items are incorrectly configured.
Any help is much appreciated! Thanks!
AppConfig:
#Configuration
#EnableWebMvc
#ComponentScan()
public class AppConfig extends WebMvcConfigurerAdapter {
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
registry.addViewController("/login").setViewName("login");
registry.addViewController("/secured/socket").setViewName("socket");
registry.addViewController("/secured/success").setViewName("success");
registry.addViewController("/denied").setViewName("denied");
}
#Bean
public UrlBasedViewResolver viewResolver() {
UrlBasedViewResolver resolver = new UrlBasedViewResolver();
resolver.setPrefix("/WEB-INF/jsp/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
return resolver;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**")
.addResourceLocations("/", "/resources/")
.setCachePeriod(3600)
.resourceChain(true)
.addResolver(new PathResourceResolver());
}
}
SecurityConfig:
#Configuration
#EnableGlobalAuthentication
#ComponentScan
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/index").permitAll()
.antMatchers("/denied").permitAll()
.antMatchers("/authenticate").permitAll()
.antMatchers("/secured/socket").authenticated()
.antMatchers("/secured/success").authenticated()
.antMatchers("/secured/pet").authenticated()
.antMatchers("/secured/**/**").authenticated()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login").permitAll()
.usernameParameter("username").passwordParameter("password")
.loginProcessingUrl("/authenticate")
.defaultSuccessUrl("/secured/success",true)
//.failureUrl("/login.html?error=true")
.and()
.logout()
.logoutSuccessUrl("/index").permitAll()
.and()
.exceptionHandling()
.accessDeniedPage("/denied")
.and()
.csrf();
}
}
Edit: to help clarify the problem - the route /secured/success or success.jsp does not require authentication to be accessed or viewed. Neither do any of the other views specified above. They should.

Looks like you forgot #EnableWebSecurity annotation at SecurityConfig.

OK,I think I solved this - the configuration files above are fine but I forgot to add the springSecurityFilterChain via:
public class SpringSecurityInitializer extends AbstractSecurityWebApplicationInitializer {
//do nothing
}
as well as:
#Configuration
#EnableGlobalMethodSecurity(prePostEnabled = true)
#EnableWebSecurity
#ComponentScan(//...)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
//...
}
Apparently, though I might be mistaken in this, #EnableWebSecurity must be explicitly stated in order to trigger the use of springSecurityFilterChain.

Related

How ant matcher works in spring security

I want to know how ant matcher works in spring security??
I have two rest point:
First Rest class
#RestController
#RequestMapping("/auth")
class RestService1{
#GetMapping("/status")
public String status() {
return "Yes, I am fine";
}
}
Second Rest class
#RestController
#RequestMapping("/test")
class RestService2{
#GetMapping("/status")
public String status() {
return "Yes, Test status";
}
}
Spring security config class:
#EnableWebSecurity
#Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter{
protected void configure(HttpSecurity http)throws Exception{
http.authorizeRequests().antMatchers("/auth/*").permitAll();
}
}
Here is my question:
As per my understanding the meaning of "antMatchers("/auth/*").permitAll()" line is permit all request urls who contains "auth". But with this code I can able to access localhost:8080/test/status URL as well.
So what i can do if i want to allow only "auth" contains URL and deny all URLs ?
This code will permit only request URLs starting with "auth" and will deny all other URLs.
#EnableWebSecurity
#Configuration
class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/auth/**")
.permitAll()
.anyRequest()
.denyAll();
}
}
anyRequest().authenticate() will make all other routes forbidden, one has to be authenticated before accessing those routes.
#Configuration
class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/auth/**")
.permitAll()
.anyRequest()
.authenticate();
}
}

Spring security x-frame-option

I have a spring boot web server which uses the httpWebSecurityAdapter.
I am trying to display some web pages (HTML CSS, javascript) in a div in my Angular app.
X-frame does not allow me to do it if enabled.
I would like to disable the x-frame options only for a certain type of request.
Right now I have it disabled for everything. I would like to do only for a certain URL.
http.headers().frameOptions().disable()
You will need to provide multiple WebSecurityConfigurerAdapter configurations. In other words, multiple security configurations for each of your url patterns.
Here's a sample configuration:
#Configuration
#EnableWebSecurity
public class SecurityConfig {
// #Order is to specify which WebSecurityConfigurerAdapter should be considered first. This configuration has the highest priority.
// This configuration is activated for url pattern: /home/**
#Order(1)
#Configuration
public static class DefaultSecurityConfiguration extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.antMatcher("/home/**")
.authorizeRequests()
.anyRequest().authenticated()
.and().formLogin()
.and().httpBasic();
}
}
// This configuration is considered after DefaultSecurityConfiguration since it has #Order(2).
// This configuration is activated for url pattern: /registerUser/**
#Order(2)
#Configuration
public static class DisabledFrameOptionsSecurityConfigurer extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.antMatcher("/registerUser/**")
.authorizeRequests()
.anyRequest().permitAll();
http.headers().frameOptions().sameOrigin();
}
}
}

Spring Security not working on Weblogic 12.2.1.2

I have a web application that uses Spring Security. It works on Tomcat, but didn't on Weblogic 12.2.1.2.
On Weblogic, user isn't redirected to the login page when tries to reach a restricted URL (for example localhost:7001/website/restricted/welcome). On Tomcat the user is correclty redirected to the login page.
I read that this is a bug of Weblogic 12.1 and it seems to be fixed in Weblogic 12.2. But I'm using Weblogic 12.2.1.2 and I enconter the same problem.
I read some solutions, but I have difficult to understand them, since I have a different Spring configuration.
These are my classes about Spring Security.
This is the class that extends WebSecurityConfigurerAdapter.
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth)
throws Exception {
auth.inMemoryAuthentication()
.passwordEncoder(passwordEncoder())
.withUser("username1")
.password(passwordEncoder()
.encode("password1"))
.roles("ADMIN");
}
#Bean
public PasswordEncoder passwordEncoder() {
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
return passwordEncoder;
}
#Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.formLogin()
.loginPage("/login")
.usernameParameter("userId")
.passwordParameter("password");
httpSecurity.formLogin()
.defaultSuccessUrl("/")
.failureHandler(new CustomAuthenticationFailureHandler())
.and()
.sessionManagement()
.maximumSessions(1)
.expiredUrl("/login?expired")
.maxSessionsPreventsLogin(true);
httpSecurity.logout()
.logoutSuccessUrl("/login?logout");
httpSecurity.rememberMe()
.rememberMeParameter("rememberMe")
.key("rememberMeKey")
.tokenValiditySeconds(1800);
httpSecurity.exceptionHandling()
.accessDeniedPage("/login?accessDenied");
httpSecurity.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/**/add").access("hasRole('ADMIN')")
.antMatchers("/**/market/**").access("hasRole('USER')");
httpSecurity.csrf()
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
}
}
This is the class that extends AbstractSecurityWebApplicationInitializer.
public class SecurityWebApplicationInitializer
extends AbstractSecurityWebApplicationInitializer
implements WebApplicationInitializer {
#Override
protected boolean enableHttpSessionEventPublisher() {
return true;
}
}
The problem seems to be bound to Spring Boot.
When, with Spring Tool Suite, I use the Spring Starter Project wizard (Spring boot) I encounter the problem.
If I don't use Spring Boot, Spring Security work properly!
How should I fix this problem?
Thank you

java Spring #EnableResourceServer and #EnableWebSecurity

I have RESTful spring resource server with #EnableResourceServer and extending ResourceServerConfigurerAdapter
In documentations says:
...In order to use this filter you must #EnableWebSecurity somewhere in your application, either in the same place as you use this annotation, or somewhere else.
But when I get to the public #interface EnableResourceServer I see ResourceServerConfiguration extends WebSecurityConfigurerAdapter.
Question:
So what do I need for pure RESTful API?
#EnableWebSecurity on any #Config
Extend the WebSecurityConfigurerAdapter?
1 + 2
Neither
My config
#Configuration
#EnableResourceServer
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class HGResourceServerConfigurerAdapter extends ResourceServerConfigurerAdapter {
#Override
public void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.cors().disable()
.csrf().disable()
.formLogin().disable()
.httpBasic().disable()
.jee().disable()
.logout().disable()
.rememberMe().disable()
.servletApi().disable()
.x509().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and().authorizeRequests().antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
.and().authorizeRequests().antMatchers(Url.API_ERROR_LOGS_FRONTEND).permitAll()
.and().authorizeRequests().antMatchers(Url.API_REGISTER_PATH).permitAll()
.and().authorizeRequests().antMatchers(Url.API_VERIFY_EMAIL_PATH).permitAll()
.and().authorizeRequests().antMatchers(Url.API_RESET_PASSWORD_PATH).permitAll()
.and().authorizeRequests().antMatchers(Url.API_CONFIRM_RESET_PASSWORD_PATH).permitAll()
.and().authorizeRequests().anyRequest().authenticated();
}
#Primary
#Bean
public RemoteTokenServices tokenService() {
RemoteTokenServices tokenService = new RemoteTokenServices();
tokenService.setCheckTokenEndpointUrl("http://localhost:8081/oauth/check_token");
tokenService.setClientId("client");
tokenService.setClientSecret("secret");
return tokenService;
}
//disable default user creation
#Bean
public UserDetailsService userDetailsService() throws Exception {
return new InMemoryUserDetailsManager();
}
//password encoder
#Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
No, the enable EnableWebSecurity is implicit.
I do not recommend to use WebSecurityConfigurerAdapter, you will come across some troubles :
Correctly configure spring security oauth2
Spring Boot makes #EnableWebSecurtiy implicit, but otherwise is it required.
You can prove this to yourself by taking a look at this OAuth2 resource server example. If you remove the #EnableWebSecurity annotation there, you will find that the Spring Security Filter Chain is not wired.
You can still extend WebSecurityConfigurerAdapter to separate general web application security concerns from those specific to resource server configuration. This isn't technically necessary, but can make for a cleaner separation of concerns.

How to provide custom security configuration for oauth2 with spring-boot 1.3.0.RC1

With spring-cloud Angel.SR3 release I followed example in https://github.com/spring-cloud-samples/sso and things work fine with spring-boot 1.2.6.RELEASE.
However with spring-boot 1.3.0.RC1, the oauth2 stuff has moved into spring-boot itself, and the code below fails to compile because class OAuth2SsoConfigurerAdapter no longer exists.
What is the spring-boot only way to create equivalent configuration?
public static void main(String[] args) {
SpringApplication.run(MainAppApplication.class, args);
}
...
#Component
public static class LoginConfigurer extends OAuth2SsoConfigurerAdapter {
#Override
public void match(RequestMatchers matchers) {
matchers.antMatchers("/dashboard/**");
}
#Override
public void configure(HttpSecurity http) throws Exception {
http.antMatcher("/dashboard/**").authorizeRequests().anyRequest()
.authenticated().and().csrf()
.csrfTokenRepository(csrfTokenRepository()).and()
.addFilterAfter(csrfHeaderFilter(), CsrfFilter.class);
}
private Filter csrfHeaderFilter() {
return new OncePerRequestFilter() {
...
};
}
...
}
You just have to use org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter and carefully use this annotation org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso
I've written carefully because its behaviour depends on where you add it. As stated in the javadoc:
Enable OAuth2 Single Sign On (SSO). If there is an existing WebSecurityConfigurerAdapter provided by the user and annotated with #EnableOAuth2Sso, it is enhanced by adding an authentication filter and an authentication entry point. If the user only has #EnableOAuth2Sso but not on a WebSecurityConfigurerAdapter then one is added with all paths secured and with an order that puts it ahead of the default HTTP Basic security chain in Spring Boot.
Hope that helps!
Turns out not special adapter needed, just the regular WebSecurityConfigurerAdapter does the trick. You cannot tell the code from below if oauth2 SSO is involved, more transparent, sort to speak.
#Configuration
#Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
protected static class ApplicationSecurity extends WebSecurityConfigurerAdapter {
#Autowired
private SecurityProperties security;
#Override
protected void configure(HttpSecurity http) throws Exception {
// #formatter:off
http
.authorizeRequests()
.antMatchers("/", "/ssologout").permitAll()
.anyRequest().fullyAuthenticated()
.and()
.formLogin()
.loginPage("/login").failureUrl("/login?error")
.permitAll()
.and()
.logout().permitAll();
// #formatter:on
}
}

Categories

Resources