基于安全元信息上下文获得安全元信息。

定义

  1. export interface SecurityMetadataSource {
  2. load(context: SecurityMetadataContext): Promise<SecurityMetadata>;
  3. }

默认实现

  1. @Component(SecurityMetadataSource)
  2. export class MethodSecurityMetadataSource implements SecurityMetadataSource {
  3. @Autowired(SecurityExpressionContextHandler) @Optional
  4. protected readonly securityExpressionContextHandler: SecurityExpressionContextHandler;
  5. async load(context: MethodSecurityMetadataContext): Promise<SecurityMetadata> {
  6. const classMetadatas: AuthorizeMetadata[] = getOwnMetadata(METADATA_KEY.authorize, context.target.constructor);
  7. const methodMetadatas: AuthorizeMetadata[] = getOwnMetadata(METADATA_KEY.authorize, context.target.constructor, context.method);
  8. const ctx = {
  9. ...context,
  10. ...SecurityContext.getAuthentication()
  11. };
  12. Context.setAttr(SECURITY_EXPRESSION_CONTEXT_KEY, ctx);
  13. if (this.securityExpressionContextHandler) {
  14. await this.securityExpressionContextHandler.handle(ctx);
  15. }
  16. const policies = classMetadatas.concat(...methodMetadatas)
  17. .filter(item => item.authorizeType === context.authorizeType)
  18. .map(item => ({
  19. type: PolicyType.El,
  20. authorizeType: item.authorizeType,
  21. el: item.el
  22. }));
  23. const resource = context.target.name;
  24. return {
  25. authorizeType: context.authorizeType,
  26. principal: SecurityContext.getAuthentication().principal,
  27. action: context.method,
  28. resource,
  29. policies: policies
  30. };
  31. }
  32. }