【问题标题】:Spring Security for RESTful APIRESTful API 的 Spring Security
【发布时间】:2015-07-04 11:54:49
【问题描述】:

我正在使用 Spring 4.1.6 和 spring-boot-starter-data-rest 构建一个宁静的 API。

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

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

欢迎任何建议, 谢谢你

【问题讨论】:

    标签: spring rest spring-security spring-security-rest


    【解决方案1】:

    要将登录表单响应更改为自定义 Http 响应,您需要为 Http 安全配置配置自定义 http 响应处理程序。如果您使用 xml 进行安全配置,请使用下面显示的配置,failureHandler used 是 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>
    

    【讨论】:

    猜你喜欢
    • 2014-04-06
    • 1970-01-01
    • 2016-04-19
    • 2015-05-04
    • 2016-02-12
    • 2023-03-28
    • 2020-12-21
    • 2016-10-01
    • 2015-12-03
    相关资源
    最近更新 更多