spring security and VAADIN - spring

I am developing my spring boot app which is protected by spring security. Here is part of secured config:
#Override
public void configure(HttpSecurity http) throws Exception {
// #formatter:off
http
// .csrf().ignoringAntMatchers("/dashboard")
// .and()
.httpBasic()
.and()
.headers().frameOptions().disable()
.and()
.antMatcher("/**").authorizeRequests()
.antMatchers("/VAADIN/**", "/PUSH/**", "/UIDL/**").permitAll()
.antMatchers("/vaadinServlet/UIDL/**").permitAll()
.antMatchers("/vaadinServlet/HEARTBEAT/**").permitAll()
.antMatchers("/actuator/health").permitAll()
.antMatchers("/actuator/**").hasAuthority(Authority.Type.ROLE_ADMIN.getName())
.antMatchers("/", "/login**", "/index.html", "/home.html").permitAll()
.and()
.logout().logoutSuccessUrl("/").permitAll()
.and()
.csrf().csrfTokenRepository(csrfTokenRepository())
.and()
.addFilterAfter(csrfHeaderFilter(), CsrfFilter.class)
.addFilterBefore(ssoFilter(), BasicAuthenticationFilter.class);
// #formatter:on
}
I am going to implement some admin dashboard to manage my app using VAADIN.
I have read that "Disable CSRF-protection in either Spring or Vaadin. If you have both turned on, your application will not work.".
In my case I need to disable CSRF-protection in Vaadin, but I could not find how can I do it using Java config.
For this moment I am getting: https://127.0.0.1:8443/vaadinServlet/UIDL/?v-wsver=7.5.5&v-uiId=0 "Communication error: UIDL could not be read from server. Check servlets mappings. Error code: 403", during navigation from the main view to other views. (e.g: /dashboard#!myview). This because AccessDeniedHandlerImpl handle method is invoked. I have try to fix this using following statements but it doesn't help:
.antMatchers("/vaadinServlet/UIDL/**").permitAll()
.antMatchers("/vaadinServlet/HEARTBEAT/**").permitAll()
So, please help me to solve this two issues:
Disable CSRF in VAADIN using java config.
Solve problem with view navigation.
Thanks

To fix the above issues, I have decided to divide my project into two modules. First is API app, which has own implemented security configuration. Second is Dashboard, which has both Spring Security integrated with Vaadin4Spring based on this sample.

Related

How does one use different session creation policies for UI and REST endpoints with Spring Security?

I have an application that contains both a UI and some REST endpoints. The UI uses SAML login (the old Spring Security SAML extension) and the REST endpoints using a custom authentication. The REST endpoints are only called by external applications.
For the REST endpoints ("/api/**") I have stated a stateless session creation policy and for the rest of the endpoint no session creation policy at all (I also tried with ALWAYS as in the below example).
Prior to some Spring Boot version, not sure which, this worked. Currently I'm using Spring Boot v.2.6.1. The UI endpoint got the authentication object from the Http session.
But now it doesn't work. The security context object cannot be found in the Http session using the default HttpSessionSecurityContextRepository implementation. It is saved but it can't be restored.
So is it possible to use two session creation policy, one for the REST and the other for the UI part, or should this be handled in a different way?
Now it seems that the stateless session creation policy is also used by the UI, which is not intended.
I'm using two WebSecurityConfigurerAdapter classes; one for the API and the other for the UI.
After a successful SAML login the redirect URL now contains the ";jsessionid=6051854D94A0771BB9B99FE573AA4DFD" parameter. Probably because of the stateless policy...?
protected void configure(HttpSecurity http) throws Exception {
List<AbstractAuthenticationProcessingFilter> authFilters = new ArrayList<>();
authFilters.add(new OAuthMacAuthenticationProcessingFilter(authenticationManager(), this.properties));
ApiAuthenticationProcessingFilter apiAuthenticationProcessingFilter = new ApiAuthenticationProcessingFilter(authenticationManager(),authFilters);
http
.csrf()
.disable()
.antMatcher("/api/**")
.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.exceptionHandling()
.authenticationEntryPoint((req, rsp, e) -> rsp.sendError(HttpServletResponse.SC_UNAUTHORIZED))
.and()
.addFilterBefore(apiAuthenticationProcessingFilter, BasicAuthenticationFilter.class)
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
and for the UI part
protected void configure(HttpSecurity http) throws Exception {
http.securityContext().securityContextRepository(customSessionSecurityContextRepository);
http
.httpBasic()
.authenticationEntryPoint(samlEntryPoint());
http
.addFilterBefore(metadataGeneratorFilter(), ChannelProcessingFilter.class);
var auth = http
.authorizeRequests()
.antMatchers("/saml/**").permitAll()
.antMatchers("/loggedout/**").permitAll()
.antMatchers("/error").permitAll();
auth
.anyRequest()
.authenticated();
http.csrf().disable();
http.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.ALWAYS);
http.headers().frameOptions().sameOrigin();
http.exceptionHandling().accessDeniedHandler(this.accessDeniedHandler());
http
.logout()
.disable(); // The logout procedure is already handled by SAML filters.
}
I'll answer this myself. The above code does actually work. The problem was on the remote end, the IDP I was using had some problems that day that resulted in that it didn't work as expected. The day after, it worked.

