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

时间:2019-08-19 15:41:09

标签: java spring spring-security

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

我发现问题something similar,但我认为不是我的情况。相同的question,没有回应。

我还尝试将控制器的请求方法从POST更改为GET,并将请求从POST更改为GET,并且有效!对于错误的凭据,将收到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);
        }
    }

安全上下文

    <!-- In Memory Authentication Manager -->
    <sec:authentication-manager id="inMemoryAuthManager" >
        <sec:authentication-provider>
            <sec:user-service properties="WEB-INF/classes/usersRoles.properties"/>    
            <sec:password-encoder hash="bcrypt" />
        </sec:authentication-provider>
    </sec:authentication-manager>

    <!-- Definition of access rules for API -->
    <sec:http use-expressions="true" pattern="/api/**" create-session="stateless"
        authentication-manager-ref="inMemoryAuthManager">
        <sec:intercept-url pattern="/api/**"
            access="hasRole('ROLE_USER')"/>
        <sec:http-basic/>
    </sec:http>

    <!-- Definition of access rules for WEB GUI. -->
    <sec:http use-expressions="true"
        authentication-manager-ref="inMemoryAuthManager">
        <!-- Resources and errors do not need authorization. -->
        <sec:intercept-url pattern="/favicon.ico" access="permitAll"/>
        <sec:intercept-url pattern="/css/**" access="permitAll"/>
        <sec:intercept-url pattern="/img/**" access="permitAll"/>
        <sec:intercept-url pattern="/js/**" access="permitAll"/>
        <sec:intercept-url pattern="/fonts/**" access="permitAll"/>
        <sec:intercept-url pattern="/error/**" access="permitAll"/>
        <sec:intercept-url pattern="/login" access="permitAll"/>
        <sec:intercept-url pattern="/login.do" access="permitAll"/>

        <!-- The rest of pages need authorized user with role ROLE_USER. -->
        <sec:intercept-url pattern="/**"
            access="hasRole('ROLE_USER')"/>
        <!-- Configuration of login page. -->
        <sec:form-login login-page="/login"
            login-processing-url="/login.do"
            authentication-failure-url="/login?error=true"
            default-target-url="/applications" username-parameter="username"
            password-parameter="password"/>
        <!-- Redirect from logout page. -->
        <sec:logout logout-url="/logout"
            logout-success-url="/login?logout=true" invalidate-session="true"
            delete-cookies="JSESSIONID"/>
        <!-- Redirect for forbidden page. -->
        <sec:access-denied-handler error-page="/error?err=403"/>
        <!-- Port configuration. -->
        <sec:port-mappings>
            <sec:port-mapping http="8080" https="8443"/>
        </sec:port-mappings>
        <sec:headers>
            <sec:frame-options policy="DENY"/>
            <sec:content-type-options/>
            <sec:xss-protection block="true"/>
        </sec:headers>
    </sec:http>    

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日志,但失败了。

2 个答案:

答案 0 :(得分:1)

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<div class="content">
<nav class="navbar navbar-expand-lg"  style="border-bottom: 3px solid blue;">
  <div class="container">
    <a class="navbar-brand" href="index.html">new
    </a>
    <a class="navbar-brand" href="index.html">new
    </a>
    <a class="navbar-brand" href="index.html">new
    </a>
    <a class="navbar-brand" href="index.html">new
    </a>
    <a class="navbar-brand" href="index.html">new
    </a>
    <a class="navbar-brand" href="index.html">new
    </a>
    <a class="navbar-brand" href="index.html">new
    </a>
  </div>
  </nav>
  <p>lorem ipsum lorem ipsum lorem ipsum lorem ipsumlorem ipsum lorem ipsumlorem ipsumlorem ipsum lorem ipsum</p></div>

好像您在测试时使用的是POST方法中的GET方法,一旦更改为POSt将得到下一个异常是

        METHOD_NOT_ALLOWED(405, "Method Not Allowed")

答案 1 :(得分:1)

问题在这里:

@Controller
public class ErrorController {
    @RequestMapping("/error")
    public String error(@RequestParam(value = "err", required = false) Integer paramErrorCode, Locale locale,
            ModelMap model, HttpServletRequest httpRequest) {
         // Do something   
     }

我有一个控制器,可以处理错误屏幕,但它仅支持GET方法。当我将其更改为GET和POST时,它开始工作。


解决方案:

@Controller
public class ErrorController {
    @RequestMapping(value = "/error" method = {RequestMethod.GET, RequestMethod.POST})
    public String error(@RequestParam(value = "err", required = false) Integer paramErrorCode, Locale locale,
            ModelMap model, HttpServletRequest httpRequest) {
         // Do something   
     }

不确定是什么原因导致重定向 web.xml

<error-page>
    <location>/error</location>
</error-page>

securitycontext.xml

<sec:access-denied-handler error-page="/error?err=403"/>