Add CSS file to Spring Boot + Spring Security Thymeleaf file - spring-boot

I wanted to add CSS file to my HTML file.
The problem appeared when I tried to add CSS to Spring Security application (I work on basic Spring Getting Started Content). I blame Spring Security because without it the CSS file loads properly.
Application.java file:
package mainpack;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class Application {
public static void main(String[] args) throws Throwable {
SpringApplication.run(Application.class, args);
}
}
MvcConfig.java file:
package mainpack;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
#Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/home").setViewName("home");
registry.addViewController("/").setViewName("home");
registry.addViewController("/hello").setViewName("hello");
registry.addViewController("/login").setViewName("login");
registry.addViewController("/index").setViewName("index");
registry.addViewController("/register").setViewName("register");
registry.addViewController("/whatever").setViewName("whatever");
}
}
WebSecurityConfig.java file:
package mainpack;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/home", "/index", "/register", "../static/css", "../static/images").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
}
I load CSS with line:
<link href="../static/css/index.css" th:href="#{/css/index.css}" rel="stylesheet" />
in index.html file.

Your pattern ../static/css is not matching your relative URL ../static/css/index.css, see AntPathMatcher:
PathMatcher implementation for Ant-style path patterns.
Part of this mapping code has been kindly borrowed from Apache Ant.
The mapping matches URLs using the following rules:
? matches one character
* matches zero or more characters
** matches zero or more directories in a path
{spring:[a-z]+} matches the regexp [a-z]+ as a path variable named "spring"
and Spring Boot Reference:
By default, resources are mapped on /** but you can tune that via spring.mvc.static-path-pattern.
Your request will be redirected to login form, because your are not logged in and all other requests need authentication.
To fix it, change your pattern to /css/** and /images/**.
A better solution for static resources is WebSecurity#ignoring:
Allows adding RequestMatcher instances that Spring Security should ignore. Web Security provided by Spring Security (including the SecurityContext) will not be available on HttpServletRequest that match. Typically the requests that are registered should be that of only static resources. For requests that are dynamic, consider mapping the request to allow all users instead.
Example Usage:
webSecurityBuilder.ignoring()
// ignore all URLs that start with /resources/ or /static/
.antMatchers("/resources/**", "/static/**");

The web.ignore()worked the best for me. just add the following method to your WebSecurityConfig class.
#Override
public void configure(WebSecurity web) throws Exception {
web
.ignoring()
.antMatchers("/resources/**", "/static/**", "/css/**", "/js/**", "/img/**", "/icon/**");
}

.antMatchers("/**/*.js", "/**/*.css").permitAll();
This allows all the js and css files present in resources/static folder to be permitted for request access.

Related

How to set WebSSOProfileConsumerImpl in your Spring Configuration file

