0

我正在使用 Spring 4.1.6 和spring-boot-starter-data-rest.

为了使其余的 api 功能齐全,我需要最后一块拼图:安全性。现在我注意到 spring 有它自己的spring-security-*包可以帮助完成这项任务。

我尝试使用spring-security-configandspring-security-web它就像一个魅力,除了如果用户未通过身份验证,spring 会将用户重定向到登录,从而提供 HTML 登录表单。因为它是一个 Restful API,所以如果用户缺少凭据或没有足够的权限来读取特定资源,我只需要在 JSON 对象中返回一个错误。我敢肯定我不是第一个提出这个问题的人,我在网上搜索了问同样问题的人,但找不到我正在寻找的东西。那么..我应该继续使用spring-security在这个方向上进行研究,还是应该找到一些东西?

欢迎任何建议,谢谢

4

1 回答 1

1

要将登录表单响应更改为自定义 Http 响应,您需要为 Http 安全配置配置自定义 http 响应处理程序。如果您使用 xml 进行安全配置,请使用下面显示的配置,failureHandler使用的是 Spring Security 包中可用的配置。更新 URL 以匹配您的。

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

    <!-- Rest authentication entry point configuration -->
    <http use-expressions="true" entry-point-ref="restAuthenticationEntryPoint">
        <intercept-url pattern="/api/**" />
        <sec:form-login authentication-failure-handler-ref="myFailureHandler" />

        <logout />
    </http>

    <!-- Using default failure handler -->
    <beans:bean id="myFailureHandler"
        class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler" />
</beans:beans>
于 2015-04-26T01:21:39.530 回答