如何访问标头中的令牌以将其传递给 thymeleaf 以便能够进行 ajax 调用

发布于 2025-01-11 05:56:44 字数 3534 浏览 0 评论 0原文

我使用 Spring Boot 和 Spring Cloud Gateway 我有另一个带有 spring boot 和 thymeleaf 的应用程序

Spring gateway 将令牌返回到我的 thymeleaf 应用程序。

@EnableWebFluxSecurity
@Configuration
public class WebFluxSecurityConfig {

    @Autowired
    private WebFluxAuthManager authManager;

    @Bean
    protected SecurityWebFilterChain securityFilterChange(ServerHttpSecurity http) throws Exception {
        http.authorizeExchange()
                // URL that starts with / or /login/
                .pathMatchers("/", "/login", "/js/**", "/images/**", "/css/**", "/h2-console/**").permitAll()
                .anyExchange().authenticated().and().formLogin()
                .authenticationManager(authManager)
                .authenticationSuccessHandler(new RedirectServerAuthenticationSuccesHandler("/findAllCustomers"));
        return http.build();

    }

}

WebFluxAuthManager 类

@Component
public class WebFluxAuthManager implements ReactiveAuthenticationManager {

    @Value("${gateway.url}")
    private String gatewayUrl;

    @Override
    public Mono<Authentication> authenticate(Authentication authentication) {
        // return is already authenticated
        if (authentication.isAuthenticated()) {
            return Mono.just(authentication);
        }
        String username = authentication.getName();
        String password = authentication.getCredentials().toString();

        LoginRequest loginRequest = new LoginRequest(username, password);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            //todo modify to use webclient
            
            HttpPost httpPost = new HttpPost(this.gatewayUrl + "/authenticate");
            httpPost.setHeader("Content-type", "application/json");
            String jsonReq = converObjectToJson(loginRequest);
            StringEntity requestEntity = new StringEntity(jsonReq);
            httpPost.setEntity(requestEntity);

            CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.OK.value()) {
                HttpEntity entity = httpResponse.getEntity();
                Header encodingHeader = entity.getContentEncoding();

                Charset encoding = encodingHeader == null ? StandardCharsets.UTF_8
                        : Charsets.toCharset(encodingHeader.getValue());
                // use org.apache.http.util.EntityUtils to read json as string
                String jsonRes = EntityUtils.toString(entity, encoding);
                LoginResponse loginResponse = converJsonToResponse(jsonRes);
                Collection<? extends GrantedAuthority> authorities = loginResponse.getRoles().stream()
                        .map(item -> new SimpleGrantedAuthority(item)).collect(Collectors.toList());
                return Mono.just(new UsernamePasswordAuthenticationToken(username, password, authorities));
            } else {
                throw new BadCredentialsException("Authentication Failed!!!");
            }

        } catch (RestClientException | ParseException | IOException e) {
            throw new BadCredentialsException("Authentication Failed!!!", e);
        } finally {
            try {
                if (httpClient != null)
                    httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

在 WebFluxAuthManager 中,我可以访问令牌,现在我搜索一种将其传输到片段的方法。

I use spring boot with spring cloud gateway
I have another app with spring boot and thymeleaf

Spring gateway return a token to my thymeleaf app.

@EnableWebFluxSecurity
@Configuration
public class WebFluxSecurityConfig {

    @Autowired
    private WebFluxAuthManager authManager;

    @Bean
    protected SecurityWebFilterChain securityFilterChange(ServerHttpSecurity http) throws Exception {
        http.authorizeExchange()
                // URL that starts with / or /login/
                .pathMatchers("/", "/login", "/js/**", "/images/**", "/css/**", "/h2-console/**").permitAll()
                .anyExchange().authenticated().and().formLogin()
                .authenticationManager(authManager)
                .authenticationSuccessHandler(new RedirectServerAuthenticationSuccesHandler("/findAllCustomers"));
        return http.build();

    }

}

WebFluxAuthManager class

@Component
public class WebFluxAuthManager implements ReactiveAuthenticationManager {

    @Value("${gateway.url}")
    private String gatewayUrl;

    @Override
    public Mono<Authentication> authenticate(Authentication authentication) {
        // return is already authenticated
        if (authentication.isAuthenticated()) {
            return Mono.just(authentication);
        }
        String username = authentication.getName();
        String password = authentication.getCredentials().toString();

        LoginRequest loginRequest = new LoginRequest(username, password);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            //todo modify to use webclient
            
            HttpPost httpPost = new HttpPost(this.gatewayUrl + "/authenticate");
            httpPost.setHeader("Content-type", "application/json");
            String jsonReq = converObjectToJson(loginRequest);
            StringEntity requestEntity = new StringEntity(jsonReq);
            httpPost.setEntity(requestEntity);

            CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.OK.value()) {
                HttpEntity entity = httpResponse.getEntity();
                Header encodingHeader = entity.getContentEncoding();

                Charset encoding = encodingHeader == null ? StandardCharsets.UTF_8
                        : Charsets.toCharset(encodingHeader.getValue());
                // use org.apache.http.util.EntityUtils to read json as string
                String jsonRes = EntityUtils.toString(entity, encoding);
                LoginResponse loginResponse = converJsonToResponse(jsonRes);
                Collection<? extends GrantedAuthority> authorities = loginResponse.getRoles().stream()
                        .map(item -> new SimpleGrantedAuthority(item)).collect(Collectors.toList());
                return Mono.just(new UsernamePasswordAuthenticationToken(username, password, authorities));
            } else {
                throw new BadCredentialsException("Authentication Failed!!!");
            }

        } catch (RestClientException | ParseException | IOException e) {
            throw new BadCredentialsException("Authentication Failed!!!", e);
        } finally {
            try {
                if (httpClient != null)
                    httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

In WebFluxAuthManager, I have access to the token, now I search a way to transfert it to a fragment.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文