当前位置: 首页 > 知识库问答 >
问题:

如何解决springboot 2 web应用程序中的401-未授权问题

燕扬
2023-03-14

我的控制器:

    @CrossOrigin(origins="http://localhost:3000") 
        @RequestMapping(value="", method = RequestMethod.GET)
        public ResponseEntity<List<Client>> getAllClients(/*@RequestParam("page") int page, @RequestParam("size") int size*/) {

            List<Client> clientList = services.getClientsList(/*page,size*/);
            if(clientList != null) {
                return new ResponseEntity<>(clientList, HttpStatus.OK);
            }else{
                return  new ResponseEntity<>(HttpStatus.BAD_REQUEST);
            }
        }

我的application.java:我也尝试使用bean CorsFilter,我也尝试使用@CrossOrigin,但我仍然无法战胜这个邪恶的401,我确实理解为什么spring会说@CrossOrigin,当它甚至不工作时,它是直接向前的,spring框架给人们的虚假信息是怎么回事,因为老实说,@CrossOrigin,只是应该直接工作,这个安全特性真糟糕!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

@SpringBootApplication
@EnableJpaRepositories("com.mycompany.Product.repositories")
public class ProductApplication {

@Bean
public FilterRegistrationBean processCorsFilter(){

UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();

config.setAllowCredentials(true);
config.addAllowedOrigin("*");             
config.addAllowedHeader("*");
config.addAllowedMethod("*");

source.registerCorsConfiguration("/**", config);                      
FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
bean.setOrder(0);

return bean;

}

/*
    @Bean
    CorsConfigurationSource corsConfiguarationSource(){

        CorsConfiguration configurations = new CorsConfiguration();

        configurations.setAllowedOrigins(Arrays.asList("*"));
        configurations.setAllowCredentials(true);
        configurations.setAllowedHeaders(Arrays.asList("Allow-Control-Allow-Headers","Allow-Control-Allow-Origin","Access-Control-Request-Method","Allow-Control-Request-Headers","Origin","Cache-Origin","Content-Type", "Authorization"));
        configurations.setAllowedMethods(Arrays.asList("DELETE","GET","POST","PATCH","PUT"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configurations);
        return  source;
    }
    /*
    @Bean
    public WebMvcConfigurer corsConfigurer(){

        return new WebMvcConfigurerAdapter(){        
            public void addCorsMappings(CorsRegistry registry){
                registry.addMapping("/client").allowedOrigins("http://localhost:3000");
            }
        };
    }*/

应用程序属性文件:

server.port = 8009
spring.datasource.url = jdbc:mysql://localhost:3306/javaumsdb?useSSL=false
spring.datasource.username = root
spring.datasource.password = 
spring.datasource.driver-class-name=com.mysql.jdbc.Driver


spring.jpa.properties.dialect = org.hibernate.dialect.MySQL5Dialect
spring.jpa.hibernate.ddl-auto = none
spring.jpa.show-sql=true
spring.datasource.name=javaumsdb
spring.datasource.validationQuery = SELECT 1
spring.datasource.whileIdle = true
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy


security.basic.enabled =false
management.security.enabled = false

POM文件,也许我的spring版本与@CrossOrigin不兼容:我真的不明白为什么这个错误不会消失...

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.springframework</groupId>
    <artifactId>gs-rest-service-cors</artifactId>
    <version>0.1.0</version>

    <name>Product</name>
    <description> project for Spring Boot</description>
        <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <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>
                                <!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
                <dependency>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-core</artifactId>
                    <version>5.0.8.RELEASE</version>
                </dependency>

