Я интегрировал keycloak с угловым приложением. В принципе, оба интерфейса и бэкэнд находятся на разных серверах. Приложение для приложения работает на apache tomcat. 8. Приложение Frontend работает в папке с приветственным содержимым JBoss.
Угловая конфигурация
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.
Фильтр Корса на бэкэнд
@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() {
}
}