Spring Security - Custom Authentication Provider and HTTP Basic for Actuator Endpoints

I´ve got a running Spring Boot Application (Spring Boot v2.4.1) and I would like to monitor it using Spring Boot Admin.
I have already setup the server and I can monitor the instance of my application with the /actuator/ endpoint not secured. I have a permitAll() on it.
Now I´d like to secure it, but I do not know how to do it without messing with my current Security Configuration.
I have Spring Security configured to match username and password from a DB and with a CustomAuthenticationProvider. If possible I would like to add a Actuator Endpoints with a HTTP Basic authentication.
This is my current security config:
http.
authorizeRequests()
.antMatchers("/admin/**").hasAuthority(AUTHORITY_ADMIN)
.antMatchers("/user/**").hasAnyAuthority(AUTHORITY_ADMIN, AUTHORITY_USER)
.anyRequest().authenticated()
.and()
.csrf().disable()
.formLogin()
.loginPage("/login")
.failureUrl("/login?error=true")
.successHandler(new CustomUrlAuthenticationSuccessHandler(translator))
.usernameParameter("username")
.passwordParameter("password")
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessUrl("/")
.and()
.exceptionHandling().accessDeniedPage("/403")
.and()
.headers().frameOptions().sameOrigin();
I would like to keep that configuration and also tell spring that whenever a user hits /actuator/ endpoint, it will requiere HTTP Basic Security credentials.
I was thinking on having two #Configuration classes, extending WebSecurityConfigurerAdapter. One would be the one I´ve already got and the other one for the actuator endpoints. But I had no luck with it.
Thank you
Thank you very much
You can create two SecurityFilterChain beans, one for your /actuator/** endpoint with higher priority, and other to every other endpoint with lower priority, like so:
#Bean
#Order(1)
public SecurityFilterChain actuatorWebSecurity(HttpSecurity http) throws Exception {
http.requestMatchers((matchers) -> matchers
.antMatchers("/actuator/**"));
http.authorizeRequests((authz) -> authz
.anyRequest().authenticated());
http.httpBasic();
http.userDetailsService(myUserDetailsService);
...
return http.build();
}
#Bean
#Order(2)
public SecurityFilterChain defaultWebSecurity(HttpSecurity http) throws Exception {
// your current configuration
}
In this configuration, the #Order annotation tells the order that the SecurityFilterChains are gonna be matched against the requests.
This is how I solve it: I create a new #Configuraiton class extending WebSecurityConfigurerAdapter,
I was unable to stop using WebSecurityConfigurerAdapter (as suggested by #Marcus-Hert-da-Coregio in the comments) because if I do not extend it I was not able to define my custom AuthenticationProvider.
This class has #Order(1) so it would take precedence over my other initial configuration (which I set to #Order(2)). And this is it's content:
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/actuator/**")
.csrf().disable()
.authorizeRequests()
.anyRequest().authenticated()
.and()
.httpBasic()
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
Then my custom AuthenticationProvider will verify if the given credentials for accessing the actuator endpoints are valid.
Addittional information
The reason why this fails the first time I test it was because I was not setting the initial
.antMatcher("/actuator/**")
by adding it I was telling SpringSecurity that this configuration should only be applied to those endpoints. I get that notion from this article
I hope this helps someone in the future

Spring boot and Spring Security, different logon forms to use different success handlers

I have a spring boot/mvc site using spring security.
I have to use ways of logging in,
In the navbar present on each page
and the login page which you are redirected to when attempting to access a restricted resource.
For the navbar i'd like the user to stay on the page after successful login
For the login page i'd like the user to be redirected to the resource they were trying to originally access after login.
I can do each functionality individually
First use case is handled by:
SimpleUrlAuthenticationSuccessHandler handler = new SimpleUrlAuthenticationSuccessHandler();
handler.setUseReferer(true);
Second case is the default functionality.
But i've been unable to make them both work.
Does anyone have any insights on how to achieve this?
You can configure each login page with a different AuthenticationSuccessHandler like described here
https://www.baeldung.com/spring_redirect_after_login
Like:
#Override
protected void configure(final HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/anonymous*").anonymous()
.antMatchers("/login*").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login.html")
.loginProcessingUrl("/login")
.successHandler(myAuthenticationSuccessHandler())
.and()
.formLogin()
.loginPage("/login2.html")
.loginProcessingUrl("/login2")
.successHandler(mySecondAuthenticationSuccessHandler())
// ...
}

How to allow all resources in static folder of spring boot maven using spring security?

I am creating a app using angular for frontend and spring boot for backend.
I am using spring-boot-security for the security purpose.
Spring boot serves static content from src/main/resources/static folder.
I am placing all the contents of angular dist folder here, i.e. all js,css,html produced by ng build.
But upon running the app, I keep on getting a 401 unauthorized error.
Here is my configure() method:
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.cors()
.and()
.exceptionHandling().authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED))
.and()
.authorizeRequests()
.requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll()
.antMatchers("/api/v1/login/").permitAll()
.anyRequest().authenticated()
.and()
.addFilter(getJWTAuthenticationFilter(authenticationManager()))
.addFilter(new JWTAuthorizationFilter(authenticationManager()));
}
If I add .antMatchers("/**").permitAll() then the app will load all angular resources correctly but makes the security then useless as all api endpoints are then exposed.
Also I read that \css,\images,\js etc. are allowed by default, but here my I just refer to static folder.I also tried moving all the content to a new endpoint, say /app by implementing addResourceHandlers() method, but then my angular code breaks, since it references all css,jss directly in its href and not behind any folder name.
I am using spring boot 2.1.1 release and most of the answers refer to spring boot v1, and I am unable to find a soln.
I want to configure spring security to allow access to just all resources under static folder. Doing so will allow me to use my angular code without changing all hrefs. How can I achieve this?

405 Method Not Allowed for POST

I have a very simple spring boot application, which is secured by the following code:
http.authorizeRequests()
.antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
.and()
.formLogin().loginPage("/login").failureUrl("/login?error")
.usernameParameter("username").passwordParameter("password")
.and()
.logout().logoutSuccessUrl("/login?logout")
.and()
.exceptionHandling().accessDeniedPage("/403");
the idea is to secure "admin" portion. It exposes a REST API.
The problem is all the POSTS returns
405 Method Not Allowed
If I remove the security starter from the application, it works. This makes me believe that the security configuration is the problem. But I cannot find out how.
This should be easy.
POSTs and PUT requests would not be allowed if CSRF is enabled,and spring boot enables those by default.
Just add this to your configuration code :
.csrf().disable()
that is :
http.
.csrf().disable().
authorizeRequests()
.antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
.and()
.formLogin().loginPage("/login").failureUrl("/login?error")
.usernameParameter("username").passwordParameter("password")
.and()
.logout().logoutSuccessUrl("/login?logout")
.and()
.exceptionHandling().accessDeniedPage("/403");
Refer docs ,if you need to enable CSRF :
http://docs.spring.io/spring-security/site/docs/4.0.x/reference/htmlsingle/#csrf-configure
This can also happen if using Spring Security SAML extension and your SAMLUserDetailsService returns a UsernameNotFoundException. Seems pretty counter-intuitive, but that's what it does by default (in my experience).

Resources