Ошибка 403 на конечной точке, которая не требует аутентификации на основе ролей, но требует аутентификации по токенуJAVA

Программисты JAVA общаются здесь
Ответить
Anonymous
 Ошибка 403 на конечной точке, которая не требует аутентификации на основе ролей, но требует аутентификации по токену

Сообщение Anonymous »

Я следую руководству по Spring Boot и застрял на этапе аутентификации. У меня есть класс фильтра безопасности JwtRequestFilter.java, который реализован в SecurityConfig.java непосредственно перед UsernamePasswordAuthenticationFilter.class, и я распечатал, неверна ли аутентификация пользователя или нет, но он работает и распечатывает аутентифицированного пользователя.
Но проблема в том, что когда я проверяю, работает ли аутентификация токена или нет, добавляя конечную точку "/test" в контроллере профиля, я получаю 403 запрещенная ошибка. Я проверяю в почтальоне, присоединяя авторизацию «Bearer oiewofj...» к конечной точке «/test». В чем может быть проблема?
Я также спросил ИИ, и хотя они предлагают мне добавить роли, и хотя я попробовал, как они предложили, это все равно не сработало.
JwtRequestFilter.java
@Component
@RequiredArgsConstructor
public class JwtRequestFilter extends OncePerRequestFilter {
private final UserDetailsService userDetailsService;
private final JwtUtil jwtUtil;

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
final String authHeader = request.getHeader("Authorization");

String email = null;
String jwt = null;

if (authHeader != null && authHeader.startsWith("Bearer ")) {
jwt = authHeader.substring(7);
email = jwtUtil.extractUsername(jwt);
}

if (email != null && SecurityContextHolder.getContext().getAuthentication() == null) {
UserDetails userDetails = this.userDetailsService.loadUserByUsername(email);
System.out.println("User: " + userDetails.toString());
if (jwtUtil.validateToken(jwt, userDetails)) {
System.out.println("Validated Token");
UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authToken);
System.out.println("[JwtFilter] Authentication set: " + SecurityContextHolder.getContext().getAuthentication());
}
}

filterChain.doFilter(request, response);
}
}

SecurityConfig.java
package react.moneymanager.config;

import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.Customizer;
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.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.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import react.moneymanager.security.JwtRequestFilter;

import java.util.List;

@Configuration
@RequiredArgsConstructor
public class SecurityConfig {

private final JwtRequestFilter jwtRequestFilter;

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
httpSecurity.cors(Customizer.withDefaults())
.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(
auth -> auth.requestMatchers(
"/status", "/health", "/register", "/activate", "/login"
)
.permitAll()
.anyRequest()
.authenticated()
)
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
return httpSecurity.build();
}

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

@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setAllowedOriginPatterns(List.of("*"));
corsConfiguration.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "OPTIONS"));
corsConfiguration.setAllowedHeaders(List.of("Authorization", "Content-Type", "Accept"));
corsConfiguration.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", corsConfiguration);
return source;
}

// AppUserDetailService will be automatically used
// as userDetailService of AuthenticationManager
// PasswordEncoder bean will also be used as the
// selected password encoder
@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration authConfig) throws Exception {
return authConfig.getAuthenticationManager();
}
}

AppUserDetailService.java
package react.moneymanager.service;

import lombok.RequiredArgsConstructor;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
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;
import react.moneymanager.entity.ProfileEntity;
import react.moneymanager.repository.ProfileRepository;

import java.util.Collections;

@Service
@RequiredArgsConstructor
public class AppUserDetailService implements UserDetailsService {
private final ProfileRepository profileRepository;

@Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
ProfileEntity profile = profileRepository.findByEmail(email).orElseThrow(
() -> new UsernameNotFoundException("User not found with the email + " + email
)
);
return User.builder()
.username(profile.getEmail())
.password(profile.getPassword())
.authorities(Collections.emptyList())
.build();
}
}


Подробнее здесь: https://stackoverflow.com/questions/797 ... -but-token
Ответить

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

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

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

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

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