Keycloak

Форк
0
/
keycloak-authz.js 
221 строка · 8.2 Кб
1
/*
2
 *  Copyright 2016 Red Hat, Inc. and/or its affiliates
3
 *  and other contributors as indicated by the @author tags.
4
 *
5
 *  Licensed under the Apache License, Version 2.0 (the "License");
6
 *  you may not use this file except in compliance with the License.
7
 *  You may obtain a copy of the License at
8
 *
9
 *  http://www.apache.org/licenses/LICENSE-2.0
10
 *
11
 *  Unless required by applicable law or agreed to in writing, software
12
 *  distributed under the License is distributed on an "AS IS" BASIS,
13
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
 *  See the License for the specific language governing permissions and
15
 *  limitations under the License.
16
 *
17
 */
18

19
var KeycloakAuthorization = function (keycloak, options) {
20
    var _instance = this;
21
    this.rpt = null;
22

23
    var resolve = function () {};
24
    var reject = function () {};
25

26
    // detects if browser supports promises
27
    if (typeof Promise !== "undefined" && Promise.toString().indexOf("[native code]") !== -1) {
28
        this.ready = new Promise(function (res, rej) {
29
            resolve = res;
30
            reject = rej;
31
        });
32
    }
33

34
    this.init = function () {
35
        var request = new XMLHttpRequest();
36

37
        request.open('GET', keycloak.authServerUrl + '/realms/' + keycloak.realm + '/.well-known/uma2-configuration');
38
        request.onreadystatechange = function () {
39
            if (request.readyState == 4) {
40
                if (request.status == 200) {
41
                    _instance.config = JSON.parse(request.responseText);
42
                    resolve();
43
                } else {
44
                    console.error('Could not obtain configuration from server.');
45
                    reject();
46
                }
47
            }
48
        }
49

50
        request.send(null);
51
    };
52

53
    /**
54
     * This method enables client applications to better integrate with resource servers protected by a Keycloak
55
     * policy enforcer using UMA protocol.
56
     *
57
     * The authorization request must be provided with a ticket.
58
     */
59
    this.authorize = function (authorizationRequest) {
60
        this.then = function (onGrant, onDeny, onError) {
61
            if (authorizationRequest && authorizationRequest.ticket) {
62
                var request = new XMLHttpRequest();
63

64
                request.open('POST', _instance.config.token_endpoint, true);
65
                request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
66
                request.setRequestHeader('Authorization', 'Bearer ' + keycloak.token);
67

68
                request.onreadystatechange = function () {
69
                    if (request.readyState == 4) {
70
                        var status = request.status;
71

72
                        if (status >= 200 && status < 300) {
73
                            var rpt = JSON.parse(request.responseText).access_token;
74
                            _instance.rpt = rpt;
75
                            onGrant(rpt);
76
                        } else if (status == 403) {
77
                            if (onDeny) {
78
                                onDeny();
79
                            } else {
80
                                console.error('Authorization request was denied by the server.');
81
                            }
82
                        } else {
83
                            if (onError) {
84
                                onError();
85
                            } else {
86
                                console.error('Could not obtain authorization data from server.');
87
                            }
88
                        }
89
                    }
90
                };
91

92
                var params = "grant_type=urn:ietf:params:oauth:grant-type:uma-ticket&client_id=" + keycloak.clientId + "&ticket=" + authorizationRequest.ticket;
93

94
                if (authorizationRequest.submitRequest != undefined) {
95
                    params += "&submit_request=" + authorizationRequest.submitRequest;
96
                }
97

98
                var metadata = authorizationRequest.metadata;
99

100
                if (metadata) {
101
                    if (metadata.responseIncludeResourceName) {
102
                        params += "&response_include_resource_name=" + metadata.responseIncludeResourceName;
103
                    }
104
                    if (metadata.responsePermissionsLimit) {
105
                        params += "&response_permissions_limit=" + metadata.responsePermissionsLimit;
106
                    }
107
                }
108

109
                if (_instance.rpt && (authorizationRequest.incrementalAuthorization == undefined || authorizationRequest.incrementalAuthorization)) {
110
                    params += "&rpt=" + _instance.rpt;
111
                }
112

113
                request.send(params);
114
            }
115
        };
116

117
        return this;
118
    };
119

120
    /**
121
     * Obtains all entitlements from a Keycloak Server based on a given resourceServerId.
122
     */
123
    this.entitlement = function (resourceServerId, authorizationRequest) {
124
        this.then = function (onGrant, onDeny, onError) {
125
            var request = new XMLHttpRequest();
126

127
            request.open('POST', _instance.config.token_endpoint, true);
128
            request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
129
            request.setRequestHeader('Authorization', 'Bearer ' + keycloak.token);
130

131
            request.onreadystatechange = function () {
132
                if (request.readyState == 4) {
133
                    var status = request.status;
134

135
                    if (status >= 200 && status < 300) {
136
                        var rpt = JSON.parse(request.responseText).access_token;
137
                        _instance.rpt = rpt;
138
                        onGrant(rpt);
139
                    } else if (status == 403) {
140
                        if (onDeny) {
141
                            onDeny();
142
                        } else {
143
                            console.error('Authorization request was denied by the server.');
144
                        }
145
                    } else {
146
                        if (onError) {
147
                            onError();
148
                        } else {
149
                            console.error('Could not obtain authorization data from server.');
150
                        }
151
                    }
152
                }
153
            };
154

155
            if (!authorizationRequest) {
156
                authorizationRequest = {};
157
            }
158

159
            var params = "grant_type=urn:ietf:params:oauth:grant-type:uma-ticket&client_id=" + keycloak.clientId;
160

161
            if (authorizationRequest.claimToken) {
162
                params += "&claim_token=" + authorizationRequest.claimToken;
163

164
                if (authorizationRequest.claimTokenFormat) {
165
                    params += "&claim_token_format=" + authorizationRequest.claimTokenFormat;
166
                }
167
            }
168

169
            params += "&audience=" + resourceServerId;
170

171
            var permissions = authorizationRequest.permissions;
172

173
            if (!permissions) {
174
                permissions = [];
175
            }
176

177
            for (var i = 0; i < permissions.length; i++) {
178
                var resource = permissions[i];
179
                var permission = resource.id;
180

181
                if (resource.scopes && resource.scopes.length > 0) {
182
                    permission += "#";
183
                    for (var j = 0; j < resource.scopes.length; j++) {
184
                        var scope = resource.scopes[j];
185
                        if (permission.indexOf('#') != permission.length - 1) {
186
                            permission += ",";
187
                        }
188
                        permission += scope;
189
                    }
190
                }
191

192
                params += "&permission=" + permission;
193
            }
194

195
            var metadata = authorizationRequest.metadata;
196

197
            if (metadata) {
198
                if (metadata.responseIncludeResourceName) {
199
                    params += "&response_include_resource_name=" + metadata.responseIncludeResourceName;
200
                }
201
                if (metadata.responsePermissionsLimit) {
202
                    params += "&response_permissions_limit=" + metadata.responsePermissionsLimit;
203
                }
204
            }
205

206
            if (_instance.rpt) {
207
                params += "&rpt=" + _instance.rpt;
208
            }
209

210
            request.send(params);
211
        };
212

213
        return this;
214
    };
215

216
    this.init(this);
217

218
    return this;
219
};
220

221
export default KeycloakAuthorization;
222

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.