当前位置: 首页 > 知识库问答 >
问题:

用于angular js前端http 401的Spring 5 Cors和Csrf集成[副本]

太叔灿
2023-03-14

我试图执行从angular js前端到spring boot中间件(spring boot 2.1.4)的请求。在我将应用程序迁移到spring Boot之前,设置一直按预期工作。

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private CustomAuthenticationProvider customAuthenticationProvider;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.authenticationProvider(customAuthenticationProvider);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.httpBasic().and().authorizeRequests().antMatchers("/**").hasAnyRole("ROLE_USER").anyRequest()
                .authenticated().and().csrf().csrfTokenRepository(csrfTokenRepository());
    }

    private CsrfTokenRepository csrfTokenRepository() {
        CustomDomainCookieCsrfTokenRepository repository = new CustomDomainCookieCsrfTokenRepository();
        repository.setCookieHttpOnly(false);
        return repository;
    }

}
@WebFilter("/*")
public class ForceCORSFilter extends OncePerRequestFilter {

    protected final Logger log = Logger.getLogger(this.getClass());
    private CacheService cacheService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        try {
            List<String> originList = getCacheService().getValidOriginUrI();
            String clientOrigin = request.getHeader("origin");
            if (clientOrigin == null) {
                // process the request even if origin is null
                processValidRequest(request, response, filterChain, clientOrigin);
            }
            if (clientOrigin != null) {
                // Origin should be validated if not null
                if (originList.contains(clientOrigin)) {
                    processValidRequest(request, response, filterChain, clientOrigin);
                } else {
                    log.info("####################### ORIGIN IS INVALID #######################" + clientOrigin);
                    filterChain.doFilter(request, response);
                }
            }
        } catch (Exception e) {
            response.getWriter()
                    .write("An error has occured while processing the request. Please retry with proper request.");
            log.info("An error has occured in the request " + e.getMessage());
        }
    }

    private void processValidRequest(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain,
            String clientOriginAllowed) throws IOException, ServletException {
        response.addHeader("Access-Control-Allow-Origin", clientOriginAllowed);
        response.addHeader("Access-Control-Allow-Credentials", "true");
        if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getMethod())) {
            response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, HEAD");
            response.addHeader("Access-Control-Allow-Headers",
                    "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers,Authorization, X-XSRF-TOKEN");
        } else {
            filterChain.doFilter(request, response);
        }
    }

    public CacheService getCacheService() {
        return cacheService;
    }

    public void setCacheService(CacheService cacheService) {
        this.cacheService = cacheService;
    }

}

http 401“请求的资源上没有'Access-Control-Allow-Origin'标头”错误。

共有1个答案

王辉
2023-03-14

一个问题可能是优先级--筛选器没有按照正确的顺序运行。您可以使用@order(ordered.highest_preasence),这样它就可以在Spring Security过滤器之前运行。

话虽如此,Spring已经对CORS提供了一流的支持,因此根本不需要繁琐地定义过滤器。请参见文档和示例。

 类似资料:
  • 我需要将angular前端与spring boot后端(REST API)与SAML 2.0集成,我的身份提供者是KeyClope。 我已经使用SAML2 js库与前端集成,现在我如何使用成功登录前端后收到的saml断言来保护后端spring rest API。我能在前面看到的是nameID和session index。如果有人使用SAML集成来保护spring后端rest API,请告诉我有关这

  • 问题内容: 是否存在一个良好的文件上传器,并且具有良好的AngularJS集成(指令)? 我正在寻找易于样式设置并支持HTML5拖放等功能的东西。 有人可能会说,使用现有的上载器并将其集成到AngularJS中很容易-我会说:如果这很容易,那么有人应该已经做到了。 问题答案: 实际上,我曾经滚动过自己的上载器……但仅是因为我不喜欢任何已经制成的JQuery上载器。不幸的是,这是专有的,我无法在互联

  • 我使用的是Spring 4.3.12。发行版AngularJS 1.4.8。我正试图阻止对应用程序的CSRF攻击。 下面是我的角服务代码 我仍然无法看到CSRF令牌标头和请求。 statelessCSRFFilter.java

  • 问题内容: 我有一个角度应用程序,其中包含一个从示例中获取的保存按钮: 这对于客户端验证非常有用,因为当用户解决问题时它会变为false,但是我有一个电子邮件字段,如果另一个用户使用相同的电子邮件注册,则该字段设置为无效。 一旦我将电子邮件字段设置为无效,就无法提交表单,并且用户无法修复该验证错误。所以现在我不能再使用来禁用我的提交按钮。 肯定有更好的办法 问题答案: 我在几个项目中都需要这样做,

  • 我正在尝试将Hibernate 5与Spring MVC 4应用程序集成,以“Spring in Action”书籍为例,但出了问题。 这是代码的简化版本: 网络配置 RootConfig WebAppInitializer 索引控制器 保存控制器 Dao公司 消息 例外 那么,我做错了什么?

  • 我正在寻找一些关于使用webpack的帮助,用于一个大型AngularJS应用程序。我们使用基于特性的文件夹结构(每个特性/页面都有一个模块,它们有控制器、指令)。我已经成功地配置了webpack,使其能够与Grunt一起工作,生成一个包。我想创建块,因为它将是一个大的应用程序,我们想要加载模块(页面/特征)工件异步。 我将通过一些webpack示例使用语法使用。然而,我不能得到块懒惰加载。首先,