凭据错误的 POST 请求返回 405 而不是 401

我正在尝试在由 Spring Security 保护的 Spring 中创建新的 POST 端点。端点正在工作。如果我提供正确的数据和凭据,服务器会处理请求并返回 200。如果我提供的凭据不正确,我会得到 405,我预计会得到 401。

我还尝试将控制器的请求方法从 POST 更改为 GET,并将请求从 POST 更改为 GET,并且成功了!对于错误的凭据,a 收到 401,对于正确的凭据,收到 200。

这是我的配置:

控制器

@Controller

@RequestMapping(value = "/api/v1")

@Secured(UserRoles.ROLE_USER)

public class ApiController {


    @RequestMapping(value = "/test", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)

    @ResponseStatus(value = HttpStatus.OK)

    @ResponseBody

    public ResponseEntity<String> handleRequest(@RequestBody DataBody dataBody, Model model, Locale locale) {

        try{

            //do something

            return new ResponseEntity<>("received", HttpStatus.OK);

        } catch (SomeProblemException e) {

            return new ResponseEntity<>(e.toString(), HttpStatus.BAD_REQUEST);

        }

    }

HTTP 请求(邮递员)


POST /api/v1/test HTTP/1.1

Host: localhost:8080

Content-Type: application/json

Authorization: Basic bWFudGfmZjptYW50YQ==

User-Agent: PostmanRuntime/7.15.2

Accept: */*

Host: localhost:8080


{

    "something": "data",

    "somethingelse": "data"

}

HTTP 响应(邮递员)


Status 405


WWW-Authenticate: Basic realm="Spring Security Application"

Allow: GET

我使用 Spring Security 3.2.10-RELEASE。我尝试启用 Spring Security 日志,但我失败了。


大话西游666
浏览 120回答 2
2回答

杨__羊羊

问题出在这里:@Controllerpublic class ErrorController {&nbsp; &nbsp; @RequestMapping("/error")&nbsp; &nbsp; public String error(@RequestParam(value = "err", required = false) Integer paramErrorCode, Locale locale,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ModelMap model, HttpServletRequest httpRequest) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// Do something&nbsp; &nbsp;&nbsp; &nbsp; &nbsp;}我有一个控制器,它处理错误屏幕,但它只支持 GET 方法。当我将其同时更改为 GET 和 POST 时,它开始工作了。解决方案:@Controllerpublic class ErrorController {&nbsp; &nbsp; @RequestMapping(value = "/error" method = {RequestMethod.GET, RequestMethod.POST})&nbsp; &nbsp; public String error(@RequestParam(value = "err", required = false) Integer paramErrorCode, Locale locale,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ModelMap model, HttpServletRequest httpRequest) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// Do something&nbsp; &nbsp;&nbsp; &nbsp; &nbsp;}如果web.xml不确定是什么导致重定向<error-page>&nbsp; &nbsp; <location>/error</location></error-page>或 securitycontext.xml<sec:access-denied-handler error-page="/error?err=403"/>

BIG阳

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;METHOD_NOT_ALLOWED(405,&nbsp;"Method&nbsp;Not&nbsp;Allowed")似乎您在测试时使用的是 GET 方法而不是 POST 方法,一旦您更改为 POSt 将获得下一个异常是&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;UNAUTHORIZED(401,&nbsp;"Unauthorized")
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java