春季安全,REST基本身份验证问题(Spring Security, REST basic auth

2019-09-04 04:08发布

我得到了相关的HTTP响应头一个问题“访问控制允许来源”表示使用春基本authetication时。 当我手动进行身份验证,如代码波纹管(我使用REST):

@RequestMapping(value = "/login", method = RequestMethod.POST, consumes = "application/json")
@ResponseStatus(value = HttpStatus.OK)
public void login(@RequestBody String body, HttpServletResponse response)
        throws IOException {
    try {
        User user = gson.fromJson(body, User.class);

        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
                usuario.getUsername(), usuario.getPassword());

        authenticationManager.authenticate(token);
    } catch (BadCredentialsException e) {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    } catch (Exception e) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

一切正常,我收到下面的HTTP响应:

HTTP/1.1 401 Unauthorized
Server: Apache-Coyote/1.1
Access-Control-Allow-Origin: null
Access-Control-Allow-Credentials: true
Content-Type: text/html;charset=utf-8
Content-Length: 951
Date: Fri, 17 May 2013 19:14:36 GMT

你可以看到,“访问控制允许来源”存在的响应。 一切都在这里很好。 我可以在我的Ajax调用赶上一个401错误。

但是,当自动进行认证,如代码波纹管:

@RequestMapping(value = "/name", method = RequestMethod.POST, consumes = "application/json")
@PreAuthorize("hasRole('ROLE_CUSTOMER')")
public @ResponseBody String getName(HttpServletResponse response) throws IOException {
    String json = null;

    try {
        User userSession = (User) SecurityContextHolder.getContext()
                .getAuthentication().getPrincipal();

        Customer customer = customerDao.getNameByUsername(userSession.getUsername());

        json = gson.toJson(customer);

    } catch (Exception e) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }

    return json;
}

HTTP响应是:

HTTP/1.1 401 Unauthorized
Server: Apache-Coyote/1.1
WWW-Authenticate: Basic realm="Spring Security Application"
Content-Type: text/html;charset=utf-8
Content-Length: 981
Date: Fri, 17 May 2013 19:41:08 GMT

没有“访问控制允许来源”的回应

谷歌浏览器控制台显示以下错误:

Origin null is not allowed by Access-Control-Allow-Origin

我的Ajax调用不返回401未授权错误,即使HTTP响应返回它(响应以上),我收到一个不明错误。

我要指出的是所有的浏览器,我需要一个“访问控制允许来源”的HTTP响应,否则会产生某种沉默的错误,我的Ajax调用会失败(不能捕捉401错误)。 其实,JavaScript就静默失败。 XMLHttpRequest的不接受没有“访问控制允许来源” HTTP响应。

我怎样才能使春天的基本身份验证的HTTP响应注入这个“访问控制允许来源”?

这是我的Spring Security XML:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:security="http://www.springframework.org/schema/security"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
          http://www.springframework.org/schema/beans
          http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
          http://www.springframework.org/schema/security
          http://www.springframework.org/schema/security/spring-security-3.1.xsd">

    <security:http create-session="stateless" entry-point-ref="authenticationEntryPoint">
        <security:intercept-url pattern="/customer/**" />
        <security:http-basic />
        <security:custom-filter ref="basicAuthenticationFilter"
            after="BASIC_AUTH_FILTER" />
    </security:http>

    <bean id="basicAuthenticationFilter"
        class="org.springframework.security.web.authentication.www.BasicAuthenticationFilter">
        <property name="authenticationManager" ref="authenticationManager" />
        <property name="authenticationEntryPoint" ref="authenticationEntryPoint" />
    </bean>

    <bean id="authenticationEntryPoint"
        class="org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint">
        <property name="realmName" value="teste.com" />
    </bean>

    <!-- It is responsible for validating the user's credentials -->
    <security:authentication-manager alias="authenticationManager">

        <!-- It is responsible for providing credential validation to the AuthenticationManager -->
        <security:authentication-provider>
            <security:password-encoder ref="passwordEncoder" />

            <security:jdbc-user-service
                data-source-ref="mySQLdataSource"
                users-by-username-query="select username, password, enabled from usuario where username = ?"
                authorities-by-username-query="select username, papel from autoridade where username = ?" />

        </security:authentication-provider>

    </security:authentication-manager>

    <bean class="org.springframework.security.crypto.password.StandardPasswordEncoder"
        id="passwordEncoder" />

