对于浏览器中的 REST API 抛出登录对话框,我也遇到了同样的问题。如您所说,当浏览器将响应标头视为
WWW-Authenticate: Basic realm="Spring Security Application
它将提示一个基本的身份验证对话框。对于基于 REST API 的登录,这并不理想。这是我的做法。定义一个自定义身份验证入口点,并在开始时
将标题设置为“FormBased”
response.setHeader("WWW-Authenticate", "FormBased");
application-context.xml 配置如下
<security:http create-session="never" entry-point-ref="authenticationEntryPoint" authentication-manager-ref="authenticationManager">
<security:custom-filter ref="customRestFilter" position="BASIC_AUTH_FILTER" />
<security:intercept-url pattern="/api/**" access="ROLE_USER" />
</security:http>
<bean id="authenticationEntryPoint" class="com.tito.demo.workflow.security.RestAuthenticationEntryPoint">
</bean>
下面的自定义入口点类。
@Component
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
private static Logger logger = Logger.getLogger(RestAuthenticationEntryPoint.class);
public void commence( HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException ) throws IOException {
logger.debug("<--- Inside authentication entry point --->");
// this is very important for a REST based API login.
// WWW-Authenticate header should be set as FormBased , else browser will show login dialog with realm
response.setHeader("WWW-Authenticate", "FormBased");
response.setStatus( HttpServletResponse.SC_UNAUTHORIZED );
}
}
注意:我用的是spring 3.2.5.Release
现在,当从像 POSTMAN 这样的 restclient 访问 rest API 时,服务器将返回 401 Unauthorized。