Аутентификация Spring Boot JWT: конечные точки доступны с помощью PermitAll, но другие приводят к 403, запрещенному даже ⇐ JAVA
Аутентификация Spring Boot JWT: конечные точки доступны с помощью PermitAll, но другие приводят к 403, запрещенному даже
To implement this, I've marked the open endpoints with permitAll, allowing access without authentication. However, when attempting to access the endpoints requiring authentication, even with a valid token, I consistently receive a 403 Forbidden response.
JwtAuthorizationFilter Class
@Component public class JwtAuthorizationFilter extends OncePerRequestFilter { private final JwtUtil jwtUtil; private final ObjectMapper mapper; public JwtAuthorizationFilter(JwtUtil jwtUtil, ObjectMapper mapper) { this.jwtUtil = jwtUtil; this.mapper = mapper; } @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException { Map errorDetails = new HashMap(); System.out.println("Filtering internal start"); try { String accessToken = jwtUtil.resolveToken(request); if (accessToken == null ) { filterChain.doFilter(request, response); return; } System.out.println("token : "+accessToken); Claims claims = jwtUtil.resolveClaims(request); if(claims != null && jwtUtil.validateClaims(claims)){ String email = claims.getSubject(); //List roles = jwtUtil.getRoles(claims); //List authorities = roles.stream().map(e-> new SimpleGrantedAuthority(e)).toList(); var authentication = new UsernamePasswordAuthenticationToken(email,""); authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); SecurityContextHolder.getContext().setAuthentication(authentication); System.out.println(authentication.getDetails()); } }catch (Exception e){ System.out.println(e.getMessage()); errorDetails.put("message", "Authentication Error"); errorDetails.put("details",e.getMessage()); response.setStatus(HttpStatus.FORBIDDEN.value()); response.setContentType(MediaType.APPLICATION_JSON_VALUE); mapper.writeValue(response.getWriter(), errorDetails); response.getWriter().flush(); } filterChain.doFilter(request, response); } } securityFilterChain Class
@Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { System.out.println("SecurityFilterChain"); http.csrf(AbstractHttpConfigurer::disable); http.cors(corsConfig->corsConfig.configurationSource(getConfigurationSource())); http .authorizeHttpRequests(request -> { request.requestMatchers( new AntPathRequestMatcher("/log") ).permitAll() .requestMatchers( new AntPathRequestMatcher("/h2-console/") ).permitAll() .requestMatchers( new AntPathRequestMatcher("/") ).authenticated(); }) .addFilterBefore(jwtAuthorizationFilter, UsernamePasswordAuthenticationFilter.class); http.csrf((csrf) -> csrf.ignoringRequestMatchers( new AntPathRequestMatcher("/h2-console/**") ).csrfTokenRepository( CookieCsrfTokenRepository.withHttpOnlyFalse() ) ); http.csrf((csrf) -> csrf.ignoringRequestMatchers( new AntPathRequestMatcher("/log") ).csrfTokenRepository( CookieCsrfTokenRepository.withHttpOnlyFalse() ) ); http.headers((headers) -> headers .frameOptions( HeadersConfigurer.FrameOptionsConfig::disable ) ); return http.build(); } I would appreciate any help to resolve this, as I've been trying multiple ways already and couldn't find a solution.
Latest Update
I added the role "USER". When there's a user role incorporated in the token, then I am able to call the other endpoints that require authentication. At this time the below code is used to check the role.
.requestMatchers(new AntPathRequestMatcher("/**")).hasAuthority("USER"); Is it necessary to always incorporate the role along with the token in spring security. Isn't it possible to use the token without incorporating the role within it?
Also if there's any other better solution please share!
Источник: https://stackoverflow.com/questions/781 ... but-others
To implement this, I've marked the open endpoints with permitAll, allowing access without authentication. However, when attempting to access the endpoints requiring authentication, even with a valid token, I consistently receive a 403 Forbidden response.
JwtAuthorizationFilter Class
@Component public class JwtAuthorizationFilter extends OncePerRequestFilter { private final JwtUtil jwtUtil; private final ObjectMapper mapper; public JwtAuthorizationFilter(JwtUtil jwtUtil, ObjectMapper mapper) { this.jwtUtil = jwtUtil; this.mapper = mapper; } @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException { Map errorDetails = new HashMap(); System.out.println("Filtering internal start"); try { String accessToken = jwtUtil.resolveToken(request); if (accessToken == null ) { filterChain.doFilter(request, response); return; } System.out.println("token : "+accessToken); Claims claims = jwtUtil.resolveClaims(request); if(claims != null && jwtUtil.validateClaims(claims)){ String email = claims.getSubject(); //List roles = jwtUtil.getRoles(claims); //List authorities = roles.stream().map(e-> new SimpleGrantedAuthority(e)).toList(); var authentication = new UsernamePasswordAuthenticationToken(email,""); authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); SecurityContextHolder.getContext().setAuthentication(authentication); System.out.println(authentication.getDetails()); } }catch (Exception e){ System.out.println(e.getMessage()); errorDetails.put("message", "Authentication Error"); errorDetails.put("details",e.getMessage()); response.setStatus(HttpStatus.FORBIDDEN.value()); response.setContentType(MediaType.APPLICATION_JSON_VALUE); mapper.writeValue(response.getWriter(), errorDetails); response.getWriter().flush(); } filterChain.doFilter(request, response); } } securityFilterChain Class
@Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { System.out.println("SecurityFilterChain"); http.csrf(AbstractHttpConfigurer::disable); http.cors(corsConfig->corsConfig.configurationSource(getConfigurationSource())); http .authorizeHttpRequests(request -> { request.requestMatchers( new AntPathRequestMatcher("/log") ).permitAll() .requestMatchers( new AntPathRequestMatcher("/h2-console/") ).permitAll() .requestMatchers( new AntPathRequestMatcher("/") ).authenticated(); }) .addFilterBefore(jwtAuthorizationFilter, UsernamePasswordAuthenticationFilter.class); http.csrf((csrf) -> csrf.ignoringRequestMatchers( new AntPathRequestMatcher("/h2-console/**") ).csrfTokenRepository( CookieCsrfTokenRepository.withHttpOnlyFalse() ) ); http.csrf((csrf) -> csrf.ignoringRequestMatchers( new AntPathRequestMatcher("/log") ).csrfTokenRepository( CookieCsrfTokenRepository.withHttpOnlyFalse() ) ); http.headers((headers) -> headers .frameOptions( HeadersConfigurer.FrameOptionsConfig::disable ) ); return http.build(); } I would appreciate any help to resolve this, as I've been trying multiple ways already and couldn't find a solution.
Latest Update
I added the role "USER". When there's a user role incorporated in the token, then I am able to call the other endpoints that require authentication. At this time the below code is used to check the role.
.requestMatchers(new AntPathRequestMatcher("/**")).hasAuthority("USER"); Is it necessary to always incorporate the role along with the token in spring security. Isn't it possible to use the token without incorporating the role within it?
Also if there's any other better solution please share!
Источник: https://stackoverflow.com/questions/781 ... but-others
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Почему Spring Boot возвращает 403 при POST, когда используется PermitAll?
Anonymous » » в форуме JAVA - 0 Ответы
- 26 Просмотры
-
Последнее сообщение Anonymous
-
-
-
Конечные точки доступны даже после того, как их прокомментировали [закрыто]
Anonymous » » в форуме Python - 0 Ответы
- 2 Просмотры
-
Последнее сообщение Anonymous
-
-
-
IntelliJ Idea Идея конечные точки с переменным путем в инструменте «Конечные точки»
Anonymous » » в форуме JAVA - 0 Ответы
- 9 Просмотры
-
Последнее сообщение Anonymous
-