在Spring Boot下将Spring xml配置转换为Java配置

时间:2017-07-23 08:17:07

标签: java spring spring-mvc spring-boot

我正在尝试将用XML编写的现有应用程序Spring安全配置迁移到Java配置(使用Spring Boot)

关于如何为以下xml定义Java配置,请帮忙吗?看着不同的网页我一直很困惑.. 提前谢谢!

<security:http auto-config="false" entry-point-ref="filterEntryPoint">
    <security:custom-filter before="FORM_LOGIN_FILTER" ref="myWebAuthorizationFilter" />
    <security:intercept-url pattern="/**" access="ROLE_USER,ROLE_EVP"/>
</security:http>

<bean id="filterEntryPoint" 
        class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint">
    <property name="loginFormUrl">
        <value>https://companyLogin.com</value>
    </property>
    <property name="forceHttps">
        <value>false</value>
    </property>
</bean>

1 个答案:

答案 0 :(得分:0)

对于此部分,您需要定义自定义过滤器

<security:http auto-config="false" entry-point-ref="filterEntryPoint">
    <security:custom-filter before="FORM_LOGIN_FILTER" ref="myWebAuthorizationFilter" />
    <security:intercept-url pattern="/**" access="ROLE_USER,ROLE_EVP"/>
</security:http>

,例如

public class MyCustomFilter extends GenericFilterBean {
    @Override
    public void doFilter (ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        chain.doFilter(request, response);
}

然后注册自定义过滤器

@Configuration
public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .addFilterBefore(new MyCustomFilter(), UsernamePasswordAuthenticationFilter.class);
            .authorizeRequests()
                .antMatchers("/**").access("hasRole('ROLE_USER') and hasRole('ROLE_EVP')");
    }
}

要详细了解自定义过滤器,请点击here

接下来,对于这个

<bean id="filterEntryPoint" 
  class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint">
<property name="loginFormUrl">
    <value>https://companyLogin.com</value>
</property>
<property name="forceHttps">
    <value>false</value>
</property>

您需要定义一个bean

@Configuration
public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .addFilterBefore(new MyCustomFilter(), UsernamePasswordAuthenticationFilter.class);
            .authorizeRequests()
                .antMatchers("/**").access("hasRole('ROLE_USER') and hasRole('ROLE_EVP')");

    //defined bean
    @Bean
    public LoginUrlAuthenticationEntryPoint filterEntryPoint() {
        LoginUrlAuthenticationEntryPoint entryPoint = new LoginUrlAuthenticationEntryPoint("https://companyLogin.com");
        entryPoint.setForceHttps(false);

        return entryPoint;
    }
}

我认为就是这样。