Keycloak angular 不存在“Access-Control-Allow-Origin"标头 [英] Keycloak angular No 'Access-Control-Allow-Origin' header is present

查看:30
本文介绍了Keycloak angular 不存在“Access-Control-Allow-Origin"标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已将 keycloak 与 angular 应用程序集成在一起.基本上,前端和后端都在不同的服务器上.后端应用程序在 apache tomcat 8 上运行.前端应用程序在 JBoss 欢迎内容文件夹上运行.

I Have integrated keycloak with an angular app. Basically, both frontend and backend are on different server.Backend app is running on apache tomcat 8. Frontend app is running on JBoss welcome content folder.

角度配置

angular.element(document).ready(function ($http) {
    var keycloakAuth = new Keycloak('keycloak.json');
    auth.loggedIn = false;
    keycloakAuth.init({ onLoad: 'login-required' }).success(function () {
        keycloakAuth.loadUserInfo().success(function (userInfo) {
            console.log(userInfo);  
        });
        auth.loggedIn = true;
        auth.authz = keycloakAuth;
        auth.logoutUrl = keycloakAuth.authServerUrl + "/realms/app1/protocol/openid-connect/logout?redirect_uri=http://35.154.214.8/hrms-keycloak/index.html";
        module.factory('Auth', function() {
            return auth;
        });
        angular.bootstrap(document, ["themesApp"]);
    }).error(function () {
            window.location.reload();
        });

});
module.factory('authInterceptor', function($q, Auth) {
    return {
        request: function (config) {
            var deferred = $q.defer();
            if (Auth.authz.token) {
                Auth.authz.updateToken(5).success(function() {
                    config.headers = config.headers || {};
                    config.headers.Authorization = 'Bearer ' + Auth.authz.token;
                    deferred.resolve(config);
                }).error(function() {
                        deferred.reject('Failed to refresh token');
                    });
            }
            return deferred.promise;
        }
    };
});
module.config(["$httpProvider", function ($httpProvider)  {
    $httpProvider.interceptors.push('authInterceptor');
}]);

请求标头

Accept:*/*
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:authorization
Access-Control-Request-Method:GET
Connection:keep-alive
Host:35.154.214.8:8080
Origin:http://35.154.214.8
Referer:http://35.154.214.8/accounts-keycloak/
User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36

网络控制台出错.

XMLHttpRequest cannot load http://35.154.214.8:8080/company/loadCurrencyList. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://35.154.214.8' is therefore not allowed access.

后端的 Cors 过滤器

@Component
public class CORSFilter implements Filter {
    static Logger logger = LoggerFactory.getLogger(CORSFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, 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-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "*");
        chain.doFilter(request, response);
    }

    public void destroy() {
    }
}

推荐答案

我与 KeyCloak 和 CORS 以及所有这一切斗争了大约两周,这是我的解决方案(针对 keycloak 3.2.1):

I was fighting with KeyCloak and CORS and all of this for about two weeks, and this is my solution (for keycloak 3.2.1):

这完全是关于配置 KeyCloak 服务器.看来,您领域的 WebOrigin 需要

Its all about configuring KeyCloak server. It seems to be, that WebOrigin of your Realm needs to be

*

只有一个来源*".

就是这样,我需要什么.

Thats all, what was needed for me.

如果您将服务器输入为 WebOrigin,麻烦就来了.当您在 JavaScript 中调用 keycloak.init 时,keycloak 不会生成 CORS 标头,因此您必须手动配置它们,并且一旦这样做,并在成功初始化后调用 keycloak.getUserInfo - 您将获得双 CORS 标头,这不是允许.

If you enter your server as WebOrigin, the trouble begins. When you call keycloak.init in JavaScript, keycloak does not generate CORS headers, so you have to configure them manually, and as soon as you do so, and call keycloak.getUserInfo after successful init - you get double CORS headers, which is not allowed.

在 keycloak 邮件列表的深处有说明,您需要在 keycloak.json 中设置 enable-cors=true,但在 keycloak.gitbooks.io 上没有任何相关内容.所以这似乎不是真的.

Somewhere deep inside of keycloak mailing lists is stated, that you need to set enable-cors=true in your keycloak.json, but there is nothing about that on keycloak.gitbooks.io. So it seems not to be true.

他们在描述 JavaScript 和 Node.Js 适配器时也没有提到 CORS,我不知道为什么,似乎根本不重要.

They also don't mention CORS when describing JavaScript and Node.Js adapters, and I don't know why, seems not to be important at all.

您似乎也不应该使用 WildFly 配置来提供 CORS 标头.

It also seems to be, that you should not touch WildFly configuration to provide CORS headers.

此外,OIDC 中的 CORS 是一个特殊的 KeyCloak 功能(而不是错误).

Besides, CORS in OIDC is a special KeyCloak feature (and not a bug).

希望这个答案对您有用.

Hopefully this answer serves you well.

这篇关于Keycloak angular 不存在“Access-Control-Allow-Origin"标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