SpringBoot webflux аутентифицируется с помощью параметра запроса - PullRequest
0 голосов
/ 14 октября 2019

В Springboot webflux я могу получить текущий принцип, используя этот код

Object principal = ReactiveSecurityContextHolder.getContext().getAuthentication().getPrincipal();

Если пользователь аутентифицирован. Но у меня есть случай, когда токен JWT будет отправлен как параметр запроса, а не как заголовок authorization, я знаю, как преобразовать токен в Authentication объект

Как я могу внедрить этот токенAuthentication объект в текущем ReactiveSecurityContextHolder

1 Ответ

0 голосов
/ 17 октября 2019

Вы можете установить свой собственный Authentication и взять токен из параметров запроса следующим образом:

@Component
public class CustomAuthentication implements ServerSecurityContextRepository {

    private static final String TOKEN_PREFIX = "Bearer ";

    @Autowired
    private ReactiveAuthenticationManager authenticationManager;

    @Override
    public Mono<Void> save(ServerWebExchange serverWebExchange, SecurityContext securityContext) {
        throw new UnsupportedOperationException("No support");
    }

    @Override
    public Mono<SecurityContext> load(ServerWebExchange serverWebExchange) {
        ServerHttpRequest request = serverWebExchange.getRequest();
        String authJwt = request.getQueryParams().getFirst("Authentication");

        if (authJwt != null && authJwt.startsWith(TOKEN_PREFIX)) {
            authJwt = authJwt.replace(TOKEN_PREFIX, "");
            Authentication authentication =
                new UsernamePasswordAuthenticationToken(getPrincipalFromJwt(authJwt), authJwt);
            return this.authenticationManager.authenticate(authentication).map((authentication1 -> new SecurityContextImpl(authentication)));
        }
        return Mono.empty();
    }

    private String getPrincipalFromJwt(String authJwt) {
        return  authJwt;
    }
}

Это простой блок кода, демонстрирующий, как вы можете достичь своей цели. Вы можете улучшить getPrincipalFromJwt() метод, чтобы он возвращал другой объект, который вы хотели бы установить в качестве принципала. Или вы можете использовать другую реализацию Authentication (в отличие от UsernamePasswordAuthenticationToken в этом примере).

...