Skip to content

Commit

Permalink
feat(authorization): add authorize.skip to skip authorization
Browse files Browse the repository at this point in the history
  • Loading branch information
raymondfeng committed Sep 19, 2019
1 parent 2bd9225 commit f706947
Show file tree
Hide file tree
Showing 5 changed files with 42 additions and 1 deletion.
21 changes: 21 additions & 0 deletions packages/authorization/README.md
Expand Up @@ -118,6 +118,27 @@ export class MyController {
}
```

Please note that `@authorize` can also be applied at class level for all methods
within the class. In the code below, `numOfViews` is protected with
`BasicStrategy` (inherited from the class level) while `hello` does not require
authorization (skipped by `@authorize.skip`).

```ts
@authorize({allow: ['ADMIN']})
export class MyController {
@get('/number-of-views')
numOfViews(): number {
return 100;
}

@authorize.skip()
@get('/hello')
hello(): string {
return 'Hello';
}
}
```

## Extract common layer(TBD)

`@loopback/authentication` and `@loopback/authorization` shares the client
Expand Down
Expand Up @@ -155,6 +155,16 @@ describe('Authentication', () => {
});
});

it('can skip authorization with a flag', () => {
class TestClass {
@authorize.skip()
getSecret() {}
}

const metaData = getAuthorizationMetadata(TestClass, 'getSecret');
expect(metaData).to.eql({skip: true});
});

it('can stack decorators to target method', () => {
class TestClass {
@authorize.allow('a1', 'a2')
Expand Down
2 changes: 1 addition & 1 deletion packages/authorization/src/authorize-interceptor.ts
Expand Up @@ -68,7 +68,7 @@ export class AuthorizationInterceptor implements Provider<Interceptor> {
debug('No authorization metadata is found for %s', description);
}
metadata = metadata || this.options.defaultMetadata;
if (!metadata) {
if (!metadata || (metadata && metadata.skip)) {
debug('Authorization is skipped for %s', description);
const result = await next();
return result;
Expand Down
6 changes: 6 additions & 0 deletions packages/authorization/src/decorators/authorize.ts
Expand Up @@ -88,6 +88,7 @@ export class AuthorizeMethodDecoratorFactory extends MethodDecoratorFactory<
return list;
}
}

/**
* Decorator `@authorize` to mark methods that require authorization
*
Expand Down Expand Up @@ -191,6 +192,11 @@ export namespace authorize {
* Deny unauthenticated users
*/
export const denyUnauthenticated = () => deny(UNAUTHENTICATED);

/**
* Skip authorization
*/
export const skip = () => authorize({skip: true});
}

/**
Expand Down
4 changes: 4 additions & 0 deletions packages/authorization/src/types.ts
Expand Up @@ -58,6 +58,10 @@ export interface AuthorizationMetadata {
* Define the access scopes
*/
scopes?: string[];
/**
* A flag to skip authorization
*/
skip?: boolean;
}

/**
Expand Down

0 comments on commit f706947

Please sign in to comment.