ali-bouali / spring-boot-3-jwt-security

Sample project on how to implement JWT security based using Spring boot 3 and Spring security 6

Home Page:https://aliboucoding.com/p/securing-your-spring-boot-3-0-applications-with-json-web-tokens-jwt

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

ERROR 403 ON AUTHENTICATION

troemmanuel opened this issue · comments

commented

I have a forbidden ressource error when I try to authenticate.
But registration work properly.

Need help plz.

commented

I fix my problem.
The account was blocked.

Hi, I have the same problem. 403 on authentication.
What do you mean with "account was blocked"?

Ok, figured it out. UserDetails overriden methods where setting the account indicators to false.

commented

Ok, figured it out. UserDetails overriden methods where setting the account indicators to false.

Yes That's.
Happy Coding !

even i also have same problem registerrequest is working fine but authentication is not working could anyone please help me out

Ok, figured it out. UserDetails overriden methods where setting the account indicators to false.

Yes That's. Happy Coding !

i have the same issue plz help me out where i need to make changes in the code

Hi, I have the same problem. I have athentication but when try to acces to the bd return 403 error. El dom, 12 de feb. de 2023 15:12, TRO KOPE EMMANUEL JUNIOR < @.> escribió:

I have a forbidden ressource error when I try to authenticate. But registration work properly. Need help plz. — Reply to this email directly, view it on GitHub <#12>, or unsubscribe https://github.com/notifications/unsubscribe-auth/AU4KTQNAMEFJG4UFNXE2IITWXERXDANCNFSM6AAAAAAUZPDKRM . You are receiving this because you are subscribed to this thread.Message ID: @.
>

bro whether your issue resolved?

i have the same issue plz help me out where i need to make changes in the code

I have an issue where everythinf is returning a 403

I got 403 problems too, but my problem's difference is 403 on "http://localhost:7001/api/v1/auth/register" but another controller link "http://localhost:7001/api/v1/places" succeed

My Security Config
`
package com.example.treavelAppback.config;
import com.example.treavelAppback.consts.strings.Paths;
import com.example.treavelAppback.filters.JWTAuthFilter;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@configuration
@EnableWebSecurity
@requiredargsconstructor
public class SecurityConfig {

private final JWTAuthFilter jwtAuthFilter;
private final AuthenticationProvider authenticationProvider;


@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http.csrf()
            .disable()
            .authorizeHttpRequests()
            .requestMatchers(
                    Paths.whiteListedRoutes

            )
            .permitAll()
            .anyRequest()
            .authenticated()
            .and()
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .authenticationProvider(authenticationProvider)
            .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class);

    return http.build();
}

}
`

My JWT Authfilter
`
package com.example.treavelAppback.filters;
import com.example.treavelAppback.consts.strings.ErrorInfo;
import com.example.treavelAppback.consts.strings.Paths;
import com.example.treavelAppback.service.JWTService;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import lombok.NonNull;
import lombok.RequiredArgsConstructor;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;

import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Arrays;

@component
@requiredargsconstructor
public class JWTAuthFilter extends OncePerRequestFilter {

private final JWTService jwtService;
private final UserDetailsService userDetailsService;

@Override
protected void doFilterInternal(@NonNull HttpServletRequest request,
                                @NonNull HttpServletResponse response,
                                @NonNull FilterChain filterChain
) throws ServletException, IOException {


    final String authHeader = request.getHeader("Authorization");
    final String jwt;
    final String username;

    if (Arrays.asList(Paths.whiteListedRoutes).contains(request.getServletPath()) ||
            authHeader == null ||
            !authHeader.startsWith("Bearer ")) {

        filterChain.doFilter(request, response);
        return;
    }
    jwt = authHeader.substring(7);
    username = jwtService.extractUsername(jwt);

    if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
        UserDetails user = this.userDetailsService.loadUserByUsername(username);
        if (jwtService.isTokenValid(jwt, user)) {
            UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
                    user,
                    null
                    , user.getAuthorities()
            );

            authToken.setDetails(
                    new WebAuthenticationDetailsSource().buildDetails(request)
            );

            SecurityContextHolder.getContext().setAuthentication(authToken);
        } else {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, ErrorInfo.inValidToken + " " + username);

        }
    } else {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, ErrorInfo.inValidToken + " " + username);
    }

    filterChain.doFilter(request, response);

}

}

`

if you are having this issue. dont forget the @NoArgsConstructor and @Allaargsconstructor of user model. my issue solved. or you may use try and catch in athenticate im auth service