Springboot安全和休息控制器,我想允许所有

时间:2016-07-06 13:04:37

标签: rest spring-mvc spring-security

我有一个带有spring-boot-starter-security和spring-boot-starter-thymeleaf以及spring-boot-starter-data-rest的springboot wab mvc应用程序。 我有一个简单的登录页面来访问欢迎用户页面。 除此之外,我还有一个休息控制器来提供Web服务:

MyRestController:

 @RequestMapping( value = "/device" )
   @RestController
   public class DeviceController {

    @Autowired
    IDeviceService deviceService;

    @RequestMapping(value="/saveProfile", method=RequestMethod.POST, produces="application/json")
    public ResponseEntity<Device> saveDeviceProfil(@RequestBody Device device) throws Throwable{
        Device deviceUpdated = deviceService.saveIfNotNull(device);
        return new ResponseEntity<Device>(deviceUpdated, HttpStatus.OK);
    }
}

我的安全配置:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

      @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                .authorizeRequests()
                    .antMatchers("/", "/home").permitAll()
                    .antMatchers(HttpMethod.POST,"/device/**").permitAll()
                    .anyRequest().authenticated()
                    .and()
                .formLogin()
                    .loginPage("/login")
                    .permitAll()
                    .and()
                .logout()
                    .permitAll();
        }

        @Autowired
        public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
            auth
                .inMemoryAuthentication()
                    .withUser("user").password("password").roles("USER");
        }       
}

当我尝试使用Postman访问http://localhost:8080/device/saveProfile时,我收到登录页面而不是JSON对象。尽管有我的安全配置,但安全性似乎并不允许所有人:

.antMatchers(HttpMethod.POST,"/device/**").permitAll()

1 个答案:

答案 0 :(得分:2)

我在WebSecurityConfig类中添加此函数时解决了这个问题:

@Override
        public void configure(WebSecurity web) throws Exception {

            web.ignoring().antMatchers("/device/**");
        }