2017-02-26 203 views
-1

美好的一天!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中的一個片段。我試圖尋找解決方案here,但@Bean的文檔沒有它。我不知道該如何處理bean的屬性。並且還用於authentication-manager節點。希望可以有人幫幫我。

提前致謝!

回答

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

}