Приложение Spring работает в IntelliJ IDE, но не в папке веб-приложений Tomcat.JAVA

Программисты JAVA общаются здесь
Ответить
Anonymous
 Приложение Spring работает в IntelliJ IDE, но не в папке веб-приложений Tomcat.

Сообщение Anonymous »

Мой код работает, когда я обычно запускаю его в IntelliJ IDE с предоставленным весной сервером Tomcat на 8080. Но когда я меняю файл pom.xml, чтобы создать файл WAR, и загружаю его на свой локальный сервер Tomcat, на который я изменил его. порт 8081. Он просто показывает код 403 для простейшего API, который даже не имеет безопасности.
Файл WAR успешно создается, а также загружается через приложение Tomcat Manager.
/>
Я изменил имя файла WAR на «logindemo».
Когда я развертываю свой файл WAR в веб-приложениях Tomcat, я запускаю этот URL-адрес в почтальоне с помощью GET: -

http://localhost:8081/logindemo/auth/welcome
Ниже приведен мой файл pom.xml, который я использую для создания файла WAR. & l t ; p r o j e c t x m l n s = & q u o t ; h t t p : / / m a v e n . a p a c h e . o r g / P O M / 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">
4.0.0

org.springframework.boot
spring-boot-starter-parent
3.0.8



com.gfg
springboot3-security
0.0.1-SNAPSHOT
springboot3-security
Demo project for Spring Boot 3 Security


17
0.11.5




org.springframework.boot
spring-boot-starter-data-jpa


org.springframework.boot
spring-boot-starter-security


org.springframework.boot
spring-boot-starter-web


org.springframework.boot
spring-boot-starter-tomcat
provided


com.mysql
mysql-connector-j
runtime


org.projectlombok
lombok
true


org.springframework.boot
spring-boot-starter-test
test


org.springframework.security
spring-security-test
test


io.jsonwebtoken
jjwt-api
${jjwt.version}


io.jsonwebtoken
jjwt-impl
${jjwt.version}


io.jsonwebtoken
jjwt-jackson
${jjwt.version}



war



org.springframework.boot
spring-boot-maven-plugin



org.projectlombok
lombok








Ниже приведен мой SecurityConfig.java
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig {

@Autowired
private JwtAuthFilter authFilter;

@Bean
public UserDetailsService userDetailsService() {
return new UserInfoService(); // Ensure UserInfoService implements UserDetailsService
}

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf(csrf -> csrf.disable()) // Disable CSRF for stateless APIs
.authorizeHttpRequests(auth -> auth
.requestMatchers("/auth/welcome", "/auth/addNewUser", "/auth/generateToken").permitAll()
.requestMatchers("/auth/user/**").hasAuthority("ROLE_USER")
.requestMatchers("/auth/admin/**").hasAuthority("ROLE_ADMIN")
.anyRequest().authenticated() // Protect all other endpoints
)
.sessionManagement(sess -> sess
.sessionCreationPolicy(SessionCreationPolicy.STATELESS) // No sessions
)
.authenticationProvider(authenticationProvider()) // Custom authentication provider
.addFilterBefore(authFilter, UsernamePasswordAuthenticationFilter.class); // Add JWT filter

return http.build();
}

@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(); // Password encoding
}

@Bean
public AuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
authenticationProvider.setUserDetailsService(userDetailsService());
authenticationProvider.setPasswordEncoder(passwordEncoder());
return authenticationProvider;
}

@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception {
return config.getAuthenticationManager();
}
}

Ниже мой контроллер
@RestController
@RequestMapping("/auth")
public class UserController {

@Autowired
private UserInfoService service;

@Autowired
private JwtService jwtService;

@Autowired
private AuthenticationManager authenticationManager;

@GetMapping("/welcome")
public String welcome() {
return "Welcome this endpoint is not secure";
}

@PostMapping("/addNewUser")
public String addNewUser(@RequestBody UserInfo userInfo) {
return service.addUser(userInfo);
}

@GetMapping("/user/userProfile")
@PreAuthorize("hasAuthority('ROLE_USER')")
public String userProfile() {
return "Welcome to User Profile";
}

@GetMapping("/admin/adminProfile")
@PreAuthorize("hasAuthority('ROLE_ADMIN')")
public String adminProfile() {
return "Welcome to Admin Profile";
}

@PostMapping("/generateToken")
public String authenticateAndGetToken(@RequestBody AuthRequest authRequest) {

Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(authRequest.getUsername(), authRequest.getPassword())
);
if (authentication.isAuthenticated()) {
return jwtService.generateToken(authRequest.getUsername());
} else {
throw new UsernameNotFoundException("Invalid user request!");
}
}
}

Ниже мой LoginApplication.java
@SpringBootApplication
public class LoginApplication extends SpringBootServletInitializer {

public static void main(String[] args) {
SpringApplication.run(LoginApplication.class, args);
}
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(LoginApplication.class);
}
}


Подробнее здесь: https://stackoverflow.com/questions/791 ... -of-tomcat
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «JAVA»