Spring Security - обработка пользовательской аннотации в GenericFilterBean - PullRequest
0 голосов
/ 06 мая 2020

в моем контроллере у меня есть настраиваемая аннотация, например:

@GetMapping("/apikey")
@Secured(apiKeys = { ApiKey.APP_1})  // <- Custom annotation
public ResponseEntity startApiKey() {
    return ResponseEntity.status(HttpStatus.OK).body("ApiKey approved");
}

В моей Spring Security Config я добавил фильтр для проверки apikey и аутентификации:

public class ApiKeyAuthenticationFilter extends AbstractPreAuthenticatedProcessingFilter {

@Override
protected Object getPreAuthenticatedPrincipal(HttpServletRequest request) {
    return request.getHeader(ApiKeyHeadername.DEFAULTHEADERNAME.getHeadername());
}

@Override
protected Object getPreAuthenticatedCredentials(HttpServletRequest request) {
    return "N/A";
}

@Override
public void setAuthenticationManager(AuthenticationManager authenticationManager) {
    super.setAuthenticationManager(authentication -> {
        String principal = (String) authentication.getPrincipal();
        if (!ApiKey.APP_1.getApiKey().equals(principal))
        {
            throw new BadCredentialsException("The API key was not found or not the expected value.");
        }
        authentication.setAuthenticated(true);
        return authentication;
    });
 }
}

Перед пользовательская аннотация была обработана в классе AspectJ:

@Component
@Aspect
@Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class SecurityAspect {

@Autowired
private IPrincipal principal;

@Autowired
private AuthorizationManager authorizationManager;

@Pointcut("@annotation(my.demo.application.security.aspect.Secured)")
public void methodAnnotatedWithSecured() {
}

@Around("methodAnnotatedWithSecured()")
public Object userAdvice(ProceedingJoinPoint joinPoint) throws Throwable {

    MethodSignature signature = (MethodSignature) joinPoint.getSignature();
    Method method = signature.getMethod();
    Secured securedAnnotation = method.getAnnotation(Secured.class);

    Authorized securityInformation = new Authorized(securedAnnotation.apiKeys(), securedAnnotation.roles(),
            securedAnnotation.usernames());

    if (authorizationManager.authorizeUserPrincipal(principal,
            securityInformation) == AuthorizationState.UNAUTHORIZED) {
        throw DefaultNotAuthorizedExceptionFactory.createNotAuthorizedException();
    }

    return joinPoint.proceed();
}

}

Как я могу обработать аннотационную информацию в AbstractPreAuthenticatedProcessingFilter или как получить аннотацию с помощью Reflection в этом фильтре. Или можно что-то уколоть, чтобы получить?

Спасибо советом

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...