Spring Security - Конфигурация Java

Добрый день!

Я пытаюсь преобразовать проект в аннотацию / конфигурацию Java на основе проекта на основе XML. Есть ли способ превратить приведенную ниже конфигурацию XML в конфигурацию Java?

<beans:bean id="jwtAuthenticationFilter" class="foo.bar.security.JwtAuthenticationFilter">  
        <beans:property name="authenticationManager" ref="authenticationManager"/>
        <beans:property name="authenticationSuccessHandler" ref="jwtAuthenticationSuccessHandler" />  
    </beans:bean>

    <authentication-manager alias="authenticationManager">
        <authentication-provider ref="jwtAuthenticationProvider" />  
    </authentication-manager>

Это, кстати, фрагмент из файла security-context.xml, который я использую. Я пытаюсь найти решение здесь, но документация для @Bean не имеет его Я не знаю, что делать со свойствами бобов. А также для authentication-manager узел. Надеюсь, кто-нибудь может мне помочь.

Заранее спасибо!

1 ответ

Вы должны объявить свой класс фильтра. Например:

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");
  }

}
Другие вопросы по тегам