Skip to content

Instantly share code, notes, and snippets.

@OmarElgabry
Last active April 30, 2019 21:33
Show Gist options
  • Select an option

  • Save OmarElgabry/27dd327a25c439d0aa375c9d14a725bf to your computer and use it in GitHub Desktop.

Select an option

Save OmarElgabry/27dd327a25c439d0aa375c9d14a725bf to your computer and use it in GitHub Desktop.
Gateway Security Configurations
package com.eureka.zuul.security;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
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.web.authentication.UsernamePasswordAuthenticationFilter;
import com.eureka.zuul.security.JwtConfig;
@EnableWebSecurity // Enable security config. This annotation denotes config for spring security.
public class SecurityTokenConfig extends WebSecurityConfigurerAdapter {
@Autowired
private JwtConfig jwtConfig;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
// make sure we use stateless session; session won't be used to store user's state.
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
// handle an authorized attempts
.exceptionHandling().authenticationEntryPoint((req, rsp, e) -> rsp.sendError(HttpServletResponse.SC_UNAUTHORIZED))
.and()
// Add a filter to validate the tokens with every request
.addFilterAfter(new JwtTokenAuthenticationFilter(jwtConfig), UsernamePasswordAuthenticationFilter.class)
// authorization requests config
.authorizeRequests()
// allow all who are accessing "auth" service
.antMatchers(HttpMethod.POST, jwtConfig.getUri()).permitAll()
// must be an admin if trying to access admin area (authentication is also required here)
.antMatchers("/gallery" + "/admin/**").hasRole("ADMIN")
// Any other request must be authenticated
.anyRequest().authenticated();
}
@Bean
public JwtConfig jwtConfig() {
return new JwtConfig();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment