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

Sample project on how to implement JWT security based using Spring boot 3 and Spring security 6
https://aliboucoding.com/p/securing-your-spring-boot-3-0-applications-with-json-web-tokens-jwt
Apache License 2.0
1.86k stars 870 forks source link

ERROR 403 ON AUTHENTICATION #12

Open troemmanuel opened 1 year ago

troemmanuel commented 1 year ago

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

Need help plz.

RaCode75 commented 1 year ago

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 https://github.com/ali-bouali/spring-boot-3-jwt-security/issues/12, or unsubscribe https://github.com/notifications/unsubscribe-auth/AU4KTQNAMEFJG4UFNXE2IITWXERXDANCNFSM6AAAAAAUZPDKRM . You are receiving this because you are subscribed to this thread.Message ID: @.***>

troemmanuel commented 1 year ago

I fix my problem. The account was blocked.

eleazardasilva commented 1 year ago

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

eleazardasilva commented 1 year ago

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

troemmanuel commented 1 year ago

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

Yes That's. Happy Coding !

HARSHA95336 commented 1 year ago

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

HARSHA95336 commented 1 year ago

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

HARSHA95336 commented 1 year ago

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?

jemmalmohamed commented 1 year ago

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

wilferraciolli commented 1 year ago

I have an issue where everythinf is returning a 403

ertbil commented 1 year ago

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);

}

}

`

jekoyjake commented 1 year ago

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