【发布时间】:2014-06-12 16:10:20
【问题描述】:
我正在尝试为我参与的项目开发一个 RESTful 网络服务,这对我来说都是全新的。
我正在尝试向网络服务器添加基本身份验证(我的想法是每个使用该服务的应用程序都具有凭据)。至少在这一点上,不会有任何 Web 界面来访问它。 我一直在关注 Spring (http://spring.io/guides/tutorials/rest/) 的教程,试图改变一些东西,主要是因为我正在尝试使用最新版本的 spring。
我被困在一个看似非常简单的部分,即只允许用户使用有效的用户名和密码向系统插入一个新值,但是由于某种原因,当我不断收到错误 403 时我运行特定的测试。
这是我的配置:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{
@Autowired
protected void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.antMatcher("/aggregators/**").authorizeRequests()
.anyRequest().hasRole("USER")
.and().httpBasic();
}
}
在测试类中,错误来自 buildindividual() 构建 JSON 的类
private ResponseEntity<Individual> buildIndividual() {
HttpEntity<String> requestEntity = new HttpEntity<String>(
RestDataFixture.standardIndividualJSON2(),
getHeaders("user:password"));
RestTemplate template = new RestTemplate();
ResponseEntity<Individual> entity = template.postForEntity(
"http://localhost:8080/aggregators/individuals",
requestEntity, Individual.class);
return entity;
}
static HttpHeaders getHeaders(String auth) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
byte[] codedString = Base64.encode(auth.getBytes());
headers.add("Authorization", "Basic " + new String(codedString));
return headers;
}
standardndividualJSON2() 函数只返回一个 JSON 字符串,例如:"{ "key" : "12345" , "name" : "StrackOverflow" }"。
我也有一种方法尝试使用错误的密码创建个人,我得到的错误也是 403(如果我没记错的话应该是 401)。这就是为什么我认为配置可能是错误的,但我不明白为什么。
我的配置有问题吗?如果有人能帮助我,那就太好了。
感谢您的帮助!
编辑
刚决定加个初始化类,可能问题出在这里:
public class WebAppInitializer implements WebApplicationInitializer{
private static Logger LOG = LoggerFactory.getLogger(WebAppInitializer.class);
@Override
public void onStartup(ServletContext servletContext)
throws ServletException {
WebApplicationContext rootContext = createRootContext(servletContext);
configureSpringMvc(servletContext, rootContext);
configureSpringSecurity(servletContext, rootContext);
}
private WebApplicationContext createRootContext(ServletContext servletContext) {
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.register(CoreConfig.class, SecurityConfig.class);
rootContext.refresh();
servletContext.addListener(new ContextLoaderListener(rootContext));
servletContext.setInitParameter("defaultHtmlEscape", "true");
return rootContext;
}
private void configureSpringMvc(ServletContext servletContext, WebApplicationContext rootContext) {
AnnotationConfigWebApplicationContext mvcContext = new AnnotationConfigWebApplicationContext();
mvcContext.register(MVCConfig.class);
mvcContext.setParent(rootContext);
ServletRegistration.Dynamic appServlet = servletContext.addServlet(
"webservice", new DispatcherServlet(mvcContext));
appServlet.setLoadOnStartup(1);
Set<String> mappingConflicts = appServlet.addMapping("/");
if (!mappingConflicts.isEmpty()) {
for (String s : mappingConflicts) {
LOG.error("Mapping conflict: " + s);
}
throw new IllegalStateException(
"'webservice' cannot be mapped to '/'");
}
}
private void configureSpringSecurity(ServletContext servletContext, WebApplicationContext rootContext) {
FilterRegistration.Dynamic springSecurity = servletContext.addFilter("springSecurityFilterChain",
new DelegatingFilterProxy("springSecurityFilterChain", rootContext));
springSecurity.addMappingForUrlPatterns(null, true, "/*");
}
}
编辑 2
通过禁用 CSRF 解决:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().
antMatcher("/aggregators/**").authorizeRequests()
.anyRequest().hasRole("USER")
.and().httpBasic();
}
【问题讨论】:
-
也许
localhost/8080应该是localhost:8080? -
我注意到了那个错字,但没有解决任何问题。我尝试添加密码错误的新个人的测试也返回 403。
-
如果您找到了解决方案,请将其作为答案发布并接受。不要将其附加到问题中。 ;)
标签: java json spring spring-mvc spring-security