[keycloak-user] How to configure KeycloakAuthorization on Angular2 Application

Carlos Feria carlosthe19916 at gmail.com
Fri Nov 11 08:12:15 EST 2016


Hi all, good morning. I am coding an Angular2 application and I need to
implement Authorization like this example on Keycloak
https://github.com/keycloak/keycloak/tree/master/examples/authz/photoz,
there are another example that indicates how to use Keycloak on Angular2
applications (
https://github.com/keycloak/keycloak/tree/master/examples/demo-template/angular2-product-app
)

My real problem is how to write responseError on Angular2? Have you ever
had this kind of problem?

This is the code(red code) that i want to pass to Angular2....please help
me.

module.factory('authInterceptor', function ($q, $injector, $timeout,
Identity) { return {
request: function (request) {
document.getElementById("output").innerHTML = '';
if (Identity.authorization && Identity.authorization.rpt && request.url.
indexOf('/authorize') == -1) {
retries = 0;
request.headers.Authorization = 'Bearer ' + Identity.authorization.rpt;
} else {
request.headers.Authorization = 'Bearer ' + Identity.authc.token;
}
return request;
},
responseError: function (rejection) {
var status = rejection.status;
if (status == 403 || status == 401) {
var retry = (!rejection.config.retry || rejection.config.retry < 1);
if (!retry) {
document.getElementById("output").innerHTML = 'You can not access or
perform the requested operation on this resource.';
return $q.reject(rejection);
}
if (rejection.config.url.indexOf('/authorize') == -1 && retry) {
var deferred = $q.defer();
// here is the authorization logic, which tries to obtain an authorization
token from the server in case the resource server
// returns a 403 or 401.
*Identity.authorization.authorize(rejection.headers('WWW-Authenticate')).then(function
(rpt) {*
* deferred.resolve(rejection);*
* }, function () {*
* document.getElementById("output").innerHTML = 'You can not access or
perform the requested operation on this resource.';*
* }, function () {*
* document.getElementById("output").innerHTML = 'Unexpected error from
server.';*
* });*
var promise = deferred.promise;
return promise.then(function (res) {
if (!res.config.retry) {
res.config.retry = 1;
} else {
res.config.retry++;
}
var $http = $injector.get("$http");
return $http(res.config).then(function (response) {
return response;
});
});
}
}
return $q.reject(rejection);
}
};
-- 
Carlos E. Feria Vila


More information about the keycloak-user mailing list