Rest Spring 来自 UI 的身份验证调用:在请求正文中传递用户名和密码,而不是在 url 参数中,以使用 spring 安全性进行身份验证

Rest Spring Authentication call from UI: Pass username and password in request body, not in url parameter, to authenticate using spring security

我正在使用 Spring 安全性进行身份验证。从 UI 如果我 post 在请求正文中输入用户名和密码,那么我将收到 HTTP 401 错误。但是,如果我在 URL 中 post 输入用户名和密码,那么它工作正常。

请找到我的Spring安全配置:

     <http auto-config="true"  use-expressions="true">

        <form-login login-processing-url="/rest/auth/j_spring_security_check"
            login-page="/rest/requiredlogin" authentication-failure-handler-ref="authFailureHandler"
            authentication-success-handler-ref="authSuccessHandler"
            username-parameter="username" password-parameter="password" />


        <logout logout-url="/rest/auth/logout" invalidate-session="true" delete-cookies="true" success-handler-ref="authLogOutSuccessHandler"/>

        <csrf disabled="true" />
    </http>

请找到我的 UI 请求:

login(userName, password): Observable<any> {

    const loginData = {'username' : userName, 'password' : password};

    const authUrlParam = 'rest/auth/j_spring_security_check';
    return post(authUrlParam, loginData);
  }

post(url: string, data: any): Observable<any> {
    console.log('Posting Data to Server url : ' + environment.serverUrl + url);

    const reqOp: RequestOptions = this.getHeaders();

    const returnResponse = this.http
      .post(environment.serverUrl + url, data, reqOp)
      .map((response: Response) => response.json().data)
      .catch(this.handleError);
    return returnResponse;
  }

我正在使用以下技术:

Spring: 4.3.9.RELEASE Spring 安全性:4.2.3.RELEASE Angular: 5.2.7

我正在寻找 post 体内凭据的解决方案。否则如果我 post 在 URL 那么任何人都可以看到凭证。

终于找到解决办法了。

现在我的登录数据,即我发布到服务器进行身份验证的凭据,是一个简单的字符串,如 "username=someusername&password=somepassword"。另请注意,我在请求中发送 content-type: application/x-www-form-urlencoded

login(userName, password): Observable<any> {

    const loginData = 'username=' + userName + '&password=' + password;

    const authUrlParam = 'rest/auth/j_spring_security_check';
    return this.ajaxService.postForLogin(authUrlParam, loginData, 'application/x-www-form-urlencoded');
  }

postForLogin(url: string, data: any, contentType: string): Observable<any> {
    console.log('Posting Data to Server url : ' + environment.serverUrl + url);

    const headers = new Headers();
    headers.append('Content-Type', contentType);
    const reqOp = new RequestOptions({ headers: headers, withCredentials: true });

    const returnResponse = this.http
      .post(environment.serverUrl + url, data, reqOp)
      .map((response: Response) => response.json().data)
      .catch(this.handleError);
    return returnResponse;
  }