【问题标题】:How to handle 401 with spring boot with angular 8如何使用带角度 8 的弹簧靴处理 401
【发布时间】:2021-03-16 07:31:37
【问题描述】:

我希望能够处理 401 并以 Angular 8 显示特定页面,但目前仅显示 index.html 文件

注意事项

  1. Angular 是 Spring Boot 的视图,因此它不是一个单独的应用程序
  2. 我没有使用 Spring Security。我只是在春天使用过滤器来确定是否要授权

这是我的过滤器。

@Component
public class CustomSessionFilter extends OncePerRequestFilter {
       protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {

        HttpServletRequest req = (HttpServletRequest) httpServletRequest;
        if (!req.getRequestURI().startsWith("/sample/path")){
                HttpServletResponse httpResponse = (HttpServletResponse) httpServletResponse;
                httpResponse.setContentType("application/json");
                httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
                return;
            }
}

也许与我有一个扩展 ErrorController 的控制器有关

@CrossOrigin
@RestController
public class IndexController implements ErrorController {

    private static final String PATH = "/error";

    @RequestMapping(value = PATH)
    public ModelAndView saveLeadQuery() {
        return new ModelAndView("forward:/");
    }

    @Override
    public String getErrorPath() {
        return PATH;
    }
}

编辑:我没有使用 Spring Security,因为我不需要登录我只需要通过特定路径并进行一些身份验证.. 并且该应用程序没有用户

【问题讨论】:

    标签: java angular spring spring-boot


    【解决方案1】:

    我只是想把我的 0.02 美元放在这里。 为了保护应用程序中的路由,您可以创建一个扩展 WebSecurityConfigurerAdapter 的安全配置,您可以在其中通过 antMatchers 或 mvcMathchers 保护某些路由(推荐使用第二种方法)。此外,您可以在此处声明一组角色或条件(通过 Spring 表达式语言),如果没有访问权限的用户尝试访问路由,这些角色或条件将自动抛出 401 错误。 更多相关信息,您可以在这里找到https://www.baeldung.com/security-spring

    对于 ErrorController,我相信控制器建议会更适合这个用例。它几乎可以拦截您声明的所有错误,并可以返回更多信息和通用响应:) 更多关于https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc

    作为

    【讨论】:

    • 我没有使用 Spring Security,因为我不需要登录,我只需要通过特定路径并进行一些身份验证.. 并且应用程序没有用户,因此不需要设置角色。目前要去 /index.. 似乎我的角度拦截器不再被调用。使用 ControllerAdvice 会检查出来。谢谢!
    猜你喜欢
    • 2023-03-29
    • 2018-08-09
    • 2019-05-17
    • 2018-02-14
    • 2020-08-06
    • 1970-01-01
    • 1970-01-01
    • 2014-06-27
    • 2020-05-18
    相关资源
    最近更新 更多