首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Spring-安全性基本HTML身份验证

Spring-安全性基本HTML身份验证
EN

Stack Overflow用户
提问于 2014-06-12 16:10:20
回答 1查看 266关注 0票数 0

我正试图为我参与的一个项目开发一个RESTful new服务,这对我来说都是非常新的。

我正在尝试向uses服务器添加一个基本身份验证(我的想法是,每个使用该服务的应用程序都具有凭据)。不会有任何网络接口来访问它,至少在这一点上。我一直在学习spring (http://spring.io/guides/tutorials/rest/)的教程,试图改变一些东西,主要是因为我试图使用Spring的最新版本。

我被困在一个表面上似乎很简单的部分,即只允许用户使用有效的用户名和密码向系统插入一个新值,但是由于某种原因,在运行特定测试时,我一直会得到错误403。

这是我的配置:

代码语言:javascript
复制
@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();
    }

}

在测试类中,错误来自构建个人()构建JSON的类

代码语言:javascript
复制
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字符串,如:"{“键”:"12345“,”名称“:"StrackOverflow”}“。

我还有一种方法试图创建一个密码错误的个人,我得到的错误也是403 (如果我没有弄错的话,它应该是401 )。这就是为什么我认为配置可能是错误的,但我不明白为什么。

我的配置有问题吗?如果有人能帮我,那就太好了。

谢谢你的帮助!

编辑

刚决定添加初始化程序类,可能问题是:

代码语言:javascript
复制
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解决:

代码语言:javascript
复制
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().
antMatcher("/aggregators/**").authorizeRequests()
.anyRequest().hasRole("USER")
.and().httpBasic();
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-01-16 15:36:37

通过禁用CSRF解决:

代码语言:javascript
复制
@Override
protected void configure(HttpSecurity http) throws Exception {
   http.csrf().disable().
   antMatcher("/aggregators/**").authorizeRequests()
   .anyRequest().hasRole("USER")
   .and().httpBasic();
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24189105

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档