Skip to content

Instantly share code, notes, and snippets.

@matthewbednarski
Last active August 29, 2015 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matthewbednarski/ea00c571bd56c1eecd93 to your computer and use it in GitHub Desktop.
Save matthewbednarski/ea00c571bd56c1eecd93 to your computer and use it in GitHub Desktop.
SecurityConfig.java an example Spring security configuration file
package configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.security.web.csrf.CsrfFilter;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.security.web.csrf.CsrfTokenRepository;
import org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.WebUtils;
import javax.inject.Inject;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
ApplicationConfigBase.java ApplicationConfig.java DataSourceConfig.java JerseyConfig.java QuartzConfig.java SecurityConfig.java Created by matthewb on 8/4/15.
*/
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.passwordEncoder(encoder())
.withUser("test").password(encoder().encode("password1")).roles("USER")
.and()
.withUser("admin").password(encoder().encode("admin1")).roles("USER", "ADMIN")
;
}
@Configuration
public static class WebEndpointsSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
// .antMatcher("/api/**")
// .authorizeRequests().anyRequest().authenticated()
// .and()
// .rememberMe()
// .regexMatcher("^(?!api/).*")
.regexMatcher(".*")
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.logout().deleteCookies("JSESSIONID", "XSRF-TOKEN")
.and()
.csrf()
.csrfTokenRepository(csrfTokenRepository())
.and()
.addFilterAfter(new SecurityConfig.CsrfHeaderFilter(), CsrfFilter.class)
.rememberMe()
;
}
@Bean
public CsrfTokenRepository csrfTokenRepository() {
HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
repository.setHeaderName("X-XSRF-TOKEN");
return repository;
}
}
@Configuration
@Order(1)
public static class ApiEndpointsSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/api/**")
.csrf().disable()
.authorizeRequests()
.antMatchers(HttpMethod.DELETE, "/api/**").hasRole("ADMIN")
.antMatchers(HttpMethod.POST, "/api/**").hasRole("ADMIN")
.antMatchers(HttpMethod.PUT, "/api/**").hasRole("ADMIN")
.antMatchers(HttpMethod.GET, "/api/**").authenticated()
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER)
.and()
.addFilter(new BasicAuthenticationFilter(authenticationManager()))
.httpBasic()
.and()
.rememberMe()
;
}
}
@Bean
public BCryptPasswordEncoder encoder() {
return new BCryptPasswordEncoder();
}
public static class CsrfHeaderFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class
.getName());
if (csrf != null) {
Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN");
String token = csrf.getToken();
if (cookie == null || token != null && !token.equals(cookie.getValue())) {
cookie = new Cookie("XSRF-TOKEN", token);
cookie.setPath("/");
response.addCookie(cookie);
}
}
filterChain.doFilter(request, response);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment