Я пытаюсь реализовать OAuth2 AuthorizationServer, как описано в этом статья, но я продолжаю получать сообщение об ошибке ниже. Для весенней конфигурации безопасности:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
@Configuration
@Order(1)
class SecurityConfig extends WebSecurityConfigurerAdapter {
@Value("${user.oauth.user.username}")
private String username;
@Value("${user.oauth.user.password}")
private String password;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.requestMatchers()
.antMatchers("/login", "/oauth/authorize")
.and()
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin().permitAll();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser(username)
.password(passwordEncoder().encode(password))
.roles("USER");
}
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
Я продолжаю получать эту ошибку:
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.0:compile (default-compile) on project auth-service: Compilation failure
[ERROR] /home/mcs/auth-service/src/main/java/com/example/authservice/config/SecurityConfig.java:[14,1] cannot access javax.servlet.Filter
[ERROR] class file for javax.servlet.Filter not found
Что это значит и что кажется неправильным?
Мой pom.xml сгенерировал форму start.spring.io с использованием последней версии M2 для Spring Boot:
<?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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.0.M2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>auth-service</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>auth-service</name>
<description>Authorization service</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>com.okta.spring</groupId>
<artifactId>okta-spring-boot-starter</artifactId>
<version>1.1.0</version>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<version>2.3.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>2.6.7</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
</pluginRepository>
</pluginRepositories>
</project>




Проверьте дерево иерархии зависимостей. Содержит ли он javax servlet api. Если нет, выберите соответствующую версию здесь https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api
и добавьте его в свой pom.xml
В статье, которой вы поделились, вас просят добавить веб-зависимость, которую я не вижу в вашем файле pom.xml. Добавьте приведенную ниже зависимость, которая должна устранить ошибку javax.servlet.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
Если вы проверите файл pom spring-boot-starter-web, вы увидите зависимость от javax.servlet-api - 3.1.0.
Посмотрите на версию API сервлета, от которой зависит Spring, а затем в Gradle включите:
compileOnly("javax.servlet:javax.servlet-api:X")
Где X — версия servlet-api, от которой зависит Spring.
Я столкнулся с той же проблемой, но исправлен после добавления зависимости spring-boot-starter-web
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.4.2</version>
</dependency>
это исправило это странное сообщение об ошибке для меня ??
Хотя это другая проблема, она имеет то же сообщение об ошибке, поэтому, если вы попали сюда и пытались заставить WebFlux работать, и вы видите эту ошибку
public class PreAuthorizeSecurityConfigAdapter extends WebSecurityConfigurerAdapter {
^
class file for javax.servlet.Filter not found
Вероятно, WebFlux не поддерживает ваш вариант использования. Я пытался получить @PreAuthorize(hasPermission(...)), но после долгих поисков в Google обнаружил, что WebFlux не поддерживает его, и вместо этого вы должны просто использовать свой собственный bean-компонент:
@PreAuthorize("@somePermissionEvaluatorBean.hasPermission(authentication, ...")