Программисты JAVA общаются здесь
Anonymous
Java.lang.StackOverflowError] с основной причиной [закрыто]
Сообщение
Anonymous » 19 апр 2024, 08:44
Когда я указываю адрес электронной почты и пароль для получения токена jwt в почтальоне, я получаю эту ошибку.
Servlet.service() для сервлета [dispatcherServlet] в контексте с путем [] бросил исключение [Ошибка отправки обработчика; вложенное исключение - java.lang.StackOverflowError] с основной причиной.
МОЖЕТ МНЕ ПОМОЧЬ.
CustomUserDetailService < /p>
Код: Выделить всё
package com.example.backend.Config;
import com.example.backend.Exception.ResourceNotFoundException;
import com.example.backend.Model.User;
import com.example.backend.Repositary.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
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;
@Service
public class CustomUserDetailService implements UserDetailsService{
@Autowired
private UserRepository userRepo;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = this.userRepo.findByEmail(username).orElseThrow(()->new ResourceNotFoundException("User Not Found"));
return user;
}
}
Конфигурация безопасности
Код: Выделить всё
package com.example.backend.Config;
import com.example.backend.Security.JwtAuthenticationEntryPoint;
import com.example.backend.Security.JwtAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.*;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private CustomUserDetailService customUserDetailsService;
public static String[] PUBLIC_URL= {"/auth/login"};
@Autowired
private JwtAuthenticationFilter filter;
@Autowired
private JwtAuthenticationEntryPoint entryPoint;
@Autowired
private UserDetailsService userDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf()
.disable()
.authorizeRequests()
.antMatchers(PUBLIC_URL).permitAll()
.anyRequest()
.authenticated()
.and()
//.httpBasic();
.exceptionHandling()
.authenticationEntryPoint(entryPoint)
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.addFilterBefore(filter, UsernamePasswordAuthenticationFilter.class);
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(this.customUserDetailsService).passwordEncoder(this.PasswordEncoder());
}
@Bean
@Override
protected AuthenticationManager authenticationManager() throws Exception {
return super.authenticationManager();
}
@Bean
public PasswordEncoder PasswordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public FilterRegistrationBean cosFilter() {
UrlBasedCorsConfigurationSource source=new UrlBasedCorsConfigurationSource();
CorsConfiguration configuration=new CorsConfiguration();
configuration.setAllowCredentials(true);
configuration.addAllowedOriginPattern("*");
configuration.addAllowedHeader("Authorization");
configuration.addAllowedHeader("Context-Type");
configuration.addAllowedHeader("Accept");
configuration.addAllowedMethod("POST");
configuration.addAllowedMethod("GET");
configuration.addAllowedMethod("PUT");
configuration.addAllowedMethod("DELETE");
configuration.addAllowedMethod("OPTIONS");
configuration.setMaxAge(3600L);
source.registerCorsConfiguration("/**",configuration);
FilterRegistrationBean bean= new FilterRegistrationBean(new org.springframework.web.filter.CorsFilter(source));
bean.setOrder(-110);
return bean;
}
}
Контроллер аутентификации
Код: Выделить всё
package com.example.backend.Controller;
import com.example.backend.Exception.ResourceNotFoundException;
import com.example.backend.Payload.JwtRequest;
import com.example.backend.Payload.JwtResponse;
import com.example.backend.Payload.UserDto;
import com.example.backend.Security.JwtHelper;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/auth")
public class AuthController {
@Autowired
private AuthenticationManager manager;
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private JwtHelper helper;
@Autowired
private ModelMapper mapper;
@PostMapping("/login")
public ResponseEntity login(@RequestBody JwtRequest request){
this.authenticateUser(request.getUsername(), request.getPassword());
UserDetails userDetails = this.userDetailsService.loadUserByUsername(request.getUsername());
String token = this.helper.generateToken(userDetails);
JwtResponse response = new JwtResponse();
response.setToken(token);
response.setUser(String.valueOf(this.mapper.map(userDetails, UserDto.class)));
return new ResponseEntity(response, HttpStatus.ACCEPTED);
}
private void authenticateUser(String username, String password){
try {
manager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
} catch (BadCredentialsException e){
throw new ResourceNotFoundException("Invalid username or password");
}catch (DisabledException e){
throw new ResourceNotFoundException("User is not active ");
}
}
}
Пользователь
Код: Выделить всё
`package com.example.backend.Model;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import javax.persistence.*;
import java.util.*;
import java.util.stream.Collectors;
@Entity
@Data
@Table(name="User_info")
public class User implements UserDetails {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long userId;
@Column(nullable = false)
private String Name;
@Column(unique = true, nullable = false)
private String email;
@Column(nullable = false)
private String password;
@Column(nullable = false)
private String address;
@Column(nullable = false)
private String gender;
@Column(nullable = false,length = 10)
private String phone;
@Column(name = "CreateAt")
private Date date;
@ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
Set role = new HashSet();
//
@Override
public Collection
Подробнее здесь: [url]https://stackoverflow.com/questions/78351542/java-lang-stackoverflowerror-with-root-cause[/url]
1713505449
Anonymous
Когда я указываю адрес электронной почты и пароль для получения токена jwt в почтальоне, я получаю эту ошибку. Servlet.service() для сервлета [dispatcherServlet] в контексте с путем [] бросил исключение [Ошибка отправки обработчика; вложенное исключение - java.lang.StackOverflowError] с основной причиной. МОЖЕТ МНЕ ПОМОЧЬ. [b]CustomUserDetailService[/b]< /p> [code]package com.example.backend.Config; import com.example.backend.Exception.ResourceNotFoundException; import com.example.backend.Model.User; import com.example.backend.Repositary.UserRepository; import org.springframework.beans.factory.annotation.Autowired; 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; @Service public class CustomUserDetailService implements UserDetailsService{ @Autowired private UserRepository userRepo; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { User user = this.userRepo.findByEmail(username).orElseThrow(()->new ResourceNotFoundException("User Not Found")); return user; } } [/code] [b]Конфигурация безопасности[/b] [code]package com.example.backend.Config; import com.example.backend.Security.JwtAuthenticationEntryPoint; import com.example.backend.Security.JwtAuthenticationFilter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.*; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private CustomUserDetailService customUserDetailsService; public static String[] PUBLIC_URL= {"/auth/login"}; @Autowired private JwtAuthenticationFilter filter; @Autowired private JwtAuthenticationEntryPoint entryPoint; @Autowired private UserDetailsService userDetailsService; @Override protected void configure(HttpSecurity http) throws Exception { http .csrf() .disable() .authorizeRequests() .antMatchers(PUBLIC_URL).permitAll() .anyRequest() .authenticated() .and() //.httpBasic(); .exceptionHandling() .authenticationEntryPoint(entryPoint) .and() .sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS); http.addFilterBefore(filter, UsernamePasswordAuthenticationFilter.class); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(this.customUserDetailsService).passwordEncoder(this.PasswordEncoder()); } @Bean @Override protected AuthenticationManager authenticationManager() throws Exception { return super.authenticationManager(); } @Bean public PasswordEncoder PasswordEncoder() { return new BCryptPasswordEncoder(); } @Bean public FilterRegistrationBean cosFilter() { UrlBasedCorsConfigurationSource source=new UrlBasedCorsConfigurationSource(); CorsConfiguration configuration=new CorsConfiguration(); configuration.setAllowCredentials(true); configuration.addAllowedOriginPattern("*"); configuration.addAllowedHeader("Authorization"); configuration.addAllowedHeader("Context-Type"); configuration.addAllowedHeader("Accept"); configuration.addAllowedMethod("POST"); configuration.addAllowedMethod("GET"); configuration.addAllowedMethod("PUT"); configuration.addAllowedMethod("DELETE"); configuration.addAllowedMethod("OPTIONS"); configuration.setMaxAge(3600L); source.registerCorsConfiguration("/**",configuration); FilterRegistrationBean bean= new FilterRegistrationBean(new org.springframework.web.filter.CorsFilter(source)); bean.setOrder(-110); return bean; } } [/code] [b]Контроллер аутентификации[/b] [code]package com.example.backend.Controller; import com.example.backend.Exception.ResourceNotFoundException; import com.example.backend.Payload.JwtRequest; import com.example.backend.Payload.JwtResponse; import com.example.backend.Payload.UserDto; import com.example.backend.Security.JwtHelper; import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.DisabledException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/auth") public class AuthController { @Autowired private AuthenticationManager manager; @Autowired private UserDetailsService userDetailsService; @Autowired private JwtHelper helper; @Autowired private ModelMapper mapper; @PostMapping("/login") public ResponseEntity login(@RequestBody JwtRequest request){ this.authenticateUser(request.getUsername(), request.getPassword()); UserDetails userDetails = this.userDetailsService.loadUserByUsername(request.getUsername()); String token = this.helper.generateToken(userDetails); JwtResponse response = new JwtResponse(); response.setToken(token); response.setUser(String.valueOf(this.mapper.map(userDetails, UserDto.class))); return new ResponseEntity(response, HttpStatus.ACCEPTED); } private void authenticateUser(String username, String password){ try { manager.authenticate(new UsernamePasswordAuthenticationToken(username, password)); } catch (BadCredentialsException e){ throw new ResourceNotFoundException("Invalid username or password"); }catch (DisabledException e){ throw new ResourceNotFoundException("User is not active "); } } } [/code] [b]Пользователь[/b] [code]`package com.example.backend.Model; import lombok.Data; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import javax.persistence.*; import java.util.*; import java.util.stream.Collectors; @Entity @Data @Table(name="User_info") public class User implements UserDetails { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE) private Long userId; @Column(nullable = false) private String Name; @Column(unique = true, nullable = false) private String email; @Column(nullable = false) private String password; @Column(nullable = false) private String address; @Column(nullable = false) private String gender; @Column(nullable = false,length = 10) private String phone; @Column(name = "CreateAt") private Date date; @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL) Set role = new HashSet(); // @Override public Collection Подробнее здесь: [url]https://stackoverflow.com/questions/78351542/java-lang-stackoverflowerror-with-root-cause[/url]
0 Ответы
93 Просмотры
Последнее сообщение Anonymous
21 окт 2023, 22:40
0 Ответы
44 Просмотры
Последнее сообщение Гость
30 апр 2024, 05:54
0 Ответы
51 Просмотры
Последнее сообщение Anonymous
10 мар 2025, 07:09
0 Ответы
20 Просмотры
Последнее сообщение Anonymous
15 окт 2024, 15:22
0 Ответы
39 Просмотры
Последнее сообщение Anonymous
22 окт 2024, 09:16