@celljs/oauth2-client 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (249) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1 -0
  3. package/cell.yml +57 -0
  4. package/lib/node/authentication/authentication-protocol.d.ts +25 -0
  5. package/lib/node/authentication/authentication-protocol.d.ts.map +1 -0
  6. package/lib/node/authentication/authentication-protocol.js +11 -0
  7. package/lib/node/authentication/authentication-protocol.js.map +1 -0
  8. package/lib/node/authentication/index.d.ts +4 -0
  9. package/lib/node/authentication/index.d.ts.map +1 -0
  10. package/lib/node/authentication/index.js +20 -0
  11. package/lib/node/authentication/index.js.map +1 -0
  12. package/lib/node/authentication/oauth2-authentication-provider.d.ts +30 -0
  13. package/lib/node/authentication/oauth2-authentication-provider.d.ts.map +1 -0
  14. package/lib/node/authentication/oauth2-authentication-provider.js +170 -0
  15. package/lib/node/authentication/oauth2-authentication-provider.js.map +1 -0
  16. package/lib/node/authentication/oidc-authentication-provider.d.ts +18 -0
  17. package/lib/node/authentication/oidc-authentication-provider.d.ts.map +1 -0
  18. package/lib/node/authentication/oidc-authentication-provider.js +74 -0
  19. package/lib/node/authentication/oidc-authentication-provider.js.map +1 -0
  20. package/lib/node/authorization/authorization-code-authorized-client-provider.d.ts +5 -0
  21. package/lib/node/authorization/authorization-code-authorized-client-provider.d.ts.map +1 -0
  22. package/lib/node/authorization/authorization-code-authorized-client-provider.js +27 -0
  23. package/lib/node/authorization/authorization-code-authorized-client-provider.js.map +1 -0
  24. package/lib/node/authorization/authorization-code-grant-middleware.d.ts +26 -0
  25. package/lib/node/authorization/authorization-code-grant-middleware.d.ts.map +1 -0
  26. package/lib/node/authorization/authorization-code-grant-middleware.js +129 -0
  27. package/lib/node/authorization/authorization-code-grant-middleware.js.map +1 -0
  28. package/lib/node/authorization/authorization-failure-handler.d.ts +10 -0
  29. package/lib/node/authorization/authorization-failure-handler.d.ts.map +1 -0
  30. package/lib/node/authorization/authorization-failure-handler.js +35 -0
  31. package/lib/node/authorization/authorization-failure-handler.js.map +1 -0
  32. package/lib/node/authorization/authorization-protocol.d.ts +78 -0
  33. package/lib/node/authorization/authorization-protocol.d.ts.map +1 -0
  34. package/lib/node/authorization/authorization-protocol.js +34 -0
  35. package/lib/node/authorization/authorization-protocol.js.map +1 -0
  36. package/lib/node/authorization/authorization-request-manager.d.ts +13 -0
  37. package/lib/node/authorization/authorization-request-manager.d.ts.map +1 -0
  38. package/lib/node/authorization/authorization-request-manager.js +64 -0
  39. package/lib/node/authorization/authorization-request-manager.js.map +1 -0
  40. package/lib/node/authorization/authorization-request-redirect-middleware.d.ts +20 -0
  41. package/lib/node/authorization/authorization-request-redirect-middleware.d.ts.map +1 -0
  42. package/lib/node/authorization/authorization-request-redirect-middleware.js +113 -0
  43. package/lib/node/authorization/authorization-request-redirect-middleware.js.map +1 -0
  44. package/lib/node/authorization/authorization-request-resolver.d.ts +38 -0
  45. package/lib/node/authorization/authorization-request-resolver.d.ts.map +1 -0
  46. package/lib/node/authorization/authorization-request-resolver.js +155 -0
  47. package/lib/node/authorization/authorization-request-resolver.js.map +1 -0
  48. package/lib/node/authorization/authorization-success-handler.d.ts +7 -0
  49. package/lib/node/authorization/authorization-success-handler.d.ts.map +1 -0
  50. package/lib/node/authorization/authorization-success-handler.js +28 -0
  51. package/lib/node/authorization/authorization-success-handler.js.map +1 -0
  52. package/lib/node/authorization/authorized-client-manager.d.ts +11 -0
  53. package/lib/node/authorization/authorized-client-manager.d.ts.map +1 -0
  54. package/lib/node/authorization/authorized-client-manager.js +48 -0
  55. package/lib/node/authorization/authorized-client-manager.js.map +1 -0
  56. package/lib/node/authorization/authorized-client-service.d.ts +12 -0
  57. package/lib/node/authorization/authorized-client-service.d.ts.map +1 -0
  58. package/lib/node/authorization/authorized-client-service.js +87 -0
  59. package/lib/node/authorization/authorized-client-service.js.map +1 -0
  60. package/lib/node/authorization/client-credentials-authorized-client-provider.d.ts +12 -0
  61. package/lib/node/authorization/client-credentials-authorized-client-provider.d.ts.map +1 -0
  62. package/lib/node/authorization/client-credentials-authorized-client-provider.js +72 -0
  63. package/lib/node/authorization/client-credentials-authorized-client-provider.js.map +1 -0
  64. package/lib/node/authorization/context-attributes-mapper.d.ts +5 -0
  65. package/lib/node/authorization/context-attributes-mapper.d.ts.map +1 -0
  66. package/lib/node/authorization/context-attributes-mapper.js +28 -0
  67. package/lib/node/authorization/context-attributes-mapper.js.map +1 -0
  68. package/lib/node/authorization/index.d.ts +14 -0
  69. package/lib/node/authorization/index.d.ts.map +1 -0
  70. package/lib/node/authorization/index.js +30 -0
  71. package/lib/node/authorization/index.js.map +1 -0
  72. package/lib/node/authorization/password-authorized-client-provider.d.ts +12 -0
  73. package/lib/node/authorization/password-authorized-client-provider.d.ts.map +1 -0
  74. package/lib/node/authorization/password-authorized-client-provider.js +85 -0
  75. package/lib/node/authorization/password-authorized-client-provider.js.map +1 -0
  76. package/lib/node/authorization/refresh-token-authorized-client-provider.d.ts +12 -0
  77. package/lib/node/authorization/refresh-token-authorized-client-provider.d.ts.map +1 -0
  78. package/lib/node/authorization/refresh-token-authorized-client-provider.js +68 -0
  79. package/lib/node/authorization/refresh-token-authorized-client-provider.js.map +1 -0
  80. package/lib/node/constants.d.ts +5 -0
  81. package/lib/node/constants.d.ts.map +1 -0
  82. package/lib/node/constants.js +8 -0
  83. package/lib/node/constants.js.map +1 -0
  84. package/lib/node/endpoint/authorization-code-token-response-client.d.ts +12 -0
  85. package/lib/node/endpoint/authorization-code-token-response-client.d.ts.map +1 -0
  86. package/lib/node/endpoint/authorization-code-token-response-client.js +83 -0
  87. package/lib/node/endpoint/authorization-code-token-response-client.js.map +1 -0
  88. package/lib/node/endpoint/client-credentials-token-response-client.d.ts +12 -0
  89. package/lib/node/endpoint/client-credentials-token-response-client.d.ts.map +1 -0
  90. package/lib/node/endpoint/client-credentials-token-response-client.js +80 -0
  91. package/lib/node/endpoint/client-credentials-token-response-client.js.map +1 -0
  92. package/lib/node/endpoint/endpoint-protocol.d.ts +48 -0
  93. package/lib/node/endpoint/endpoint-protocol.d.ts.map +1 -0
  94. package/lib/node/endpoint/endpoint-protocol.js +9 -0
  95. package/lib/node/endpoint/endpoint-protocol.js.map +1 -0
  96. package/lib/node/endpoint/index.d.ts +7 -0
  97. package/lib/node/endpoint/index.d.ts.map +1 -0
  98. package/lib/node/endpoint/index.js +23 -0
  99. package/lib/node/endpoint/index.js.map +1 -0
  100. package/lib/node/endpoint/password-token-response-client.d.ts +12 -0
  101. package/lib/node/endpoint/password-token-response-client.d.ts.map +1 -0
  102. package/lib/node/endpoint/password-token-response-client.js +82 -0
  103. package/lib/node/endpoint/password-token-response-client.js.map +1 -0
  104. package/lib/node/endpoint/refresh-token-token-response-client.d.ts +12 -0
  105. package/lib/node/endpoint/refresh-token-token-response-client.d.ts.map +1 -0
  106. package/lib/node/endpoint/refresh-token-token-response-client.js +87 -0
  107. package/lib/node/endpoint/refresh-token-token-response-client.js.map +1 -0
  108. package/lib/node/endpoint/user-response-client.d.ts +9 -0
  109. package/lib/node/endpoint/user-response-client.d.ts.map +1 -0
  110. package/lib/node/endpoint/user-response-client.js +84 -0
  111. package/lib/node/endpoint/user-response-client.js.map +1 -0
  112. package/lib/node/error/error-hander.d.ts +11 -0
  113. package/lib/node/error/error-hander.d.ts.map +1 -0
  114. package/lib/node/error/error-hander.js +52 -0
  115. package/lib/node/error/error-hander.js.map +1 -0
  116. package/lib/node/error/error-protocol.d.ts +3 -0
  117. package/lib/node/error/error-protocol.d.ts.map +1 -0
  118. package/lib/node/error/error-protocol.js +7 -0
  119. package/lib/node/error/error-protocol.js.map +1 -0
  120. package/lib/node/error/error.d.ts +10 -0
  121. package/lib/node/error/error.d.ts.map +1 -0
  122. package/lib/node/error/error.js +23 -0
  123. package/lib/node/error/error.js.map +1 -0
  124. package/lib/node/error/index.d.ts +4 -0
  125. package/lib/node/error/index.d.ts.map +1 -0
  126. package/lib/node/error/index.js +20 -0
  127. package/lib/node/error/index.js.map +1 -0
  128. package/lib/node/index.d.ts +8 -0
  129. package/lib/node/index.d.ts.map +1 -0
  130. package/lib/node/index.js +24 -0
  131. package/lib/node/index.js.map +1 -0
  132. package/lib/node/module.d.ts +4 -0
  133. package/lib/node/module.d.ts.map +1 -0
  134. package/lib/node/module.js +6 -0
  135. package/lib/node/module.js.map +1 -0
  136. package/lib/node/provider/index.d.ts +3 -0
  137. package/lib/node/provider/index.d.ts.map +1 -0
  138. package/lib/node/provider/index.js +19 -0
  139. package/lib/node/provider/index.js.map +1 -0
  140. package/lib/node/provider/provider-details-manager.d.ts +12 -0
  141. package/lib/node/provider/provider-details-manager.d.ts.map +1 -0
  142. package/lib/node/provider/provider-details-manager.js +50 -0
  143. package/lib/node/provider/provider-details-manager.js.map +1 -0
  144. package/lib/node/provider/provider-protocol.d.ts +21 -0
  145. package/lib/node/provider/provider-protocol.d.ts.map +1 -0
  146. package/lib/node/provider/provider-protocol.js +5 -0
  147. package/lib/node/provider/provider-protocol.js.map +1 -0
  148. package/lib/node/registration/id-token-jwt-decoder-facatory.d.ts +15 -0
  149. package/lib/node/registration/id-token-jwt-decoder-facatory.d.ts.map +1 -0
  150. package/lib/node/registration/id-token-jwt-decoder-facatory.js +89 -0
  151. package/lib/node/registration/id-token-jwt-decoder-facatory.js.map +1 -0
  152. package/lib/node/registration/index.d.ts +5 -0
  153. package/lib/node/registration/index.d.ts.map +1 -0
  154. package/lib/node/registration/index.js +21 -0
  155. package/lib/node/registration/index.js.map +1 -0
  156. package/lib/node/registration/jws-algorithm-resolver.d.ts +5 -0
  157. package/lib/node/registration/jws-algorithm-resolver.d.ts.map +1 -0
  158. package/lib/node/registration/jws-algorithm-resolver.js +22 -0
  159. package/lib/node/registration/jws-algorithm-resolver.js.map +1 -0
  160. package/lib/node/registration/registration-manager.d.ts +15 -0
  161. package/lib/node/registration/registration-manager.d.ts.map +1 -0
  162. package/lib/node/registration/registration-manager.js +64 -0
  163. package/lib/node/registration/registration-manager.js.map +1 -0
  164. package/lib/node/registration/registration-protocol.d.ts +22 -0
  165. package/lib/node/registration/registration-protocol.d.ts.map +1 -0
  166. package/lib/node/registration/registration-protocol.js +7 -0
  167. package/lib/node/registration/registration-protocol.js.map +1 -0
  168. package/lib/node/user/index.d.ts +4 -0
  169. package/lib/node/user/index.d.ts.map +1 -0
  170. package/lib/node/user/index.js +20 -0
  171. package/lib/node/user/index.js.map +1 -0
  172. package/lib/node/user/oauth2-user-service.d.ts +10 -0
  173. package/lib/node/user/oauth2-user-service.d.ts.map +1 -0
  174. package/lib/node/user/oauth2-user-service.js +61 -0
  175. package/lib/node/user/oauth2-user-service.js.map +1 -0
  176. package/lib/node/user/oidc-user-service.d.ts +13 -0
  177. package/lib/node/user/oidc-user-service.d.ts.map +1 -0
  178. package/lib/node/user/oidc-user-service.js +98 -0
  179. package/lib/node/user/oidc-user-service.js.map +1 -0
  180. package/lib/node/user/user-protocol.d.ts +6 -0
  181. package/lib/node/user/user-protocol.d.ts.map +1 -0
  182. package/lib/node/user/user-protocol.js +3 -0
  183. package/lib/node/user/user-protocol.js.map +1 -0
  184. package/lib/node/utils/authorization-grant-request-entity-util.d.ts +10 -0
  185. package/lib/node/utils/authorization-grant-request-entity-util.d.ts.map +1 -0
  186. package/lib/node/utils/authorization-grant-request-entity-util.js +28 -0
  187. package/lib/node/utils/authorization-grant-request-entity-util.js.map +1 -0
  188. package/lib/node/utils/authorization-response-util.d.ts +8 -0
  189. package/lib/node/utils/authorization-response-util.d.ts.map +1 -0
  190. package/lib/node/utils/authorization-response-util.js +53 -0
  191. package/lib/node/utils/authorization-response-util.js.map +1 -0
  192. package/lib/node/utils/index.d.ts +3 -0
  193. package/lib/node/utils/index.d.ts.map +1 -0
  194. package/lib/node/utils/index.js +19 -0
  195. package/lib/node/utils/index.js.map +1 -0
  196. package/lib/package.spec.d.ts +1 -0
  197. package/lib/package.spec.d.ts.map +1 -0
  198. package/lib/package.spec.js +4 -0
  199. package/lib/package.spec.js.map +1 -0
  200. package/package.json +51 -0
  201. package/src/node/authentication/authentication-protocol.ts +26 -0
  202. package/src/node/authentication/index.ts +3 -0
  203. package/src/node/authentication/oauth2-authentication-provider.ts +163 -0
  204. package/src/node/authentication/oidc-authentication-provider.ts +60 -0
  205. package/src/node/authorization/authorization-code-authorized-client-provider.ts +16 -0
  206. package/src/node/authorization/authorization-code-grant-middleware.ts +110 -0
  207. package/src/node/authorization/authorization-failure-handler.ts +23 -0
  208. package/src/node/authorization/authorization-protocol.ts +104 -0
  209. package/src/node/authorization/authorization-request-manager.ts +54 -0
  210. package/src/node/authorization/authorization-request-redirect-middleware.ts +91 -0
  211. package/src/node/authorization/authorization-request-resolver.ts +149 -0
  212. package/src/node/authorization/authorization-success-handler.ts +15 -0
  213. package/src/node/authorization/authorized-client-manager.ts +35 -0
  214. package/src/node/authorization/authorized-client-service.ts +73 -0
  215. package/src/node/authorization/client-credentials-authorized-client-provider.ts +61 -0
  216. package/src/node/authorization/context-attributes-mapper.ts +18 -0
  217. package/src/node/authorization/index.ts +13 -0
  218. package/src/node/authorization/password-authorized-client-provider.ts +78 -0
  219. package/src/node/authorization/refresh-token-authorized-client-provider.ts +58 -0
  220. package/src/node/constants.ts +4 -0
  221. package/src/node/endpoint/authorization-code-token-response-client.ts +73 -0
  222. package/src/node/endpoint/client-credentials-token-response-client.ts +69 -0
  223. package/src/node/endpoint/endpoint-protocol.ts +55 -0
  224. package/src/node/endpoint/index.ts +6 -0
  225. package/src/node/endpoint/password-token-response-client.ts +71 -0
  226. package/src/node/endpoint/refresh-token-token-response-client.ts +77 -0
  227. package/src/node/endpoint/user-response-client.ts +72 -0
  228. package/src/node/error/error-hander.ts +39 -0
  229. package/src/node/error/error-protocol.ts +6 -0
  230. package/src/node/error/error.ts +19 -0
  231. package/src/node/error/index.ts +3 -0
  232. package/src/node/index.ts +7 -0
  233. package/src/node/module.ts +4 -0
  234. package/src/node/provider/index.ts +2 -0
  235. package/src/node/provider/provider-details-manager.ts +33 -0
  236. package/src/node/provider/provider-protocol.ts +24 -0
  237. package/src/node/registration/id-token-jwt-decoder-facatory.ts +71 -0
  238. package/src/node/registration/index.ts +4 -0
  239. package/src/node/registration/jws-algorithm-resolver.ts +12 -0
  240. package/src/node/registration/registration-manager.ts +47 -0
  241. package/src/node/registration/registration-protocol.ts +27 -0
  242. package/src/node/user/index.ts +3 -0
  243. package/src/node/user/oauth2-user-service.ts +50 -0
  244. package/src/node/user/oidc-user-service.ts +92 -0
  245. package/src/node/user/user-protocol.ts +6 -0
  246. package/src/node/utils/authorization-grant-request-entity-util.ts +26 -0
  247. package/src/node/utils/authorization-response-util.ts +50 -0
  248. package/src/node/utils/index.ts +2 -0
  249. package/src/package.spec.ts +4 -0
