Last active
January 23, 2020 14:05
-
-
Save sophea/acb37a3c82fd36335bbbfdcd83ed244b to your computer and use it in GitHub Desktop.
Springboot SecurityConfig
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.sma.security.config; | |
@Configuration | |
@EnableWebSecurity | |
@EnableGlobalMethodSecurity(prePostEnabled = true, | |
securedEnabled = true) | |
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { | |
@Autowired | |
private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint; | |
@Autowired | |
private UserDetailsService jwtUserDetailsService; | |
@Autowired | |
private JwtRequestFilter jwtRequestFilter; | |
@Autowired | |
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { | |
// configure AuthenticationManager so that it knows from where to load | |
// user for matching credentials | |
// Use BCryptPasswordEncoder | |
auth.userDetailsService(jwtUserDetailsService).passwordEncoder(passwordEncoder()); | |
} | |
@Bean | |
public PasswordEncoder passwordEncoder() { | |
return new BCryptPasswordEncoder(); | |
} | |
@Bean | |
@Override | |
public AuthenticationManager authenticationManagerBean() throws Exception { | |
return super.authenticationManagerBean(); | |
} | |
@Override | |
protected void configure(HttpSecurity httpSecurity) throws Exception { | |
// We don't need CSRF for this example | |
httpSecurity | |
.csrf().disable() | |
.exceptionHandling() | |
.authenticationEntryPoint(jwtAuthenticationEntryPoint) | |
.and() | |
.sessionManagement() | |
.sessionCreationPolicy(SessionCreationPolicy.STATELESS) | |
.and() | |
// dont authenticate this particular request | |
.authorizeRequests() | |
.antMatchers("/authenticate", "/register").permitAll() | |
// all other requests need to be authenticated | |
// anyRequest().authenticated() | |
; | |
// Add a filter to validate the tokens with every request | |
httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment