Skip to content

Instantly share code, notes, and snippets.

@lusabo
Last active May 1, 2018 22:02
Show Gist options
  • Save lusabo/584c7bc2f12b631eb06bfac9e69043fe to your computer and use it in GitHub Desktop.
Save lusabo/584c7bc2f12b631eb06bfac9e69043fe to your computer and use it in GitHub Desktop.
WebSecurityConfig
package com.eco.security;
// Imports
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private JwtAuthenticationEntryPoint unauthorizedHandler;
@Autowired
private UserDetailsService userDetailsService;
@Autowired
public void configureAuthentication(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
authenticationManagerBuilder.userDetailsService(this.userDetailsService).passwordEncoder(passwordEncoder());
}
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Bean
public UserDetailsService userDetailsServiceBean() throws Exception {
return super.userDetailsServiceBean();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public JwtAuthenticationTokenFilter authenticationTokenFilterBean() throws Exception {
return new JwtAuthenticationTokenFilter();
}
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
/*
* Este trecho está desabilitando cross-site scripting, informa qual exceção devemos chamar em caso de erro,
* informa como deve ser o controle de sessão, no caso, sem estado (stateless) e diz que para acessar o recurso
* /login o usuário não precisa estar autenticado e nos demais recursos é preciso autenticação.
*/
httpSecurity.csrf().disable().exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests()
.antMatchers("/login").permitAll().anyRequest().authenticated();
httpSecurity.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);
httpSecurity.headers().cacheControl();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment