-1

再会!

我正在尝试将项目从基于 XML 的项目转换为基于注释的/Java 配置。有没有办法将下面的 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中没有。我不知道如何处理bean的属性。也适用于authentication-manager节点。希望可以有人帮帮我。

提前致谢!

4

1 回答 1

0

您需要声明您的过滤器类。例如:

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-26T21:34:52.150 回答