필터 클래스를 선언해야합니다. 예 :
public class JwtAuthenticationFilter extends OncePerRequestFilter {
private final AuthenticationManager authenticationManager;
public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
String authToken = request.getHeader("X-AUTH-TOKEN");
if (authToken == null) {
chain.doFilter(request, response);
return;
}
Authentication authentication = authenticationManager.authenticate(new JwtAuthenticationToken(authToken));
SecurityContextHolder.getContext().setAuthentication(authentication);
chain.doFilter(request, response);
}
}
그리고 SecurityConfiguration 클래스를 만듭니다. 예 :
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Value("${secret.key}")
private String secretKey;
@Autowired
private UserRepository userRepository;
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.authenticationEventPublisher(new NoopAuthenticationEventPublisher())
.authenticationProvider(new JwtAuthenticationProvider(secretKey, userRepository));
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.csrf().disable()
.addFilterBefore(new JwtAuthenticationFilter(authenticationManager()), AbstractPreAuthenticatedProcessingFilter.class)
.addFilterBefore(new BasicAuthenticationFilter(authenticationManager()), BasicAuthenticationFilter.class)
.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/owner/**").hasAnyRole("OWNER", "ADMIN")
.antMatchers("/health", "invitation/accept").permitAll()
.antMatchers("/**").hasRole("USER");
}
}
출처
2017-02-26 21:34:52
hya