I am facing issue of specifying WebSSOProfileConsumerImpl to my Spring Configuration file. I am trying to modify responseSkew in this bean but after adding configuration for WebSSOProfileConsumerImpl I am getting MetadataManager issue
APPLICATION FAILED TO START
Description:
Parameter 0 of method setMetadata in org.springframework.security.saml.websso.AbstractProfileBase required a bean of type 'org.springframework.security.saml.metadata.MetadataManager' that could not be found.
Action:
Consider defining a bean of type 'org.springframework.security.saml.metadata.MetadataManager'
Can anyone help me in resolving this issue?
I have already gone through the link : http://docs.spring.io/spring-security-saml/docs/current/reference/html/configuration-advanced.html but it does not specify how to set this in configuration.
My Code
import static org.springframework.security.extensions.saml2.config.SAMLConfigurer.saml;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.saml.websso.WebSSOProfileConsumer;
import org.springframework.security.saml.websso.WebSSOProfileConsumerImpl;
#EnableWebSecurity
#Configuration
#EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Value("${security.saml2.metadata-url}")
String metadataUrl;
#Value("${server.ssl.key-alias}")
String keyAlias;
#Value("${server.ssl.key-store-password}")
String password;
#Value("${server.port}")
String port;
#Value("${server.ssl.key-store}")
String keyStoreFilePath;
#Value("${security.saml2.responseSkew}")
int responseSkew = 0;
#Override
protected void configure(final HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/saml*").permitAll()
.anyRequest().authenticated()
.and()
.apply(saml())
.serviceProvider()
.keyStore()
.storeFilePath(this.keyStoreFilePath)
.password(this.password)
.keyname(this.keyAlias)
.keyPassword(this.password)
.and()
.protocol("https")
.hostname(String.format("%s:%s", "localhost", this.port))
.basePath("/")
.and()
.identityProvider()
.metadataFilePath(this.metadataUrl).and();
/* Map<? extends Object, Object> sharedObjects = new Map<? extends Object>, Object>(http.getSharedObjects());
sharedObjects.put(WebSSOProfileConsumer.class, webSSOprofileConsumerImpl());*/
}
#Bean
#Qualifier("webSSOprofileConsumer")
public WebSSOProfileConsumer webSSOprofileConsumerImpl() {
WebSSOProfileConsumerImpl consumerImpl = new WebSSOProfileConsumerImpl();
consumerImpl.setResponseSkew(this.responseSkew);
return consumerImpl;
}
}
If you do not need the WebSSOProfileConsumer to be accessible as a bean to the rest of the application, you can create it inside the configure method like this:
#Override
protected void configure(final HttpSecurity http) throws Exception {
WebSSOProfileConsumerImpl consumerImpl = new WebSSOProfileConsumerImpl();
consumerImpl.setResponseSkew(this.responseSkew);
http
.authorizeRequests()
.antMatchers("/saml*").permitAll()
.anyRequest().authenticated()
.and()
.apply(saml())
.serviceProvider()
.ssoProfileConsumer(consumerImpl) // <-- added here
.keyStore()
// Your method continues as before
I do not remember the exact reason regular wiring fails in your case, but the gist of it is that configure sets up a builder object rather than regular beans. Normally the ServiceProviderBuilder provides the MetadataManager needed by your WebSSOProfileConsumer during its build step, but if you autowire the profile consumer you won't get the MetadataManager provided for you since your autowired object is assumed to be complete already.
(I learned this when looking for a way to configure the max authentication age, since the two hour default in spring-security-saml in some cases is lower than the defaults used by identity providers. This effectively locks your users out of your application until the identity provider's max authentication age has passed.)

Principal is null in controller when using http.csrf().disable()

I have a controller and POJO that I want to test. The GET to the REST interface forces a login and returns a principal object and so all is good. I was able to extend WebSecurityConfigurerAdapter to enable and username and password for testing.
However, during testing, the Spring framework requires a CSRF token for a POST request. Since I have no UI and I am only testing the REST interface I want to disable it temporarily.
So I extended WebSecurityConfigurerAdapter as per the documentation:
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("{noop}password").roles("USER");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
}
}
However this disabled the authentication. My controller receives a Principal object that is null. Here is my controller:
import java.security.Principal;
import org.springframework.context.annotation.Scope;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.neutech.model.ShoppingCart;
#Scope("session")
#RestController
#RequestMapping("/cart/api/v1")
public class SomeController {
#RequestMapping(value = "/thing", method = RequestMethod.POST)
public void create(#RequestBody String stuff,#AuthenticationPrincipal Principal user) {
// do stuff
}
I have tried various flavours of setting CSRF for specific URLs or HTTP verbs. All with the same result. The principal delivered to the controller is null.
After scouring the net for some kind of resolution to this I can come up with nothing. There are lots of examples tell me to do exactly what I am doing. However I only find only other similar type questions.
Can someone explain to me what I am doing wrong?
In order to enable authentication change your configure method, try this:
http
.csrf().disable()
.authorizeRequests()
.anyRequest()
.fullyAuthenticated();
If you use Spring Boot 1.5, you could disable CSRF by properties, see
Spring Boot Reference Guide:
security.enable-csrf=false # Enable Cross Site Request Forgery support.
If you use Spring Boot 2.0, you have to write a complete Spring Security configuration, see Spring Boot Security 2.0:
Custom Security
If you want to configure custom security for your application, you will need to add a WebSecurityConfigurerAdapter that adds all the bits that you want to configure. In order to avoid ordering issues with the WebSecurityConfigurerAdapter, Spring Boot auto-configuration will back off completely.
Example:
#Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.csrf().disable()
}
}

Spring security always returning 403