</beans>

Answer 1:

刚刚发现我自己的方式:

首先,我真的不记得为什么我在这里把这个线,但它搞乱了我的代码:

<security:http-basic />

其次,这个答案告诉我的路径: 拉手未经授权的错误消息的基本身份验证在春季安全 。 我不得不为了发送访问控制允许来源的东西来创建自定义的身份验证入口点。

所以这是我现在的代码:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:security="http://www.springframework.org/schema/security"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
              http://www.springframework.org/schema/beans
              http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
              http://www.springframework.org/schema/security
              http://www.springframework.org/schema/security/spring-security-3.1.xsd">

    <security:http create-session="stateless"
        entry-point-ref="authenticationEntryPoint">
        <security:intercept-url pattern="/api/admin/**" />
        <security:intercept-url pattern="/medico/**" />
        <!-- <security:http-basic />  -->
        <security:custom-filter ref="basicAuthenticationFilter"
            after="BASIC_AUTH_FILTER" />
    </security:http>

    <bean id="basicAuthenticationFilter"
        class="org.springframework.security.web.authentication.www.BasicAuthenticationFilter">
        <property name="authenticationManager" ref="authenticationManager" />
        <property name="authenticationEntryPoint" ref="authenticationEntryPoint" />
    </bean>

            <!-- 
    <bean id="authenticationEntryPoint" 
        class="org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint">
        <property name="realmName" value="test.com" />
    </bean> -->


    <bean id="authenticationEntryPoint" 
        class="com.test.util.PlainTextBasicAuthenticationEntryPoint">
        <property name="realmName" value="test.com" />
    </bean> 

    <!-- It is responsible for validating the user's credentials -->
    <security:authentication-manager alias="authenticationManager">

        <!-- It is responsible for providing credential validation to the AuthenticationManager -->
        <security:authentication-provider>
            <security:password-encoder ref="passwordEncoder" />

            <security:jdbc-user-service
                data-source-ref="mySQLdataSource"
                users-by-username-query="select username, password, enabled from usuario where username = ?"
                authorities-by-username-query="select username, papel from autoridade where username = ?" />

        </security:authentication-provider>

    </security:authentication-manager>

    <bean
        class="org.springframework.security.crypto.password.StandardPasswordEncoder"
        id="passwordEncoder" />

</beans>
package com.test.util;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint;

public class PlainTextBasicAuthenticationEntryPoint extends
        BasicAuthenticationEntryPoint {

      @Override
        public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
            response.addHeader("Access-Control-Allow-Origin", "null");
            response.addHeader("WWW-Authenticate", "Basic realm=\"" + getRealmName() + "\"");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            PrintWriter writer = response.getWriter();
            writer.println("HTTP Status " + HttpServletResponse.SC_UNAUTHORIZED + " - " + authException.getMessage());
        }

}

我现在的HTTP响应:

HTTP/1.1 401 Unauthorized
Server: Apache-Coyote/1.1
Access-Control-Allow-Origin: null
WWW-Authenticate: Basic realm="test.com"
Content-Length: 35
Date: Mon, 20 May 2013 20:05:03 GMT

HTTP Status 401 - Bad credentials

变更前,我收到此错误信息:

OPTIONS http://localhost:8080/test/customer/name 200 (OK) jquery-1.8.2.min.js:2
XMLHttpRequest cannot load http://localhost:8080/test/customer/name. Origin null is     not allowed by Access-Control-Allow-Origin. 

现在按预期我得到这个:

OPTIONS http://localhost:8080/test/customer/name 200 (OK) jquery-1.8.2.min.js:2
POST http://localhost:8080/test/customer/name 401 (Unauthorized) 


文章来源: Spring Security, REST basic authentication issue