Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java rest应用程序的Spring安全性。POST始终返回403代码_Java_Spring_Spring Mvc_Spring Security_Spring Restcontroller - Fatal编程技术网

Java rest应用程序的Spring安全性。POST始终返回403代码

Java rest应用程序的Spring安全性。POST始终返回403代码,java,spring,spring-mvc,spring-security,spring-restcontroller,Java,Spring,Spring Mvc,Spring Security,Spring Restcontroller,这是我的spring-security.xml: <security:http pattern="/eklienci/**" authentication-manager-ref="authenticationManager" entry-point-ref="restAuthenticationEntryPoint" create-session="stateless"> <security:intercept-url

这是我的spring-security.xml:

    <security:http pattern="/eklienci/**"
        authentication-manager-ref="authenticationManager" entry-point-ref="restAuthenticationEntryPoint"
        create-session="stateless">
        <security:intercept-url pattern="/eklienci/**"
            access="hasAnyAuthority('ADMIN','USER','VIEWER')" />
        <form-login
            authentication-success-handler-ref="mySuccessHandler"
            authentication-failure-handler-ref="myFailureHandler"
        />
        <security:custom-filter ref="restServicesFilter"
            before="PRE_AUTH_FILTER" />
    </security:http>
    <!-- other stuff --!>
  <beans:bean id="restAuthenticationEntryPoint"
      class="pl.aemon.smom.config.RestAuthenticationEntryPoint" />
  <!-- Filter for REST services. -->
  <beans:bean id="restServicesFilter"
    class="pl.aemon.smom.config.RestUsernamePasswordAuthenticationFilter">
    <beans:property name="postOnly" value="true" />
    <beans:property name="authenticationManager" ref="authenticationManager" />
    <beans:property name="authenticationSuccessHandler" ref="mySuccessHandler" />
 </beans:bean>
当我尝试调用/get/{eklientid}时,它总是工作正常。所有GET调用都会返回至少一个关于非正交访问(401)的信息,并且我会看到RestUsernamePasswordAuthenticationFilter中的日志

但是,当我尝试任何POST调用(例如/eClienci/add}时,我的应用程序总是返回403代码,并且不生成任何日志。原因是什么?如何修复它?

对于常见的非GET方法(如POST、PUT、DELETE),如果您没有在REST调用中放置CSRF头,则默认情况下会激活403。您可以(暂时!)关闭security.xml中的CSRF以确认这是问题所在。您主要需要将添加到REST调用和任何客户端服务器调用的JSP标记中。仅供参考,我需要在我的开源项目中实现的其他类,可能对您有用:

  • 关闭某些不需要授权的POST/PUT等的CSRF。如my security.xml中配置的
  • 将会话超时导致的CSRF 403路由到登录页面

  • 关闭CSRF保护。如果您有
    create session=“stateless”
    ,则不需要该保护

    
    
    您提到的GET请求在返回状态代码401时可以正常工作,这意味着什么?此调用发生在身份验证之前还是之后?不,不是真的:@GlenMazza在某些特殊情况下不安全,但OP似乎既不使用身份验证cookie也不使用基本身份验证。
    public class RestUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter
    {
    
        @Autowired
        private CustomAuthenticationProvider authenticationProvider;
    
    
        @Override
        public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
    
            Enumeration<String> names = request.getHeaderNames();
            while(names.hasMoreElements())
            {
                System.out.println(names.nextElement());
            }
            String username = obtainUsername(request);
            String password = obtainPassword(request);
            System.out.println("Username " + username + " password: " + password);
            if(username!=null)
            {
                username = username.trim();
            }
    
            UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
    
            // Allow subclasses to set the "details" property
            setDetails(request, authRequest);
            return authenticationProvider.authenticateRest(authRequest);
    
    //        System.out.println(auth.toString());
    //        return auth;
        }
    
    
    
        @Override
        protected String obtainPassword(HttpServletRequest request) {
            return request.getHeader("password");
        }
    
        @Override
        protected String obtainUsername(HttpServletRequest request) {
            return request.getHeader("username");
        }
    
        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
                ServletException {
    
            HttpServletRequest httpRequest = (HttpServletRequest) request;
            HttpServletResponse httpResponse = (HttpServletResponse) response;
    
            Authentication auth = attemptAuthentication(httpRequest, httpResponse);
            SecurityContextHolder.getContext().setAuthentication(auth);
    
            chain.doFilter(request, response);
    
        }
    }
    
    @RestController
    @RequestMapping("/eklienci")
    public class EklientRestController
    {
        @RequestMapping(value="/get/{eklientid}")
        public Eklient get(@PathVariable String eklientid) 
        {
            return userService.findById(eklientid);
        }
    
        @RequestMapping(value = "/add", method = RequestMethod.POST, produces="application/json", consumes="application/json")
        @ResponseBody
        public String add(@RequestBody String json) 
        {
            System.out.println(json);
            Eklient pj = new Eklient();
            ObjectMapper mapper = new ObjectMapper();
            try
            {
                pj = mapper.readValue(json, Eklient.class);
                return mapper.writeValueAsString(pj);
            } catch (JsonParseException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (JsonMappingException e)
            {
            // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    
            return "Error";
        }
    }