java - 找不到用于定界符text/html; charset = UTF-8的插件!注册的插件:[org.springframework.hateoas.mediatype.hal.HalLinkDiscoverer @

标签 java spring-boot

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

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通过媒体支持(HATEOAS)在JSON中提供RESTful API端点。

ProductMicroServiceClient使用ProductMicroService的API端点,并为前端提供RESTful API以及媒体支持(HATEOAS)。

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

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

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

User和Authority表与数据服务位于相同的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

我介绍了一个数据库View 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成功进行身份验证之后以及加载下一页之前,我得到了Exception。

<!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>


在此问题的顶部提到Exception。

我已经尝试过的


将不同的UTF-8配置放入文件pom.xml等。
将数据库字段更改为CHARSET utf8 COLLATE utf8_bin和CHARSET 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 App调用ProductMicrosService的API端点。
在调试时,我发现
(a)正确的用户,(加密的)密码和角色用于身份验证
(b)没有访问被拒绝的处理程序被调用
(c)未输入API端点的方法调用(findAll()方法)
(d)响应标题包含“ HttP 401-未经授权”
(e)邮递员的回应为空

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

现在问我:
安全配置是否存在缺失或错误?
为什么我没有收到未经授权的例外?

最佳答案

报告的异常问题现在可以解决。
在安全性配置中进行某些更改后,该异常已解决。
现在可以从Postman App调用Data Service API端点(ProductMicroService),并且可以提供预期的JSON对象作为响应。
从接口服务(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(正在学习)。

关于java - 找不到用于定界符text/html; charset = UTF-8的插件!注册的插件:[org.springframework.hateoas.mediatype.hal.HalLinkDiscoverer @,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61302769/

相关文章:

java - 如何使用 Jackson 指定要序列化为 JSON 的特定字段?

java - JPA 中的 @OneToMany 关系且 IS NOT EMPTY

java - 飞行路线迁移: Data Import With German Umlauts

spring-boot - Hystrix 和 Turbine 不适用于 Spring boot 2 和 Spring cloud Finchley.M8

java - 为什么第二个代码比第一个更有效?

java - 如何使用 Eclipse 在 Java 中编译这个网络套接字示例?

java - 在给定的代码块中查找错误(类的扩展,个人/学生)

java - 使用不同的 jackson ObjectMapper 进行单独的 RequestMapping

spring-boot - 如何连接到不同dc中的多个Cassandra

spring-boot - ErrorPageFilter 将错误代码更改为 HTTP 200 OK