Skip to content

Commit

Permalink
feat: add config option for debouncing unauthorized handler
Browse files Browse the repository at this point in the history
  • Loading branch information
derrabauke committed Apr 20, 2023
1 parent dd18217 commit 0bafd98
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 4 deletions.
12 changes: 9 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,10 @@ export default class LoginRoute extends OIDCAuthenticationRoute {}

Authenticated routes need to call `session.requireAuthentication` in their
respective `beforeModel`, to ensure that unauthenticated transitions are
prevented and redirected to the authentication route.
prevented and redirected to the authentication route. It's recommended to
await the `beforeModel` hook, to make sure authentication is handled before
other API calls are triggered (which might lead to `401` responses, potentially
causing redirect loops).

```js
// app/routes/protected.js
Expand All @@ -53,8 +56,8 @@ import { inject as service } from "@ember/service";
export default class ProtectedRoute extends Route {
@service session;

beforeModel(transition) {
this.session.requireAuthentication(transition, "login");
async beforeModel(transition) {
await this.session.requireAuthentication(transition, "login");
}
}
```
Expand Down Expand Up @@ -239,6 +242,9 @@ Timeout in milliseconds between each retry if a token refresh should fail. Defau
**enablePkce** `<Boolean>` (optional)
Enables PKCE mechanism to provide additional protection during code to token exchanges. Default is `false`.

**unauthorizedRequestRedirectTimeout** `<Number>` (optional)
Debounce timeout for redirection after (multiple) `401` responses are received to prevent redirect loops (at the cost of a small delay). Set to `0` to disable debouncing. Default is `1000`.

## Contributing

### Installation
Expand Down
1 change: 1 addition & 0 deletions addon/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ export function getConfig(owner) {
...(owner.resolveRegistration("config:environment")[
"ember-simple-auth-oidc"
] ?? {}),
unauthorizedRequestRedirectTimeout: 1000,
};
}

Expand Down
7 changes: 6 additions & 1 deletion addon/unauthorized.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,11 @@ export default function handleUnauthorized(session) {
// Debounce the redirect, so we can collect all unauthorized requests and trigger a final
// redirect. We don't want to interrupt calls to the authorization endpoint nor create race
// conditions when multiple requests land in this unauthorized handler.
debounce(this, replaceUri, session, 1000);
debounce(
this,
replaceUri,
session,
getConfig(getOwner(session)).unauthorizedRequestRedirectTimeout
);
}
}

0 comments on commit 0bafd98

Please sign in to comment.