我在我的Spring MVC应用程序上启用了Rest支持,并AuthenticationEntryPoint在我的security-context.xml上设置为
<http auto-config="false" use-expressions="true"
disable-url-rewriting="true" entry-point-ref="restAuthenticationEntryPoint">
Run Code Online (Sandbox Code Playgroud)
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");
}
}
Run Code Online (Sandbox Code Playgroud)
每当任何用户尝试访问资源而不进行身份验证时,都会出现以下错误:
HTTP Status 401 - Unauthorized
Run Code Online (Sandbox Code Playgroud)
以上行为仅适用于Rest服务.但是,如果用户尚未通过身份验证,我希望具有将用户重定向到登录页面以进行正常Web请求的默认行为.怎么做到这一点?
小智 0
我通过在 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");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
46624 次 |
| 最近记录: |