@@ -0,0 +1,110 @@
1
+ import { Middleware, Context, RedirectStrategy, RequestMatcher } from '@celljs/web/lib/node';
2
+ import { Component, Value, Autowired } from '@celljs/core';
3
+ import { AuthorizationRequestResolver, AuthorizationRequestManager, AUTHORIZATION_CODE_GRANT_MIDDLEWARE_PRIORITY,
4
+ AuthorizedClientManager, AuthorizedClient, INVALID_STATE_PARAMETER_ERROR_CODE } from './authorization-protocol';
5
+ import { AuthorizationRequest, OAuth2ParameterNames, OAuth2AuthorizationError, OAuth2Error } from '@celljs/oauth2-core';
6
+ import { AuthorizationResponseUtil } from '../utils';
7
+ import { ClientRegistrationManager, ClientRegistration } from '../registration';
8
+ import { ENDPOINT, PathResolver } from '@celljs/web';
9
+ import { SecurityContext, RequestCache } from '@celljs/security/lib/node';
10
+ import { AuthorizationCodeTokenResponseClient } from '../endpoint';
11
+ import { AUTHORIZATION_CODE_GRANT_URI, REDIRECT_LOGIN_PATH } from '../constants';
12
+
13
+ @Component(Middleware)
14
+ export class AuthorizationCodeGrantMiddleware implements Middleware {
15
+
16
+ @Autowired(AuthorizationRequestManager)
17
+ protected readonly authorizationRequestManager: AuthorizationRequestManager<AuthorizationRequest>;
18
+
19
+ @Autowired(AuthorizationRequestResolver)
20
+ protected readonly authorizationRequestResolver: AuthorizationRequestResolver;
21
+
22
+ @Autowired(ClientRegistrationManager)
23
+ protected readonly clientRegistrationManager: ClientRegistrationManager;
24
+
25
+ @Autowired(AuthorizedClientManager)
26
+ protected readonly authorizedClientManager: AuthorizedClientManager<AuthorizedClient>;
27
+
28
+ @Autowired(RedirectStrategy)
29
+ protected readonly redirectStrategy: RedirectStrategy;
30
+
31
+ @Autowired(RequestMatcher)
32
+ protected readonly requestMatcher: RequestMatcher;
33
+
34
+ @Autowired(PathResolver)
35
+ protected readonly pathResolver: PathResolver;
36
+
37
+ @Autowired(RequestCache)
38
+ protected readonly requestCache: RequestCache;
39
+
40
+ @Autowired(AuthorizationCodeTokenResponseClient)
41
+ protected readonly authorizationCodeTokenResponseClient: AuthorizationCodeTokenResponseClient;
42
+
43
+ @Value(ENDPOINT)
44
+ protected readonly endpoint: string;
45
+
46
+ @Value(REDIRECT_LOGIN_PATH)
47
+ protected readonly redirectLoginPath: string;
48
+
49
+ @Value(AUTHORIZATION_CODE_GRANT_URI)
50
+ protected readonly authorizationCodeGrantUri: string;
51
+
52
+ async handle(ctx: Context, next: () => Promise<void>): Promise<void> {
53
+ if (await this.matchesAuthorizationResponse()) {
54
+ await this.processAuthorizationResponse();
55
+ }
56
+ await next();
57
+
58
+ }
59
+
60
+ async processAuthorizationResponse() {
61
+ const authorizationRequest = <AuthorizationRequest>await this.authorizationRequestManager.remove();
62
+ const registrationId = authorizationRequest.attributes[OAuth2ParameterNames.REGISTRATION_ID];
63
+ const clientRegistration = <ClientRegistration> await this.clientRegistrationManager.get(registrationId!);
64
+ const redirectUri = await this.pathResolver.resolve(this.endpoint, Context.getRequest().path);
65
+ const authorizationResponse = AuthorizationResponseUtil.convert(redirectUri);
66
+ if (authorizationResponse.error) {
67
+ throw new OAuth2AuthorizationError(authorizationResponse.error);
68
+ }
69
+ if (authorizationResponse.state !== authorizationRequest.state) {
70
+ throw new OAuth2AuthorizationError(<OAuth2Error>{
71
+ errorCode: INVALID_STATE_PARAMETER_ERROR_CODE
72
+ });
73
+ }
74
+ const tokenResponse = await this.authorizationCodeTokenResponseClient.getTokenResponse({
75
+ authorizationGrantType: clientRegistration.authorizationGrantType,
76
+ clientRegistration,
77
+ authorizationExchange: {
78
+ authorizationRequest, authorizationResponse
79
+ }
80
+ });
81
+
82
+ const authentication = SecurityContext.getAuthentication();
83
+ const principalName = authentication.name;
84
+ await this.authorizedClientManager.save(<AuthorizedClient>{
85
+ clientRegistration,
86
+ principalName,
87
+ accessToken: tokenResponse.accessToken,
88
+ refreshToken: tokenResponse.refreshToken
89
+ }, principalName);
90
+ const savedRequest = await this.requestCache.get();
91
+ await this.redirectStrategy.send(savedRequest?.redirectUrl || authorizationRequest.redirectUri);
92
+ }
93
+
94
+ protected async matchesAuthorizationResponse() {
95
+ const authorizationMatch = this.authorizationCodeGrantUri && await this.requestMatcher.match(
96
+ await this.pathResolver.resolve(this.authorizationCodeGrantUri)
97
+ );
98
+ if (!AuthorizationResponseUtil.isAuthorizationResponse() || !authorizationMatch) {
99
+ return false;
100
+ }
101
+ const authorizationRequest = await this.authorizationRequestManager.get();
102
+ if (!authorizationRequest) {
103
+ return false;
104
+ }
105
+ return !await this.requestMatcher.match(await this.pathResolver.resolve(this.redirectLoginPath));
106
+ }
107
+
108
+ readonly priority: number = AUTHORIZATION_CODE_GRANT_MIDDLEWARE_PRIORITY;
109
+
110
+ }
@@ -0,0 +1,23 @@
1
+ import { AuthorizationSuccessHandler, AuthorizedClient, AuthorizedClientManager, AuthorizationFailureHandler } from './authorization-protocol';
2
+ import { Authentication } from '@celljs/security/lib/node';
3
+ import { Component, Autowired } from '@celljs/core';
4
+ import { OAuth2AuthorizationError, OAuth2ErrorCodes } from '@celljs/oauth2-core';
5
+ import { ClientAuthorizationError } from '../error';
6
+
7
+ @Component(AuthorizationSuccessHandler)
8
+ export class DefaultAuthorizationFailureHandler implements AuthorizationFailureHandler {
9
+
10
+ @Autowired(AuthorizedClientManager)
11
+ protected readonly authorizedClientManager: AuthorizedClientManager<AuthorizedClient>;
12
+
13
+ async onAuthorizationFailure(oauth2AuthorizationError: OAuth2AuthorizationError, principal: Authentication): Promise<void> {
14
+ if (oauth2AuthorizationError instanceof ClientAuthorizationError && this.hasRemovalErrorCode(oauth2AuthorizationError)) {
15
+ await this.authorizedClientManager.remove(oauth2AuthorizationError.clientRegistrationId, principal.name);
16
+ }
17
+ }
18
+
19
+ protected hasRemovalErrorCode(oauth2AuthorizationError: ClientAuthorizationError) {
20
+ return [ OAuth2ErrorCodes.INVALID_TOKEN, OAuth2ErrorCodes.INVALID_GRANT ].findIndex( code => code === oauth2AuthorizationError.oauth2Error.errorCode);
21
+ }
22
+
23
+ }
@@ -0,0 +1,104 @@
1
+ import { AuthorizationRequest, AccessToken, RefreshToken, OAuth2AuthorizationError } from '@celljs/oauth2-core';
2
+ import { ClientRegistration } from '../registration';
3
+ import { Authentication, AUTHENTICATION_MIDDLE_PRIORITY } from '@celljs/security/lib/node';
4
+
5
+ export const AuthorizationRequestResolver = Symbol('AuthorizationRequestResolver');
6
+ export const AuthorizedClientManager = Symbol('AuthorizedClientManager');
7
+ export const AuthorizationRequestManager = Symbol('AuthorizationRequestManager');
8
+ export const AuthorizedClientService = Symbol('AuthorizedClientService');
9
+ export const AuthorizedClientProvider = Symbol('AuthorizedClientProvider');
10
+ export const ContextAttributesMapper = Symbol('ContextAttributesMapper');
11
+ export const AuthorizationSuccessHandler = Symbol('AuthorizationSuccessHandler');
12
+ export const AuthorizationFailureHandler = Symbol('AuthorizationFailureHandler');
13
+
14
+ export const AUTHORIZATION_REQUEST_REDIRECT_MIDDLEWARE_PRIORITY = AUTHENTICATION_MIDDLE_PRIORITY + 50;
15
+ export const AUTHORIZATION_CODE_GRANT_MIDDLEWARE_PRIORITY = AUTHENTICATION_MIDDLE_PRIORITY - 100;
16
+ export const INVALID_STATE_PARAMETER_ERROR_CODE = 'invalid_state_parameter';
17
+
18
+ export interface AuthorizationRequestResolver {
19
+
20
+ resolve(clientRegistrationId?: string): Promise<AuthorizationRequest | undefined>;
21
+
22
+ }
23
+
24
+ export interface AuthorizedClient {
25
+ clientRegistration: ClientRegistration;
26
+ principalName: string;
27
+ accessToken: AccessToken;
28
+ refreshToken?: RefreshToken;
29
+ }
30
+
31
+ export interface AuthorizedClientManager<T extends AuthorizedClient> {
32
+
33
+ get(clientRegistrationId: string, principalName: string): Promise<T | undefined>;
34
+
35
+ save(authorizedClient: T, principalName: string): Promise<void>;
36
+
37
+ remove(clientRegistrationId: string, principalName: string): Promise<void>;
38
+
39
+ }
40
+
41
+ export interface AuthorizationRequestManager<T extends AuthorizationRequest> {
42
+
43
+ get(): Promise<T | undefined>;
44
+
45
+ save(authorizationRequest: T): Promise<void>;
46
+
47
+ remove(): Promise<T | undefined>;
48
+
49
+ }
50
+
51
+ export interface AuthorizeRequest {
52
+ clientRegistrationId: string;
53
+ authorizedClient: AuthorizedClient;
54
+ principal: Authentication;
55
+ attributes?: Map<string, any>;
56
+ }
57
+
58
+ export interface AuthorizedClientService {
59
+ authorize(authorizeRequest: AuthorizeRequest): Promise<AuthorizedClient | undefined>;
60
+ }
61
+
62
+ export interface AuthorizationContext {
63
+ clientRegistration: ClientRegistration;
64
+ authorizedClient?: AuthorizedClient;
65
+ principal: Authentication;
66
+ attributes: Map<string, any>;
67
+ }
68
+
69
+ export namespace AuthorizationContext {
70
+
71
+ /**
72
+ * The name of the attributes in the context associated
73
+ * to the value for the "request scope(s)".
74
+ */
75
+ export const REQUEST_SCOPE_ATTRIBUTE_NAME = 'AuthorizationContext.REQUEST_SCOPE';
76
+
77
+ /**
78
+ * The name of the attributes in the context associated
79
+ * to the value for the resource owner's username.
80
+ */
81
+ export const USERNAME_ATTRIBUTE_NAME = 'AuthorizationContext.USERNAME';
82
+
83
+ /**
84
+ * The name of the attributes in the context associated
85
+ * to the value for the resource owner's password.
86
+ */
87
+ export const PASSWORD_ATTRIBUTE_NAME = 'AuthorizationContext.PASSWORD';
88
+ }
89
+
90
+ export interface AuthorizedClientProvider {
91
+ provide(context: AuthorizationContext): Promise<AuthorizedClient | undefined>;
92
+ }
93
+
94
+ export interface ContextAttributesMapper {
95
+ apply(authorizeRequest: AuthorizeRequest): Promise<Map<string, any>>;
96
+ }
97
+
98
+ export interface AuthorizationSuccessHandler {
99
+ onAuthorizationSuccess(authorizedClient: AuthorizedClient, principal: Authentication): Promise<void>;
100
+ }
101
+
102
+ export interface AuthorizationFailureHandler {
103
+ onAuthorizationFailure(oauth2AuthorizationError: OAuth2AuthorizationError, principal: Authentication): Promise<void>;
104
+ }
@@ -0,0 +1,54 @@
1
+ import { AuthorizationRequestManager } from './authorization-protocol';
2
+ import { AuthorizationRequest, OAuth2ParameterNames } from '@celljs/oauth2-core';
3
+ import { Context } from '@celljs/web/lib/node';
4
+ import { ok } from 'assert';
5
+ import { Component } from '@celljs/core';
6
+
7
+ @Component(AuthorizationRequestManager)
8
+ export class HttpSessionAuthorizationRequestManager implements AuthorizationRequestManager<AuthorizationRequest> {
9
+
10
+ protected readonly sessionAttributeName = `${HttpSessionAuthorizationRequestManager.name}.AUTHORIZATION_REQUEST`;
11
+
12
+ async get(): Promise<AuthorizationRequest | undefined> {
13
+ const stateParameter = this.getStateParameter();
14
+ if (stateParameter) {
15
+ return this.getAuthorizationRequests()[stateParameter];
16
+ }
17
+ }
18
+
19
+ async save(authorizationRequest: AuthorizationRequest): Promise<void> {
20
+ if (authorizationRequest) {
21
+ const state = authorizationRequest.state;
22
+ ok(state, 'authorizationRequest.state cannot be empty');
23
+ const authorizationRequests = this.getAuthorizationRequests();
24
+ authorizationRequests[state] = authorizationRequest;
25
+ const session = Context.getSession();
26
+ session[this.sessionAttributeName] = authorizationRequests;
27
+ } else {
28
+ await this.remove();
29
+ }
30
+ }
31
+ async remove(): Promise<AuthorizationRequest | undefined> {
32
+ const stateParameter = this.getStateParameter();
33
+ if (stateParameter) {
34
+ const authorizationRequests = this.getAuthorizationRequests();
35
+ const originalRequest = authorizationRequests[stateParameter];
36
+ delete authorizationRequests[stateParameter];
37
+ if (!Object.keys(authorizationRequests).length) {
38
+ const session = Context.getSession();
39
+ delete session[this.sessionAttributeName];
40
+ }
41
+ return originalRequest;
42
+ }
43
+ }
44
+
45
+ protected getStateParameter(): string | undefined {
46
+ return <string>Context.getRequest().query[OAuth2ParameterNames.STATE];
47
+ }
48
+
49
+ protected getAuthorizationRequests(): { [state: string]: AuthorizationRequest } {
50
+ const session = Context.getSession();
51
+ return session[this.sessionAttributeName] || {};
52
+ }
53
+
54
+ }
@@ -0,0 +1,91 @@
1
+ import { Middleware, Context, RequestMatcher, HttpError, RedirectStrategy } from '@celljs/web/lib/node';
2
+ import { Component, Value, Autowired, Logger } from '@celljs/core';
3
+ import { AUTHORIZATION_REQUEST_BASE_URI } from '../constants';
4
+ import { AuthorizationRequestResolver, AuthorizationRequestManager, AUTHORIZATION_REQUEST_REDIRECT_MIDDLEWARE_PRIORITY } from './authorization-protocol';
5
+ import { AuthorizationGrantType, AuthorizationRequest } from '@celljs/oauth2-core';
6
+ import { HttpMethod, HttpStatus } from '@celljs/http';
7
+ import { ClientAuthorizationError } from '../error';
8
+ import { RequestCache } from '@celljs/security/lib/node';
9
+
10
+ @Component(Middleware)
11
+ export class AuthorizationRequestRedirectMiddleware implements Middleware {
12
+
13
+ @Value(AUTHORIZATION_REQUEST_BASE_URI)
14
+ protected readonly authorizationRequestBaseUri: string;
15
+
16
+ @Autowired(RequestMatcher)
17
+ protected readonly requestMatcher: RequestMatcher;
18
+
19
+ @Autowired(AuthorizationRequestManager)
20
+ protected readonly authorizationRequestManager: AuthorizationRequestManager<AuthorizationRequest>;
21
+
22
+ @Autowired(AuthorizationRequestResolver)
23
+ protected readonly authorizationRequestResolver: AuthorizationRequestResolver;
24
+
25
+ @Autowired(RedirectStrategy)
26
+ protected readonly redirectStrategy: RedirectStrategy;
27
+
28
+ @Autowired(RequestCache)
29
+ protected readonly requestCache: RequestCache;
30
+
31
+ @Value('cell.security.targetUrlParameter')
32
+ protected readonly targetUrlParameter: string;
33
+
34
+ @Autowired(Logger)
35
+ protected readonly logger: Logger;
36
+
37
+ async handle(ctx: Context, next: () => Promise<void>): Promise<void> {
38
+ try {
39
+ const authorizationRequest = await this.authorizationRequestResolver.resolve();
40
+ if (authorizationRequest) {
41
+ await this.sendRedirectForAuthorization(authorizationRequest);
42
+ return;
43
+ }
44
+ } catch (error) {
45
+ this.unsuccessfulRedirectForAuthorization(error);
46
+ }
47
+ try {
48
+ await next();
49
+ } catch (err) {
50
+ if (err instanceof ClientAuthorizationError) {
51
+ try {
52
+ const authorizationRequest = await this.authorizationRequestResolver.resolve(err.clientRegistrationId);
53
+ if (authorizationRequest) {
54
+ await this.sendRedirectForAuthorization(authorizationRequest);
55
+ await this.requestCache.save();
56
+ return;
57
+ }
58
+ } catch (error) {
59
+ this.unsuccessfulRedirectForAuthorization(error);
60
+ }
61
+ }
62
+
63
+ throw err;
64
+ }
65
+
66
+ }
67
+ protected unsuccessfulRedirectForAuthorization(error: any) {
68
+ this.logger.error(`Authorization Request failed: ${error}`);
69
+ throw new HttpError(HttpStatus.INTERNAL_SERVER_ERROR, HttpStatus.INTERNAL_SERVER_ERROR_REASON_PHRASE);
70
+ }
71
+
72
+ protected async sendRedirectForAuthorization(authorizationRequest: AuthorizationRequest) {
73
+ if (AuthorizationGrantType.AuthorizationCode === authorizationRequest.authorizationGrantType) {
74
+ await this.authorizationRequestManager.save(authorizationRequest);
75
+ }
76
+ if (this.targetUrlParameter) {
77
+ const redirectUrl = <string>Context.getRequest().query[this.targetUrlParameter];
78
+ if (redirectUrl) {
79
+ await this.requestCache.save({
80
+ redirectUrl,
81
+ method: HttpMethod.GET,
82
+ query: {}
83
+ });
84
+ }
85
+ }
86
+ await this.redirectStrategy.send(authorizationRequest.authorizationRequestUri);
87
+ }
88
+
89
+ readonly priority: number = AUTHORIZATION_REQUEST_REDIRECT_MIDDLEWARE_PRIORITY;
90
+
91
+ }
@@ -0,0 +1,149 @@
1
+ import { AuthorizationRequestResolver } from './authorization-protocol';
2
+ import { AuthorizationRequest, OAuth2ParameterNames,
3
+ AuthorizationGrantType, OidcScopes, PkceParameterNames, ClientAuthenticationMethod, OidcParameterNames, AuthorizationResponseType } from '@celljs/oauth2-core';
4
+ import { Component, Autowired, Value, IllegalArgumentError } from '@celljs/core';
5
+ import { ClientRegistrationManager, ClientRegistration } from '../registration';
6
+ import { RequestMatcher, Context } from '@celljs/web/lib/node';
7
+ import { AUTHORIZATION_REQUEST_BASE_URI, DEFAULT_REDIRECT_URI } from '../constants';
8
+ import { Base64StringKeyGenerator } from '@celljs/security/lib/node';
9
+ import { SHA256, enc } from 'crypto-js';
10
+ import { ProviderDetailsManager } from '../provider';
11
+ import * as qs from 'qs';
12
+ import { PathResolver, ENDPOINT, UrlUtil } from '@celljs/web';
13
+
14
+ export const REGISTRATION_ID_URI_VARIABLE_NAME = 'registrationId';
15
+
16
+ @Component(AuthorizationRequestResolver)
17
+ export class DefaultAuthorizationRequestResolver implements AuthorizationRequestResolver {
18
+
19
+ @Autowired(ClientRegistrationManager)
20
+ protected readonly clientRegistrationManager: ClientRegistrationManager;
21
+
22
+ @Autowired(ProviderDetailsManager)
23
+ protected readonly providerDetailsManager: ProviderDetailsManager;
24
+
25
+ @Autowired(RequestMatcher)
26
+ protected readonly requestMatcher: RequestMatcher;
27
+
28
+ @Autowired(Base64StringKeyGenerator)
29
+ protected readonly base64StringKeyGenerator: Base64StringKeyGenerator;
30
+
31
+ @Autowired(PathResolver)
32
+ protected readonly pathResolver: PathResolver;
33
+
34
+ @Value(AUTHORIZATION_REQUEST_BASE_URI)
35
+ protected readonly authorizationRequestBaseUri: string;
36
+
37
+ @Value(DEFAULT_REDIRECT_URI)
38
+ protected readonly defaultRedirectUri: string;
39
+
40
+ @Value(ENDPOINT)
41
+ protected readonly endpoint: string;
42
+
43
+ async resolve(clientRegistrationId?: string): Promise<AuthorizationRequest | undefined> {
44
+ const registrationId = clientRegistrationId || await this.resolveRegistrationId();
45
+ if (registrationId) {
46
+ const redirectUriAction = this.getAction();
47
+ return this.doResolve(registrationId, redirectUriAction);
48
+ }
49
+ }
50
+
51
+ protected async doResolve(registrationId: string, redirectUriAction: string) {
52
+ const clientRegistration = await this.clientRegistrationManager.get(registrationId);
53
+ if (!clientRegistration) {
54
+ throw new IllegalArgumentError(`Invalid Client Registration with Id: ${registrationId}`);
55
+ }
56
+ const attributes: { [key: string]: any } = {};
57
+ attributes[OAuth2ParameterNames.REGISTRATION_ID] = clientRegistration.registrationId;
58
+
59
+ if (AuthorizationGrantType.AuthorizationCode === clientRegistration.authorizationGrantType) {
60
+ const additionalParameters: { [key: string]: any } = {};
61
+ const scopes = clientRegistration.scopes;
62
+ if (scopes.indexOf(OidcScopes.OPENID)) {
63
+ await this.addNonceParameters(attributes, additionalParameters);
64
+ }
65
+ if (ClientAuthenticationMethod.None === clientRegistration.clientAuthenticationMethod) {
66
+ await this.addPkceParameters(attributes, additionalParameters);
67
+ }
68
+ const providerDetails = await this.providerDetailsManager.get(clientRegistration.provider);
69
+ if (!providerDetails) {
70
+ throw new IllegalArgumentError(`Invalid Provider Details with Id: ${clientRegistration.provider}`);
71
+ }
72
+ const authorizationRequest = <AuthorizationRequest>{
73
+ authorizationGrantType: clientRegistration.authorizationGrantType,
74
+ responseType: clientRegistration.authorizationGrantType === AuthorizationGrantType.AuthorizationCode ? AuthorizationResponseType.Code : undefined,
75
+ clientId: clientRegistration.clientId,
76
+ authorizationUri: providerDetails.authorizationUri,
77
+ redirectUri: await this.expandRedirectUri(clientRegistration, redirectUriAction),
78
+ scopes: clientRegistration.scopes,
79
+ state: await this.base64StringKeyGenerator.generateKey(),
80
+ attributes,
81
+ additionalParameters
82
+ };
83
+ authorizationRequest.authorizationRequestUri = `${authorizationRequest.authorizationUri}?${qs.stringify(this.getParameters(authorizationRequest))}`;
84
+ return authorizationRequest;
85
+ }
86
+
87
+ throw new IllegalArgumentError(
88
+ `Invalid Authorization Grant Type (${clientRegistration.authorizationGrantType}) for Client Registration with Id: ${clientRegistration.registrationId}`);
89
+
90
+ }
91
+
92
+ protected getParameters(authorizationRequest: AuthorizationRequest) {
93
+ const parameters: { [key: string]: string } = {};
94
+ parameters[OAuth2ParameterNames.RESPONSE_TYPE] = authorizationRequest.responseType;
95
+ parameters[OAuth2ParameterNames.CLIENT_ID] = authorizationRequest.clientId;
96
+ if (authorizationRequest.scopes) {
97
+ parameters[OAuth2ParameterNames.SCOPE] = authorizationRequest.scopes.join(' ');
98
+ }
99
+ if (authorizationRequest.state) {
100
+ parameters[OAuth2ParameterNames.STATE] = authorizationRequest.state;
101
+ }
102
+ if (authorizationRequest.redirectUri) {
103
+ parameters[OAuth2ParameterNames.REDIRECT_URI] = authorizationRequest.redirectUri;
104
+ }
105
+ for (const key in authorizationRequest.additionalParameters) {
106
+ if (Object.prototype.hasOwnProperty.call(authorizationRequest.additionalParameters, key)) {
107
+ parameters[key] = authorizationRequest.additionalParameters[key];
108
+ }
109
+ }
110
+ return parameters;
111
+ }
112
+
113
+ protected expandRedirectUri(clientRegistration: ClientRegistration, action: string) {
114
+ const redirectUri = clientRegistration.redirectUri || this.defaultRedirectUri;
115
+ return this.pathResolver.resolve(UrlUtil.isAbsoluteUrl(redirectUri) ? '' : this.endpoint,
116
+ redirectUri.replace('{action}', action).replace(`{${REGISTRATION_ID_URI_VARIABLE_NAME}}`, clientRegistration.registrationId));
117
+ }
118
+
119
+ protected async addNonceParameters(attributes: { [key: string]: any }, additionalParameters: { [key: string]: any }) {
120
+ const nonce = await this.base64StringKeyGenerator.generateKey(96);
121
+ const nonceHash = this.createHash(nonce);
122
+ attributes[OidcParameterNames.NONCE] = nonce;
123
+ additionalParameters[OidcParameterNames.NONCE] = nonceHash;
124
+ }
125
+
126
+ protected async addPkceParameters(attributes: { [key: string]: any }, additionalParameters: { [key: string]: any }) {
127
+ const codeVerifier = await this.base64StringKeyGenerator.generateKey(96);
128
+ attributes[PkceParameterNames.CODE_VERIFIER] = codeVerifier;
129
+ const codeChallenge = this.createHash(codeVerifier);
130
+ additionalParameters[PkceParameterNames.CODE_CHALLENGE] = codeChallenge;
131
+ additionalParameters[PkceParameterNames.CODE_CHALLENGE_METHOD] = 'S256';
132
+ }
133
+
134
+ protected createHash(nonce: string) {
135
+ return enc.Base64.stringify(SHA256(nonce));
136
+ }
137
+
138
+ protected async resolveRegistrationId(): Promise<string | undefined> {
139
+ const params = await this.requestMatcher.match(`${this.authorizationRequestBaseUri}/:${REGISTRATION_ID_URI_VARIABLE_NAME}`);
140
+ if (params) {
141
+ return params[REGISTRATION_ID_URI_VARIABLE_NAME];
142
+ }
143
+ }
144
+
145
+ protected getAction(defaultAction = 'login') {
146
+ return <string>Context.getRequest().query['action'] || defaultAction;
147
+ }
148
+
149
+ }
@@ -0,0 +1,15 @@
1
+ import { AuthorizationSuccessHandler, AuthorizedClient, AuthorizedClientManager } from './authorization-protocol';
2
+ import { Authentication } from '@celljs/security/lib/node';
3
+ import { Component, Autowired } from '@celljs/core';
4
+
5
+ @Component(AuthorizationSuccessHandler)
6
+ export class DefaultAuthorizationSuccessHandler implements AuthorizationSuccessHandler {
7
+
8
+ @Autowired(AuthorizedClientManager)
9
+ protected readonly authorizedClientManager: AuthorizedClientManager<AuthorizedClient>;
10
+
11
+ onAuthorizationSuccess(authorizedClient: AuthorizedClient, principal: Authentication): Promise<void> {
12
+ return this.authorizedClientManager.save(authorizedClient, principal.name);
13
+ }
14
+
15
+ }
@@ -0,0 +1,35 @@
1
+ import { AuthorizedClient, AuthorizedClientManager } from './authorization-protocol';
2
+ import { Component, Autowired } from '@celljs/core';
3
+ import { ClientRegistrationManager } from '../registration';
4
+
5
+ @Component(AuthorizedClientManager)
6
+ export class InMemoryAuthorizedClientManager implements AuthorizedClientManager<AuthorizedClient> {
7
+
8
+ protected readonly authorizedClients = new Map<string, AuthorizedClient>();
9
+
10
+ @Autowired(ClientRegistrationManager)
11
+ protected readonly clientRegistrationManager: ClientRegistrationManager;
12
+
13
+ async get(clientRegistrationId: string, principalName: string): Promise<AuthorizedClient | undefined> {
14
+ const registration = await this.clientRegistrationManager.get(clientRegistrationId);
15
+ if (registration) {
16
+ return this.authorizedClients.get(this.getId(clientRegistrationId, principalName));
17
+ }
18
+ }
19
+ async save(authorizedClient: AuthorizedClient, principalName: string): Promise<void> {
20
+ const { clientRegistration } = authorizedClient;
21
+ this.authorizedClients.set(this.getId(clientRegistration.registrationId, principalName), authorizedClient);
22
+ }
23
+
24
+ async remove(clientRegistrationId: string, principalName: string): Promise<void> {
25
+ const registration = await this.clientRegistrationManager.get(clientRegistrationId);
26
+ if (registration) {
27
+ this.authorizedClients.delete(this.getId(clientRegistrationId, principalName));
28
+ }
29
+ }
30
+
31
+ protected getId(clientRegistrationId: string, principalName: string) {
32
+ return `${clientRegistrationId}@${principalName}`;
33
+ }
34
+
35
+ }
@@ -0,0 +1,73 @@
1
+ import { AuthorizedClientService, AuthorizeRequest, AuthorizedClient, AuthorizedClientProvider, AuthorizationContext, AuthorizedClientManager,
2
+ ContextAttributesMapper, AuthorizationSuccessHandler, AuthorizationFailureHandler } from './authorization-protocol';
3
+ import { Component, Autowired } from '@celljs/core';
4
+ import { ClientRegistrationManager } from '../registration';
5
+ import { ok } from 'assert';
6
+ import { OAuth2AuthorizationError } from '@celljs/oauth2-core';
7
+
8
+ @Component(AuthorizedClientService)
9
+ export class DefaultAuthorizedClientService implements AuthorizedClientService {
10
+
11
+ @Autowired(AuthorizedClientProvider)
12
+ protected readonly authorizedClientProviders: AuthorizedClientProvider[];
13
+
14
+ @Autowired(ClientRegistrationManager)
15
+ protected readonly clientRegistrationManager: ClientRegistrationManager;
16
+
17
+ @Autowired(AuthorizedClientManager)
18
+ protected readonly authorizedClientManager: AuthorizedClientManager<AuthorizedClient>;
19
+
20
+ @Autowired(ContextAttributesMapper)
21
+ protected readonly contextAttributesMapper: ContextAttributesMapper;
22
+
23
+ @Autowired(AuthorizationSuccessHandler)
24
+ protected readonly authorizationSuccessHandler: AuthorizationSuccessHandler;
25
+
26
+ @Autowired(AuthorizationFailureHandler)
27
+ protected readonly authorizationFailureHandler: AuthorizationFailureHandler;
28
+
29
+ async authorize(authorizeRequest: AuthorizeRequest): Promise<AuthorizedClient | undefined> {
30
+ const { clientRegistrationId, principal, authorizedClient, attributes } = authorizeRequest;
31
+ const contextAttributes = await this.contextAttributesMapper.apply(authorizeRequest);
32
+
33
+ if (attributes) {
34
+ for (const [key, value] of attributes.entries()) {
35
+ contextAttributes.set(key, value);
36
+ }
37
+ }
38
+ const context = <AuthorizationContext>{
39
+ principal,
40
+ attributes: contextAttributes
41
+ };
42
+ if (!authorizedClient) {
43
+ const clientRegistration = await this.clientRegistrationManager.get(clientRegistrationId);
44
+ ok(clientRegistration, `Could not find ClientRegistration with id '${clientRegistrationId}'`);
45
+ context.clientRegistration = clientRegistration!;
46
+ context.authorizedClient = await this.authorizedClientManager.get(clientRegistrationId, principal.name);
47
+ }
48
+
49
+ let client: AuthorizedClient | undefined;
50
+
51
+ try {
52
+ for (const authorizedClientProvider of this.authorizedClientProviders) {
53
+ client = await authorizedClientProvider.provide(context);
54
+ if (client) {
55
+ break;
56
+ }
57
+ }
58
+ } catch (error) {
59
+ if (error instanceof OAuth2AuthorizationError) {
60
+ await this.authorizationFailureHandler.onAuthorizationFailure(error, principal);
61
+ }
62
+ throw error;
63
+ }
64
+
65
+ if (client) {
66
+ await this.authorizationSuccessHandler.onAuthorizationSuccess(client, principal);
67
+ return client;
68
+ }
69
+ return authorizedClient;
70
+
71
+ }
72
+
73
+ }