Вызов исключения времени выполнения в SpringBoot вызывает исключение «Отказано в доступе»JAVA

Программисты JAVA общаются здесь
Ответить
Гость
 Вызов исключения времени выполнения в SpringBoot вызывает исключение «Отказано в доступе»

Сообщение Гость »


My springboot application (for blog) is using JWT method of authentication. When user tries to find a blog by the which doesn't exist in the repository, I am trying to throw a

Код: Выделить всё

NoSuchElementException

In BlogService:

Код: Выделить всё

    public BlogResponseDTO findBlogByPageId(String pageId) {         BlogEntity blogEntity = blogRepository.findByPageId(pageId);         if (blogEntity == null) {             throw new NoSuchElementException("Blog not found for pageId: " + pageId);         }         return buildBlogResponseDTO(blogEntity);     } 
But it throws

Код: Выделить всё

401 Unauthorized
error as a response.

WebSecurityConfig:

Код: Выделить всё

 //Imports import jakarta.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.annotation.Order; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration; 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.configurers.AbstractHttpConfigurer; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.authentication.Http403ForbiddenEntryPoint; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.web.multipart.support.MultipartFilter; import static org.springframework.security.config.Customizer.withDefaults; @Configuration @EnableWebSecurity public class WebSecurityConfig {     @Autowired     private CustomUserDetailsService userDetailsService;     @Autowired     private JwtRequestFilter jwtRequestFilter;     @Bean     public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {         http                 .authorizeHttpRequests((auth) -> auth                         .requestMatchers("/auth").permitAll()                         .anyRequest().authenticated()                 )                 .csrf(AbstractHttpConfigurer::disable)                 .httpBasic(withDefaults())                 .userDetailsService(userDetailsService)                 .sessionManagement(sess -> sess.sessionCreationPolicy(SessionCreationPolicy.STATELESS))                 .exceptionHandling(httpSecurityExceptionHandlingConfigurer -> {                     httpSecurityExceptionHandlingConfigurer.authenticationEntryPoint((request, response, authException) -> {                         response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);                         response.getWriter().write("Authentication failed: " + authException.getMessage());                     });                 });         http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);         return http.build();     }          @Bean     public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {         return authenticationConfiguration.getAuthenticationManager();     } } 
My application doesn't throw runtime errors from even though I try throwing it explicitly. Can someone help me with what am I missing? If you need any more details, please drop a comment.


Источник: https://stackoverflow.com/questions/781 ... -exception
Ответить

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

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

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

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

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