Can someone tell me why this code is always returning 403?
I mapped /login to trigger the security login but it is not working properly.
package esercizio.security;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("q#q").password("pluto").roles("USER");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/**").anonymous()
.antMatchers("/auth/**").hasRole("USER")
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login.jsp")
.defaultSuccessUrl("/auth/list-student")
.failureUrl("/errorPage")
.and()
.logout().logoutSuccessUrl("/login.jsp");
}
}
It should let anyone in if the URL doesn't start with /auth, I don't know why it doesn't happen.
I think, you must prepend 'ROLE_' to you authority like ROLE_USER.
For more visit :
Spring Security always return the 403 accessDeniedPage after login

Spring Boot JS App wont work after securing rest-api with Spring Security

I created a simple Spring Boot/ JS App. In a next step I tried to implement an usermanagement feature to handle multiple users.
So I implemented a usermodel and controller and secured all rest-api calls via authentication of spring security.
#Configuration
#EnableWebSecurity
#ComponentScan("package.packagename")
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
DataSource dataSource;
#Autowired
public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception{
auth.jdbcAuthentication().dataSource(dataSource)
.usersByUsernameQuery("select email, password, active from accounts where email=?")
.authoritiesByUsernameQuery("select email, role from account_roles where email=?");
}
#Override
#Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
protected void configure(HttpSecurity http) throws Exception {
http
.formLogin().permitAll()
.and()
.authorizeRequests()
.antMatchers("/index.html", "/").permitAll()
.anyRequest().authenticated()
.and()
.logout();
}
}
Additionally to this file I have the SecurityWebApplicationInitializer
public class SecurityWebApplicationInitializer
extends AbstractSecurityWebApplicationInitializer {
public SecurityWebApplicationInitializer() {
super(SecurityConfig.class);
}
}
My problem now is the fact, that if I start the application and try to access it via localhost:8080 I face an 404 Error.
Usually the app should work even without login and it seems that with springsecurity enabled the app is not able to load the js stuff in resources/public directory.
Reading the logs showed the following:
No mapping found for HTTP request with URI [/] in DispatcherServlet with name 'dispatcherServlet'
If I start the App without spring security it works without any problems.
The securing of the api-calls works like a charm - I'm able to login, receive a cookie and use this cookie to authenticate against the api-functions which are secured by springsecurity.
I hope you can help me to resolve my (hopefully small) problem.
Thanks in advance
When you use .formLogin() you need to define the login page or use .httpBasic() auth. So you can use something like this:
.formLogin()
.and()
.httpBasic();
or
.formLogin()
.loginPage("/login.html")
You can read more here
http://docs.spring.io/spring-security/site/docs/3.2.x/guides/form.html
http://www.baeldung.com/spring-security-login
I figured out that I have to add a WebConfig.java class like this:
import org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
#Configuration
#EnableWebMvc
#ComponentScan
public class WebConfig extends WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter {
}
Now Spring is able to resolve the / call properly. I just have to make sure to open the access to all files in public for all users (permitall() function).
Anyway thanks for your help :-)

Allow Iframe for all domains while using Spring Security

I am using Spring Security. By default It doesn't allow a page to be loaded in iframe.
Spring Security set header X-Frame-Options value 'DENY'. I don't want this header to be include in my application.
Here is my configuration file.
package com.some.package.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import com.some.package.crm.enums.Role;
import com.some.package.security.AuthSuccessHandler;
import com.some.package.security.AuthenticationProvider;
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private AuthenticationProvider authenticationProvider;
#Autowired
private AuthSuccessHandler authSuccessHandler;
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider);
}
#Bean
public PasswordEncoder getPasswordEncoder(){
PasswordEncoder encoder = new BCryptPasswordEncoder();
return encoder;
}
#Override
public void configure(WebSecurity webSecurity) throws Exception
{
webSecurity
.ignoring()
// All of Spring Security will ignore the requests
.antMatchers("/resources/**", "/","/site/**","/affLinkCount", "/forgotPassword","/thirdPartyLogin", "/resetPassword", "/notifyCallbackToRecurring");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
/*
* Security Headers added by default
* Cache Control
* Content Type Options
* HTTP Strict Transport Security
* X-Frame-Options
* X-XSS-Protection
* csrf added by default
*/
http
.authorizeRequests()
.antMatchers("/crm/**").hasRole(Role.CUSTOMER.name())
.antMatchers("/analyst/**").hasRole(Role.ANALYST.name())
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.failureUrl("/login?failed=true")
.successHandler(authSuccessHandler)
.usernameParameter("username")
.passwordParameter("password").loginProcessingUrl("/j_spring_security_check")
.permitAll()
.and()
.sessionManagement().sessionFixation().newSession()
.sessionAuthenticationErrorUrl("/login")
.invalidSessionUrl("/login")
.maximumSessions(1)
.expiredUrl("/login").and()
.and()
.exceptionHandling().accessDeniedPage("/login")
.and()
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/login")
.permitAll();
// .and().headers().frameOptions().disable();
// addFilterAfter(new IFrameEnableFilter(), HeaderWriterFilter.class);
//.headers().frameOptions().addHeaderWriter(new XFrameOptionsHeaderWriter(new WhiteListedAllowFromStrategy(Arrays.asList("localhost"))));
// .headers().addHeaderWriter(new XFrameOptionsHeaderWriter(new WhiteListedAllowFromStrategy(Arrays.asList("localhost"))));
}
}
If you are using Spring Security 4, then you can do this with something like:
http
.headers()
.frameOptions().disable()
.and()
// ...
You can find additional details in the 4.0.x reference.
In Spring Security 3.2.x things are a little different if you want to continue using the other HTTP headers. You need to do something like this:
http
.headers()
.contentTypeOptions();
.xssProtection()
.cacheControl()
.httpStrictTransportSecurity()
.frameOptions()
.and()
// ...
Additional details can be found in the 3.2.x reference.
Thank you #Rob Winch to your answer which leaded me to find a simple solution from the same source, where I could disable it in the xml configuration file as below:
<security:frame-options disabled="true"/>
I just shared this since it may be used by others in order to not do code changes, so it only requires configuration updates

Resources