使用Spring Rest服务进行基本身份验证的AuthenticationCredentialsNotFoundException

时间:2016-04-25 11:25:24

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

我运行了我的Spring Rest服务的AuthenticationCredentialsNotFoundException,应该使用基本身份验证来保护它。这导致HTTP 500而不是预期的403。 配置中缺少什么?

我的Spring安全配置:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, proxyTargetClass = true)
public class MySecurityConfig extends WebSecurityConfigurerAdapter {

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

我的春天配置:

@Configuration
@ComponentScan(basePackages = {"com.dummy"})
@EnableWebMvc
@Import({MySecurityConfig.class})
public class MySpringConfig extends WebMvcConfigurerAdapter implements WebApplicationInitializer {

    @Override
    public void onStartup(final ServletContext servletContext) throws ServletException {
        final AnnotationConfigWebApplicationContext context = getContext();
        servletContext.addListener(new ContextLoaderListener(context));
        final ServletRegistration.Dynamic dispatcher = servletContext.addServlet("springDispatcher",
                new DispatcherServlet(context));
        dispatcher.setLoadOnStartup(0);
        dispatcher.addMapping("/");
    }

    private AnnotationConfigWebApplicationContext getContext() {
        final AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.register(MySpringConfig.class);
        return context;
    }
}

我的安全控制器:

@RestController
@RequestMapping("/dummy")
public class MyController {

    @PreAuthorize("hasRole('USER')")
    @RequestMapping(method = RequestMethod.POST)
    public HttpEntity<?> doSomething() {
        return new ResponseEntity<>(HttpStatus.CREATED);
    }
}

我的失败测试(实际:500,预期:403)

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = MySpringConfig.class)
public class MyControllerTest {

    @Autowired
    protected WebApplicationContext context;

    protected MockMvc mvc;

    @Before
    public void setUp() throws Exception {
        new TestContextManager(getClass()).prepareTestInstance(this);
        this.mvc = MockMvcBuilders.webAppContextSetup(this.context).build();
    }

    @Test
    public void doDummy_not_authorized_403() throws Exception {
        final MockHttpServletResponse response = this.mvc.perform(post("/dummy")).andDo(MockMvcResultHandlers.print()).andReturn().getResponse();
        assertThat(response.getStatus(), equalTo(403));
    }
}

0 个答案:

没有答案