Skip to content

Commit

Permalink
Enable CORS except for Public API
Browse files Browse the repository at this point in the history
  • Loading branch information
cjmalloy committed Nov 27, 2023
1 parent 64006f7 commit 762e936
Show file tree
Hide file tree
Showing 4 changed files with 33 additions and 17 deletions.
29 changes: 19 additions & 10 deletions src/main/java/jasper/config/SecurityConfiguration.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.http.HttpMethod;
import org.springframework.security.access.hierarchicalroles.RoleHierarchy;
import org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
Expand All @@ -15,6 +16,8 @@
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
import org.springframework.security.web.csrf.CsrfTokenRepository;
import org.springframework.security.web.header.writers.ReferrerPolicyHeaderWriter;
import org.springframework.web.context.annotation.ApplicationScope;
import org.springframework.web.cors.CorsConfiguration;
Expand Down Expand Up @@ -87,8 +90,6 @@ private boolean profile(String profile) {
public void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.csrf()
.disable()
.exceptionHandling()
.authenticationEntryPoint(problemSupport)
.accessDeniedHandler(problemSupport)
Expand All @@ -107,25 +108,33 @@ public void configure(HttpSecurity http) throws Exception {
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.apply(securityConfigurerAdapter())
.and()
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS, "/api/v1/**").permitAll()
.and()
.headers()
.frameOptions()
.sameOrigin()
.and()
.cors().configurationSource(request -> {
var config = new CorsConfiguration();
config.addAllowedMethod("*");
config.applyPermitDefaultValues();
return config;
});
// @formatter:on
.csrf()
.csrfTokenRepository(csrfTokenRepository())
.ignoringAntMatchers("/api/v1/repl/**") // Public API
; // @formatter:on
}

private JWTConfigurer securityConfigurerAdapter() {
@Bean
JWTConfigurer securityConfigurerAdapter() {
logger.info("Minimum Role: {}", props.getMinRole());
return new JWTConfigurer(props, tokenProvider, defaultTokenProvider);
}

@Bean
CsrfTokenRepository csrfTokenRepository() {
var r = CookieCsrfTokenRepository.withHttpOnlyFalse();
r.setSecure(false); // Required when using SSL terminating gateway
return r;
}

@Bean
@ApplicationScope
public RoleHierarchy roleHierarchy() {
Expand Down
5 changes: 5 additions & 0 deletions src/main/java/jasper/security/jwt/JWTFilter.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.GenericFilterBean;

Expand Down Expand Up @@ -38,6 +39,10 @@ public JWTFilter(Props props, TokenProvider tokenProvider, TokenProviderImplDefa
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
var httpServletRequest = (HttpServletRequest) servletRequest;
if ("OPTIONS".equalsIgnoreCase(httpServletRequest.getMethod())) {
SecurityContextHolder.getContext().setAuthentication(new PreAuthenticatedAuthenticationToken("options", null));
}

var origin = resolveOrigin(httpServletRequest);
var jwt = resolveToken(httpServletRequest);
if (tokenProvider.validateToken(jwt, origin)) {
Expand Down
2 changes: 2 additions & 0 deletions src/main/java/jasper/web/rest/ReplicateController.java
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
Expand All @@ -47,6 +48,7 @@
import static jasper.domain.proj.HasOrigin.ORIGIN_LEN;
import static jasper.repository.filter.Query.QUERY_LEN;

@CrossOrigin
@RestController
@RequestMapping("api/v1/repl")
@Validated
Expand Down
14 changes: 7 additions & 7 deletions src/main/resources/config/application-dev.yml
Original file line number Diff line number Diff line change
Expand Up @@ -80,13 +80,13 @@ jasper:
scrape-interval-min: 5
# CORS is disabled by default on microservices, as you should access them through a gateway.
# If you want to enable it, please uncomment the configuration below.
# cors:
# allowed-origins: "http://localhost:9000,https://localhost:9000"
# allowed-methods: "*"
# allowed-headers: "*"
# exposed-headers: "Authorization,Link,X-Total-Count"
# allow-credentials: true
# max-age: 1800
cors:
allowed-origins: "http://localhost:4200,https://localhost:4200"
allowed-methods: "*"
allowed-headers: "*"
exposed-headers: "Authorization,Link,X-Total-Count"
allow-credentials: true
max-age: 1800
security:
clients:
default:
Expand Down

0 comments on commit 762e936

Please sign in to comment.