繁体   English   中英

没有为分隔符 text/html 找到插件;charset=UTF-8:已注册插件。 [org.springframework.hateoas.mediatype.hal.HalLinkDiscoverer@

[英]No plugin found for delimiter text/html;charset=UTF-8! Registered plugins: [org.springframework.hateoas.mediatype.hal.HalLinkDiscoverer@

对于以下异常,我需要您的帮助:

Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Sun Apr 19 09:45:23 CEST 2020
There was an unexpected error (type=Internal Server Error, status=500).
No plugin found for delimiter text/html;charset=UTF-8! Registered plugins: [org.springframework.hateoas.mediatype.hal.HalLinkDiscoverer@665cd8b1].
java.lang.IllegalArgumentException: No plugin found for delimiter text/html;charset=UTF-8! Registered plugins: [org.springframework.hateoas.mediatype.hal.HalLinkDiscoverer@665cd8b1].
    at org.springframework.plugin.core.SimplePluginRegistry.lambda$getRequiredPluginFor$2(SimplePluginRegistry.java:140)
...

我使用 SpringBoot 实现了两个 WebService:一个名为 ProductMicroService 的数据服务和一个名为 ProductMicroServiceClient 的接口服务,用于前端的消费者。

ProductMicroService 基于 JPA 实现,并使用 SQL 数据库(在我的示例中为 MariaDB)作为持久性后端。 Controller 在 JSON 中提供带有媒体支持 (HATEOAS) 的 RESTful API 端点。

ProductMicroServiceClient 使用来自 ProductMicroService 的 API 端点,并为前端提供 RESTful API,同时还具有媒体支持 (HATEOAS)。

在我的示例中,客户端是一个运行一些简单 Thymleaf 模板的 WebBrowser。

在我的本地机器上运行纯 ProductMicroService 和 ProductMicroServiceClient 实现时,一切顺利。

此外,在为 ProductMicroServiceClient 引入基于 JDBC 的安全性之后,一切都运行良好,包括对 API 端点的访问限制。

用户和权限表与数据服务保持在相同的 MariaDB 中。

但是在为 ProductMicroService 引入 SecurityService 之后,我在成功验证后收到上述异常(来自 SpringBoot 的标准登录页面)。

我正在使用 OpenJDK。

在互联网上搜索时,我找不到任何解决方案的方向。

一些相关代码

对于 ProductMicroServiceClient:

———— pom.xml ——————————————————————————————————————

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <groupId>eu.mydomain</groupId>
    <artifactId>ProductMicroServiceClient</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>ProductMicroServiceClient</name>
    <description>Learn Spring Boot Configuration for SpringData</description>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-hateoas</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>   

        <dependency>
            <groupId>org.mariadb.jdbc</groupId>
            <artifactId>mariadb-java-client</artifactId>
      </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

——— eu.mydomain.product.security.EncodingFilter.java —————————————————

package eu.mydomain.product.security;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.springframework.web.filter.GenericFilterBean;

public class EncodingFilter extends GenericFilterBean {

    @Override
    public void doFilter(   ServletRequest request,
            ServletResponse response,
            FilterChain chain
            ) throws IOException, ServletException {

        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        chain.doFilter( request, response);
    }

}

——— eu.mydomain.product.security.WebSecurityConfig.java ———————————————

package eu.mydomain.product.security;

import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.crypto.password.StandardPasswordEncoder;
import org.springframework.security.web.access.channel.ChannelProcessingFilter;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure( HttpSecurity http) throws Exception {

        http.addFilterBefore( new EncodingFilter(), ChannelProcessingFilter.class);

        http
            .httpBasic()
            .and()
                .authorizeRequests()
                    .antMatchers("/product/**","/products", "/products/**").hasRole("USER")
                    .antMatchers("/create-products", "/products4create", "/products4edit/**","/update-products/**","/products4edit/**","/delete-products/**","/products4delete/**").hasRole("ADMIN")
                    // .antMatchers("/","/**").permitAll()
                    .antMatchers("/").permitAll()
                    .anyRequest().authenticated()
            .and()
                .formLogin()
            // .and().httpBasic()
            ;


    @Bean
    public PasswordEncoder encoder() {
        return new BCryptPasswordEncoder(16);
    }

    @Autowired DataSource dataSource;
    public void configure( AuthenticationManagerBuilder auth) throws Exception {

        auth 
            .jdbcAuthentication()
            .passwordEncoder( encoder() )
            .usersByUsernameQuery( "SELECT username, password, enabled FROM users WHERE username = ?")
            .authoritiesByUsernameQuery( "SELECT username, authority FROM authorities WHERE username = ?") 
            .dataSource( dataSource);        
    }
}

如前所述,一切都按预期工作。

对于 ProductMicroService

我介绍了一个数据库视图 V_PRODUCT_USERS,它从用户和权限表中提供相关的用户权限,并实现了 ProductUser 实体、IProductUserRepository 和 UserDetailService。

——— eu.mydomain.product.domain.ProductUser.java ——————————————

package eu.mydomain.product.domain;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table( name="v_product_users")
public class ProductUser {

    /*
     * create view if not exists v_product_users as select u.is id, u.username username, u.'password' 'password', a.authority rolefrom users u, authorities a where u.username = a.username;
     * commit;
     */

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(nullable = false, updatable = false)
    private Long id;

    @Column(nullable = false, unique = true, updatable = false)
    private String username;

    @Column(nullable = false, updatable = false)
    private String password;

    @Column(nullable = false, updatable = false)
    private String role;

    public ProductUser()
    {}

    public ProductUser(Long id, String username, String password, String role)
    {
        super();
        this.id = id;
        this.username = username;
        this.password = password;
        this.role = role; 
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getRole() {
        return role;
    }

    public void setRole(String role) {
        this.role = role;
    }   
}

——— eu.mydomain.product.repository.IProductUserRepository.java —————————

package eu.mydomain.product.repository;

import org.springframework.data.repository.CrudRepository;
import eu.mydomain.product.domain.ProductUser;

public interface IProductUserRepository extends CrudRepository< ProductUser, Long> {

        ProductUser findByUsername( String username);
}

——— eu.mydomain.product.service.UserDetailServiceImpl.java —————————

package eu.mydomain.product.service;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import org.springframework.stereotype.Service;

import eu.mydomain.product.domain.ProductUser;
import eu.mydomain.product.repository.IProductUserRepository;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private IProductUserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername( String username) throws UsernameNotFoundException {


        ProductUser productUser = userRepository.findByUsername( username);
        return new User(
                username,
                productUser.getPassword(),
                AuthorityUtils.createAuthorityList( productUser.getRole())      // @TODO: comma separated list of all roles granted
                );
    }

}

最后,为了安全,我介绍了 EncodingFilter 和 WebSecurityConfig:

——— eu.mydomain.product.security.EncodingFilter.java —————————————————

package eu.mydomain.product.security;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.springframework.web.filter.GenericFilterBean;

public class EncodingFilter extends GenericFilterBean {

    @Override
    public void doFilter(   ServletRequest request,
            ServletResponse response,
            FilterChain chain
            ) throws IOException, ServletException {

        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        chain.doFilter( request, response);
    }

}

——— eu.mydomain.product.security.WebSecurityConfig.java ——————————————————

package eu.mydomain.product.security;

import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.channel.ChannelProcessingFilter;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import eu.nydomain.product.service.UserDetailsServiceImpl;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsServiceImpl userDetailsServiceImpl;


    @Override
    protected void configure( HttpSecurity http) throws Exception {

        /*
         *  For Tyhmleaf Templates add <meta>-tag to the HTML-Header for the CSRF Token
         * 
         *      <meta name="_csrf" th:content="${_csrf.token}" />
         *      <meta name="_csrf_header" th:content="${_csrf.headerName}" />
         */

        http.addFilterBefore( new EncodingFilter(), ChannelProcessingFilter.class);

        http
            .authorizeRequests()
                .anyRequest().authenticated()
            .and()
                .formLogin()
            .and()
                .httpBasic()
            ;
    }

    @Bean
    public PasswordEncoder encoder() {
        return new BCryptPasswordEncoder(16);
    }

    @Autowired
    @Override
    public void configure( AuthenticationManagerBuilder auth) throws Exception {        

        auth 
            .userDetailsService( userDetailsServiceImpl)
            .passwordEncoder( encoder() );      

    }

}

现在,在向数据服务引入安全性之后,我在 SpringBoot Security 成功验证后以及在加载以下页面之前得到了异常。

<!DOCTYPE html5>
<html>
    <head>
        <title>Spring Boot Introduction Sample - Products</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <meta name="_csrf" th:content="${_csrf.token}" />
        <meta name="_csrf_header" th:content="${_csrf.headerName}" />
        <!-- <link rel="stylesheet" type="text/css" media="all" href="../css/my.css" data-th-href="@{/css/my.css}" />  -->
    </head>

    <body>

        <p>This is a <i>Product</i> database - as a Client for the Spring Boot Test Sample for RESTful Product services</p> 

        <table>
            <tr>
                <td>
                    <form action="#" th:action="@{/products}" th:object="${product}" method="get">
                        <input type="submit" value="Show All Products" />
                    </form>
                </td>
                <td>
                    <form action="#" th:action="@{/products4create}" th:object="${product}" method="get">
                        <input type="submit" value="Create a new Product" />
                    </form>
                </td>
            </tr>
        </table>
        <hr/>

        <p>All Products:</p> 
        <table>
            <thead>
                <tr>
                    <th>Id</th>
                    <th>Product id</th>
                    <th>Product Name</th>
                    <th>Product Type</th>
                    <th>Description</th>
                    <th>Brand</th>
                    <th colspan="2">Action</th>
                </tr>
            </thead>
            <tbody>          
                <!-- <tr th:each="product, rowStat: ${products}" th:style="${rowStat.odd} ? 'color: gray' : 'color: blue;'"> -->
                <tr th:each="product : ${products}">
                    <td th:text="${product.content.id}">1</td>
                    <td th:text="${product.content.prodId}">Prod Id</td>
                    <td th:text="${product.content.name}">Name</td>
                    <td th:text="${product.content.type}">Type</td>
                    <td th:text="${product.content.description}">Description</td>
                    <td th:text="${product.content.brand}">Brand</td>
                    <td><a th:href="@{|/products4edit/${product.content.id}|}">Edit</a></td>                    
                    <td><a th:href="@{|/products4delete/${product.content.id}|}">Delete</a></td>
                </tr>   
            </tbody>
        </table>
    </body>
</html>

在这个问题的顶部提到异常。

我已经尝试过的:

  • 将不同的UTF-8 配置放入文件 pom.xml 等。
  • 将数据库字段更改为CHARSET utf8 COLLATE utf8_binCHARSET utf8mb4 COLLATE utf8mb4_bin
  • 我实现了我的个人登录页面(和相关处理)
  • 我发现认证后的 ProductMicroServiceClient 一直有效,直到通过以下方式调用 ProductMicroService API 端点:


     ...
            CollectionModel<EntityModel<Product>> productResources = myTraverson
                    .follow( "/products")                                                                   // JSON element             
                    .toObject(new ParameterizedTypeReference<CollectionModel<EntityModel<Product>>>() {});

      ...

不进入 API 端点:


@GetMapping(value = "/products", produces = "application/hal+json")
public CollectionModel<ProductRepresentationModel> findAll() {

    List<Product> products = new ArrayList<>();
    productRepository.findAll().forEach( (p -> products.add(p)));
    CollectionModel<ProductRepresentationModel> productsModelList = new ProductRepresentationAssembler().toCollectionModel(products);

    productsModelList.add( WebMvcLinkBuilder.linkTo( WebMvcLinkBuilder.methodOn(ProductController.class).findAll()).withRel("/products"));      

    return productsModelList;
}

  • 我在 ProductMicroService 中介绍了一个拒绝访问处理程序
    @Override
    protected void configure( HttpSecurity http) throws Exception {

        /*
         *  For Tyhmleaf Templates add <meta>-tag to the HTML-Header for the CSRF Token
         * 
         *      <meta name="_csrf" th:content="${_csrf.token}" />
         *      <meta name="_csrf_header" th:content="${_csrf.headerName}" />
         */

        http.addFilterBefore( new EncodingFilter(), ChannelProcessingFilter.class);

        http
            // .httpBasic()
            // .and()
            .authorizeRequests()
                .anyRequest().authenticated()
            .and()
                .formLogin()
            .and()
                .exceptionHandling()
                .accessDeniedHandler(accessDeniedHandler)
            .and()
                .httpBasic()
            ;

    }

我切换到调试使用 Postman 应用程序和基本身份验证调用 ProductMicrosService 的 API 端点。 在调试时,我发现(a)正确的用户、(加密的)密码和角色用于身份验证(b)没有调用拒绝访问处理程序(c)API 端点的方法调用( findAll() 方法)未输入 (d) 响应 Header 包含“HTTP 401 - 未经授权” (e) Postman 中的响应为空

我现在假设由于收到空响应和 HttP 401 Unauthorizedfrom API 调用而引发上述异常。

现在向我提问:安全配置是否有遗漏或错误? 为什么我没有收到未经授权的异常?

现在可以解决报告的异常问题。 在对安全配置进行某些更改后,异常已得到解决。 从 Postman 应用程序调用数据服务 API 端点 (ProductMicroService) 现在可以工作,并提供预期的 JSON Z43554031790141 作为响应。 从接口服务 (ProdctMicroServiceClient) 调用数据服务 API 端点 (ProductMicroService) 会引发另一个异常:

401 : [{"timestamp":"2020-04-24T19:22:48.851+0000","status":401,"error":"Unauthorized","message":"Unauthorized","path":"/my-products/products"}]
org.springframework.web.client.HttpClientErrorException$Unauthorized: 401 : [{"timestamp":"2020-04-24T19:22:48.851+0000","status":401,"error":"Unauthorized","message":"Unauthorized","path":"/my-products/products"}]

我现在正在关注 JWT 实现(在 ProductMicroService 中运行良好)和 OAuth2(正在进行学习)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM