【问题标题】:Spring Security Authentication Entry PointSpring Security 身份验证入口点
【发布时间】:2013-06-20 13:39:28
【问题描述】:

我在我的 security-context.xml 上设置 AuthenticationEntryPoint 为我的 Spring MVC 应用程序启用了 Rest 支持

<http auto-config="false" use-expressions="true"
            disable-url-rewriting="true" entry-point-ref="restAuthenticationEntryPoint">

RestAuthenticationEntryPoint.java

@Component
public final class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(final HttpServletRequest request, final HttpServletResponse response, final AuthenticationException authException) throws IOException {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
    }

}

每当任何用户尝试访问资源而不进行身份验证时,都会出现以下错误:

HTTP Status 401 - Unauthorized

上述行为仅适用于 Rest 服务。但是,如果用户未通过身份验证,我希望默认行为将用户重定向到正常 Web 请求的登录页面。如何做到这一点?

【问题讨论】:

标签: spring-security


【解决方案1】:

我通过在 API 请求中发送 HTTP 标头并根据该标头从 AuthenticationEntryPoint 的开始方法发送响应来实现这一点

您可以通过在开始方法中添加以下代码来实现:

if(request.getHeader("request-source") != null && request.getHeader("request-source").equals("API")) {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
    }else {
        response.sendRedirect("/login");                    
    }

【讨论】:

    猜你喜欢
    • 2015-05-11
    • 2022-01-15
    • 2014-02-26
    • 2013-01-15
    • 2019-08-25
    • 2013-10-30
    • 2014-04-07
    • 2012-02-18
    • 2019-04-08
    相关资源
    最近更新 更多