javascript - AngularJS 身份验证与 Spring Security CORS 问题

标签 javascript java angularjs spring spring-mvc

我正在使用 https://spring.io/guides/tutorials/spring-security-and-angular-js 上的教程将 AngularJS 应用程序连接到 Spring Security 后端以进行身份​​验证。

当我尝试登录时(用户名和密码已经存在于后端),我在浏览器控制台中收到以下错误(我在 Chrome、Firefox 和 IE 中测试我的应用程序,它们都给我同样的错误) .

错误是:

 XMLHttpRequest cannot load http://SERVER_URL:4444/test/user. 
Response to preflight request doesn't pass access control 

        check: No 'Access-Control-Allow-Origin' header is present on the requested resource. 

         Origin 'http://localhost:3000' is therefore not allowed access. 
            The response had HTTP status code 401.

代码:

var auth = angular.module("Admin");

authService.service("AuthService", function($http, $rootScope){

    this.login = function(credentials){
        var headers = credentials ? {authorization: "Basic " + btoa(credentials.username + ":" + credentials.password)} : {};

        $http.get("http://SERVER_URL:4444/test/user",{headers:headers})
            .then(function(response){
                console.log("success");
                $rootScope.authenticated = true;
        }, function(){
                console.log("failed");
                $rootScope.authenticated = false;
            });


    };




});

当我在浏览器中访问同一个链接时,我会看到一个验证框,然后我输入用户名和密码,然后我就可以看到结果了。但是我不明白为什么我不能通过 $http() 成功访问相同的链接。

正确的做法是什么?我已经阅读了很多帖子和问答,但没有一个能解决问题。我只是不明白发生了什么。

最佳答案

您需要在后端的 Spring Security 配置中注册一个 CORS 过滤器,以允许 Angular 应用程序的来源访问后端,因为它正在发出跨域请求(它不是来自同一主机和端口) :

@Configuration
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

  @Bean
  public CorsFilter corsFilter() {
    final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
    final CorsConfiguration corsConfiguration = new CorsConfiguration();
    corsConfiguration.setAllowCredentials(true);
    corsConfiguration.addAllowedOrigin("*");
    corsConfiguration.addAllowedHeader("*");
    corsConfiguration.addAllowedMethod("*");
    urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
    return new CorsFilter(urlBasedCorsConfigurationSource);
  }

}

或者,如果您使用不支持 CorsConfiguration 的旧版本 Spring Security,您可以通过实现自定义过滤器并将其注入(inject)您的过滤器链来完成同样的事情:

@Component
public class CorsFilter implements Filter {

  public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    HttpServletResponse response = (HttpServletResponse) res;
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "*");
    response.setHeader("Access-Control-Allow-Headers", "*");
    chain.doFilter(req, res);
  }

  public void init(FilterConfig filterConfig) {}

  public void destroy() {}

}

关于javascript - AngularJS 身份验证与 Spring Security CORS 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38122070/

相关文章:

javascript - 使用功能文件更新 JSON 元素

java - 使用 build-helper-maven-plugin 从 Jar 中排除文件

java - 如何扩展 OHLCItem 类并在 OHLCSeries 中使用它

javascript - Angular Js 中的自动填充表单

angularjs - Angular 混合错误 : Trying to get the AngularJS injector before it being set

javascript - 如何在Next js上将数据从express服务器发送到客户端?

javascript - 使用 Zoomooz 放大特定的 div

javascript - 如何通过变量将数据插入MySQL数据库?

java - 未找到二传手/字段

javascript - 了解使用 JS Angular + HTML 进行导航的语法(ng-click ="save(userForm)".....)