                 <dependency>
                       <groupId>com.transactioncompany</groupId>
                       <artifactId>cors-filter</artifactId>
                       <version>2.1.2</version>
                </dependency>
                <dependency>
                       <groupId>com.transactioncompany</groupId>
                       <artifactId>java-property-utils</artifactId>
                       <version>1.9.1</version>
                </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-neo4j</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-integration</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency> 
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
        </dependency>

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
                <dependency>
                        <groupId>org.hibernate</groupId>
                        <artifactId>hibernate-entitymanager</artifactId>
                        <version>5.2.3.Final</version>
                </dependency>
                <dependency>
                        <groupId>org.hibernate</groupId>
                        <artifactId>hibernate-core</artifactId>
                        <version>5.2.17.Final</version>
                </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>io.projectreactor</groupId>
            <artifactId>reactor-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
                <dependency>
                        <groupId>org.codehaus.plexus</groupId>
                        <artifactId>plexus</artifactId>
                        <version>3.3.1</version>
                </dependency>
                <!-- https://mvnrepository.com/artifact/org.codehaus.plexus/plexus-utils -->
                <dependency>
                        <groupId>org.codehaus.plexus</groupId>
                        <artifactId>plexus-utils</artifactId>
                        <version>3.1.0</version>
                </dependency>

                <!-- https://mvnrepository.com/artifact/org.codehaus.mojo/exec-maven-plugin -->
                <dependency>
                        <groupId>org.codehaus.mojo</groupId>
                        <artifactId>exec-maven-plugin</artifactId>
                        <version>1.6.0</version>
                </dependency>

               <!-- <dependency>
                    <artifactId>gwt-maven-plugin</artifactId>
                    <groupId>org.codehaus.mojo</groupId>
                    <version>1.3.1</version>
                </dependency> -->
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
                        <plugin>
                                <groupId>org.codehaus.mojo</groupId>
                                <artifactId>exec-maven-plugin</artifactId>
                        </plugin>
        </plugins>
    </build>
</project>

共有1个答案

陶唯
2023-03-14

您是否提供了WebMVCConfigurer的实现。请创建这个配置类&尝试。

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

@Override
public void addCorsMappings(CorsRegistry registry) {
   registry.addMapping("/**").allowedMethods("HEAD", "GET", "PUT", "POST", "DELETE", 
"PATCH");
  }
}
 类似资料:
  • 我们正在使用AWS Lambda授权器和API网关来保护我们的下游API。 下面是我们基于Java的lambda授权程序的代码片段 我们需要401(“未经授权”)作为一个回应,有人能请帮助如何做这一点吗?我们有用Java编写的lambda授权器。

  • 只要我的antMatcher上有.permitall(),这就可以很好地工作,但是当我试图保护它以便只有管理员才能进行该调用时(DB中的管理员角色是ROLE_ADMIN),它会返回401未经授权的访问,并且没有消息。我试过了 .hasRole(“admin”) .hasRole(“role_admin”) .hasAuthority(“admin”) .hasAuthority(“role_adm

  • 我的代码:GoogleCredential凭据 credential.refreshToken() 错误日志: 创建服务号的步骤: 我在凭据中的oauth 2.0中创建了一个Web应用程序 然后我用客户端ID创建了一个服务号 现在我正在使用这个服务号和从它生成的p12证书来验证和创建Google凭据的对象 一旦刷新令牌,我就给了我401例外。 在这种情况下,任何帮助都会受到感激

  • 尝试使用EWS连接到exchange 2010 SP1 它连接到我的本地邮箱,而不是“测试邮箱”。我从我们的管理员那里获得了TestMailbox NT帐户的密码,并尝试了以下所有方法: 所有这些都失败了。假设我在本地网络上的NT用户名是“用户”,我甚至尝试过: 它失败了。我一直在使用以下链接作为参考。 编辑1:我已经尝试了以上所有与网络信用而不是网络信用,它仍然失败。

  • 我正试图连接到google Contacts api以访问保存在google中的联系人/联系人,但它抛出了一个TokenResponseException:401 Unauthorized。我对谷歌Oauth2有些陌生。0.我已按要求将服务帐户密钥文件下载到我的项目根目录。 代码如下: 但是,会引发以下异常: 通用域名格式。谷歌。应用程序编程接口。客户啊。oauth2。TokenResponseE

  • 我想使用爪哇谷歌驱动器API。我尝试了这段代码: 但是我得到了这个错误: 我使用以下配置: 你能告诉我怎么解决这个问题吗?