在Spring Security中,如何为每个人忽略一些资源/ URL?

时间:2018-12-27 10:05:23

标签: java spring spring-mvc spring-security spring-rest

我有一些URL(到目前为止是一个),我想允许每个用户使用,例如注册和登录URL。我只想在注册后排除任何网址路径,并保护或限制任何其他网址。

请参考以下代码:

   package com.travelplanner.rest.config;

    //COPY
    import javax.sql.DataSource;

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
    import org.springframework.security.config.annotation.web.builders.HttpSecurity;
    import org.springframework.security.config.annotation.web.builders.WebSecurity;
    import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
    import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
    import org.springframework.security.core.userdetails.User;
    import org.springframework.security.core.userdetails.User.UserBuilder;
    import org.springframework.security.provisioning.JdbcUserDetailsManager;
    import org.springframework.security.provisioning.UserDetailsManager;

    @Configuration
    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
        @Autowired
        private DataSource securityDataSource;

        @Bean
        public UserDetailsManager userDetailsManager() {
            JdbcUserDetailsManager jdbcUserDetailsManager = new JdbcUserDetailsManager();
            jdbcUserDetailsManager.setDataSource(securityDataSource);
            return jdbcUserDetailsManager;
        }

        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.jdbcAuthentication().dataSource(securityDataSource);
        }

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.cors().and().httpBasic().and().csrf().disable()     
            .authorizeRequests().antMatchers("/register/**").permitAll();
        }

    }

这是Google App Engine中的Spring MVC Rest。我已经使用了上面的代码片段,它说即使对antmatchers也未授权。请帮忙!预先感谢。

1 个答案:

答案 0 :(得分:-1)

可能是httpBasic()部分需要身份验证。您应该首先放置特定的说明,最后放置更一般的说明,因此请尝试以下操作:

http.cors().and().csrf().disable()
    .authorizeRequests().antMatchers("api/users/register/user").permitAll()
    .and()
    .anyRequest().httpBasic();

这使每个人都可以访问“ api /用户/注册/用户”,但需要其他网址的http身份验证。