基于Java注释的Spring安全配置

时间:2017-09-05 03:49:53

标签: java spring spring-mvc spring-security

我尝试执行基于Java注释的Spring security配置。我按照教程完成后,按照提供的代码进行操作

@Configuration
@EnableWebSecurity
// need to change this to the security directory
@ComponentScan("")
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private RestAuthenticationEntryPoint restAuthenticationEntryPoint;

    @Autowired
    private MySavedRequestAwareAuthenticationSuccessHandler authenticationSuccessHandler;

    @Override
    protected void configure(AuthenticationManagerBuilder auth)
            throws Exception {

        auth.inMemoryAuthentication()
                .withUser("temporary").password("temporary").roles("ADMIN")
                .and()
                .withUser("user").password("userPass").roles("USER");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .exceptionHandling()
                .authenticationEntryPoint(restAuthenticationEntryPoint)
                .and()
                .authorizeRequests()
                .antMatchers("/api/foos").authenticated()
                .and()
                .formLogin()
                .successHandler(authenticationSuccessHandler)
                .failureHandler(new SimpleUrlAuthenticationFailureHandler())
                .and()
                .logout();
    }

    @Bean
    public MySavedRequestAwareAuthenticationSuccessHandler mySuccessHandler() {
        return new MySavedRequestAwareAuthenticationSuccessHandler();
    }

    @Bean
    public SimpleUrlAuthenticationFailureHandler myFailureHandler() {
        return new SimpleUrlAuthenticationFailureHandler();
    }
}

我工作的项目的API基础,

public static final String API_BASE = "/*";

例如,我执行cURL请求,例如

curl -X GET http://localhost:8080/rest/wallet/wallets | json

我不确定代码中的.antMatchers("/api/foos").authenticated()行。例如,foos来自何处,是否需要将其更改为.antMatchers("/foos").authenticated()

1 个答案:

答案 0 :(得分:2)

如果您不熟悉编程,那么这是一个有效的问题。但要习惯它。所有的例子通常都有'foo'和'bar'作为样本变量,方法名等。

无论如何,RAutomation指定匹配/ api / foo的模式URL需要进行身份验证,然后应使用以下处理程序。

将模式更改为匹配的模式 - .antMatchers("/api/foos").authenticated()并测试您的代码。

如需更多参考 - 请阅读以下文章:When to use Spring Security`s antMatcher()?