I have a spring boot application and I want to enable the HSTS over my domain (say https:example.com).
I wrote the script in WebSecurityConfigurerAdapter. The code snippet is shown below.
#EnableWebSecurity
#Configuration
#Order(1)
public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
// #formatter:off
http
.authorizeRequests()
.antMatchers(HttpMethod.TRACE, "/**").denyAll()
.antMatchers("/**").permitAll();
http
.antMatcher("/**").httpBasic()
.and().csrf().disable()
.headers().httpStrictTransportSecurity()
.includeSubDomains(true)
.maxAgeInSeconds(31536000);
// #formatter:on
}
}
The deployment of the spring boot application happened in the Azure cloud. After the deployment, I'm not seeing the HSTS header when I hit the base domain.
But I can see the header when hitting the entire URL (say https://example.com/questions/ask).
Any help would be appreciated. Thanks!
Related
I want to run a Vaadin 23 frontend but also have a REST API in my application. I want to use Token-Based (JWT) authentication for the REST API and Standard form-based for the frontend. I have tested a lot of different configurations from examples in the Spring Security documentation and around the internet. The only configuration where both options get called upon initialization is this one:
#EnableWebSecurity
public class SecurityConfiguration extends VaadinWebSecurity {
// ... other stuff here ...
#Bean
#Order(1)
public SecurityFilterChain restFilterChain(HttpSecurity http) throws Exception {
return http
.cors().and().csrf().disable()
.authorizeRequests().antMatchers("/api/login").anonymous().and()
.authorizeRequests().antMatchers("/api/**").authenticated().and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.addFilterBefore(authTokenFilter(), UsernamePasswordAuthenticationFilter.class)
.build();
}
#Bean
#Order(2)
public SecurityFilterChain frontendFilterChain(HttpSecurity http) throws Exception {
super.configure(http);
setLoginView(http, LoginView.class, LOGOUT_URL);
return http.build();
}
}
Both configuration blocks work, I have tried with either one being #Order(1) and the other being #Order(2). The configuration that gets #Order(1) is called on login and authentication works. But there is no fallback to #Order(2) regardless of how the other attempt ends (with .denyAll() or just "nothing"). What am I missing here?
Spring Version: 5.3.22
Spring Security Version: 5.7.3
I am trying to secure actuator health endpoint using spring security:
To achieve this, I have added the following:
#Configuration
#EnableWebSecurity
public class ActuatorSecurityConfiguration extends WebSecurityConfigurerAdapter implements ApplicationContextAware {
private static final String ACTUATOR_ROLE = System.getenv("actuatorRole");
#Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/actuator/**")
.hasRole(ACTUATOR_ROLE)
.anyRequest().authenticated();
}
}
The following properties I have defined in my application.properties file:
spring.security.user.name=${username}
spring.security.user.password=${actuatorPassword}
spring.security.user.roles=${actuatorRole}
management.endpoint.health.roles=${actuatorRole}
But when I am trying to run the health check after this configuration, it is giving me 403 Forbidden error. Can anybody please help me why I am getting this error?
Does this help:
application.properties:
management.endpoints.enabled-by-default=false
management.endpoints.web.exposure.include=health
management.endpoint.health.enabled=true
management.endpoint.health.show-details=always
I need a help
I'm doing migration spring boot 1.5.17 -> 2.2.1 and everything is fine except spring security.
The problem is I can't login from my login form(tried default login page, same result). Login with basic auth works fine.
I have enabled debug logs with logging.level.org.springframework.security=DEBUG config but still nothing.
What I noticed is when I'm typing wrong credentials - it says 'Username/password is incorrect' so seems the problem is not with password encoder, as spring security version changed.
Than I check browser's networks devtool tab and I can see following: first request goes to /login -> than it redirects to /welcome and than again to /login (see on screen)
Here is my security config
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(securedEnabled = true)
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
#Autowired
private UserService userService;
#Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and()
.csrf().disable()
.authorizeRequests()
.antMatchers("/css/**", "/images/**", "/script/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/welcome", true)
.failureUrl("/login/error").permitAll();
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService).passwordEncoder(PasswordEncoderFactories.createDelegatingPasswordEncoder());
}
}
Help please
Thank you in advance
I've built a REST API service using Spring where I've enabled sessions using MongoDB:
#Configuration
#EnableMongoHttpSession(maxInactiveIntervalInSeconds = Globals.SESSION_MAX_INTERVAL)
public class SessionConfig {
#Bean
public AbstractMongoSessionConverter createSessionConverterBean() {
return new JacksonMongoSessionConverter(Collections.singletonList(new GeoModule()));
}
}
I would however, like to have control over which connections should be issued a session. Currently, every HTTP request has a session generated for it, but there are scenarios where the session is not needed, and I'd prefer not to clutter up the session storage with session objects that will never be used.
One such scenario is a standalone desktop application that acts as a content management system. This application has no need for HTTP sessions because authentication is done via the application side via a custom authorization header. This application also only accesses endpoints from a certain root route mapping:
Public traffic routes to api.domain.com/pub and the CMS traffic routes through api.domain.com/cpi.
It would be nice to be able to tell Spring that it does not need to create a session for any requests coming to /cpi. The desktop application also provides a unique Origin that I can match as well if that is more easily done.
My Web security looks like this:
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest()
.permitAll()
.and()
.cors()
.and()
.httpBasic();
http.csrf().disable(); // Self-implemented
}
I've searched all over and haven't found a thing. Can anyone point me in the right direction?
Thanks!
You could add multiple security configuration in the following scheme. Where one is explicitly matching for the all /cpi requests and the other one handling the remaining requests.
You could also configure different authentication methods this way.
#Order(1)
#Configuration
public static class Custom1WebSecurityConfigurerAdapter extends
WebSecurityConfigurerAdapter {
http
.antMatcher("/cpi/**")
.authorizeRequests()
...
http.sessionManagement() // dont create a session for this configuration
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
#Order(2)
#Configuration
public static class Custom2WebSecurityConfigurerAdapter extends
WebSecurityConfigurerAdapter {
http
.authorizeRequests()
...
}
You could try below in application.yml file.
server:
servlet:
session:
persistent: false
timeout: 0
I work on angularjs application and I try to serve static resource (my front end) with Spring boot.
I used gulp to build project and I get this distribution structure:
here is the content of hash folder
my spring security config look like this:
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.exceptionHandling()
.authenticationEntryPoint(myEntryPoint());
http
.authorizeRequests()
.antMatchers("/__hash__/**").permitAll()
.antMatchers("/views/**").permitAll()
.antMatchers("/index.html").permitAll()
.antMatchers("/api/**").authenticated()
.antMatchers("/**").permitAll();
http // login configuration
.addFilterAfter(springSecurityFilter(), BasicAuthenticationFilter.class);
/*http
.authorizeRequests()
.anyRequest().authenticated();*/
http //logout configuration
.logout()
.logoutSuccessHandler(logoutHandler());
http.csrf().disable();
}
The config spring for serving static content:
#Configuration
public class MyContentConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/**")
.addResourceLocations("file:///" + "c:/front/") ;
}
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("forward:/index.html");
}
}
After authentication, I get the index.html page but without css style and without js.
And when I try to access to css using this url "https://localhost:9999/hash/styles.min.css" I get this error:
There was an unexpected error (type=Not Acceptable, status=406).
Could not find acceptable representation
You are loading livereload.js over http. If you are using https, all resource must be load over https.
so load livereload.js over https.
I resolved the problem. it's related to "spring-cloud-config-server". I just delete this config:
org.springframework.cloud
spring-cloud-config-server