Spring Security 6.21版本403 fobiden错误

yx2lnoni  于 12个月前  发布在  Spring
关注(0)|答案(1)|浏览(182)
@Getter
@RequiredArgsConstructor
public enum Role {
   
    ROLE_USER("USER"),
    ROLE_COUNTRYMANEGER("COUNTRYMANEGER"),
    ROLE_AREAMANEGER("AREAMANEGER"),
    ROLE_ADMIN("ADMIN");

    private final String key;
   
}
@RestController
@RequiredArgsConstructor
public class UserController {

    private final UserService userService;

    @GetMapping("/modify/update")
    public GlobalDto<?> update(@AuthenticationPrincipal UserDetails userDetails) {
        return GlobalDto.res(HttpStatus.OK, userDetails.getUsername());
    }

    @PostMapping("/user/join")
    public GlobalDto<?> saveUser(@RequestBody UserRegisterDto registerDto) {
        return userService.saveUser(registerDto);
    }
    @PostMapping("/user/login")
    public GlobalDto<?> login(@RequestBody UserLoginDto loginRequest) {
       return userService.login(loginRequest);

    }
    @GetMapping("/cookie")
    public void yourEndpoint(HttpServletRequest request, @RequestHeader("Cookie") String cookie) {
        System.out.println("Cookies: " + cookie);
    }

}
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class securityConfig {
    @Bean
    @ConditionalOnProperty(name = "spring.h2.console.enabled",havingValue = "true")
    public WebSecurityCustomizer configureH2ConsoleEnable() {
        return web -> web.ignoring()
                .requestMatchers(PathRequest.toH2Console());
    }
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {

        http
                .csrf(csrf -> csrf.disable());

        http
                .authorizeHttpRequests((auth) -> auth
                        .requestMatchers(PathRequest.toH2Console()).permitAll()
                        .requestMatchers("/", "cookie", "/user/**").permitAll()
                        .requestMatchers("/modify/**").hasAnyRole("USER", "COUNTRYMANEGER", "AREAMANAGER", "ADMIN")
                        .requestMatchers("h2-console/**").permitAll()
                );
        http
                .securityContext((securityContext) -> securityContext
                        .securityContextRepository(new RequestAttributeSecurityContextRepository())
                );

        http
                .sessionManagement((auth) -> auth
                        .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
                );

        return http.build();
    }

    @Bean
    public AuthenticationManager authenticationManager(
            UserDetailsService userDetailsService,
            PasswordEncoder passwordEncoder) {
        DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
        authenticationProvider.setUserDetailsService(userDetailsService);
        authenticationProvider.setPasswordEncoder(passwordEncoder);

        return new ProviderManager(authenticationProvider);
    }

        @Bean
        public PasswordEncoder passwordEncoder () {
            return PasswordEncoderFactories.createDelegatingPasswordEncoder();
        }

    }
@Data
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@AllArgsConstructor
@Getter

public class CustomUserDetails implements UserDetails {

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority(users.getAuthority().getKey()));
        return authorities;
    }

    public String getUserId() {
        return users.getUserId();
    }

    @Override
    public String getPassword() {
        return users.getPassword();
    }

    @Override
    public String getUsername() {
        return users.getUserId();
    }

    private Users users;

    public Long getId() {
        return users.getId();
    }


    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
@Service
@AllArgsConstructor
public class UserService {
    private final UserRepository userRepository;
    private final CustomUserDetailsService customUserDetailsService;
    private final PasswordEncoder passwordEncoder;



    @Transactional
    public GlobalDto<?> saveUser(UserRegisterDto registerDto) {
        if (userRepository.existsByUserId(registerDto.getUserId())) {
            return GlobalDto.res(HttpStatus.BAD_REQUEST, "ID that exists
.");
        }
        Users users = Users.builder()
                .userId(registerDto.getUserId())
                .password(passwordEncoder.encode(registerDto.getPassword()))
                .name(registerDto.getName())
                .locationTag(registerDto.getLocationTag())
                .authority(Role.ROLE_USER)
                .build();
        userRepository.save(users);
        return GlobalDto.res(HttpStatus.OK, "join success");
    }

    @Transactional
    public GlobalDto<?> login(UserLoginDto loginDto) {
        try {
            UserDetails userDetails = customUserDetailsService.loadUserByUsername(loginDto.getUserId());

            if (!passwordEncoder.matches(loginDto.getPassword(), userDetails.getPassword())) {
                return GlobalDto.res(HttpStatus.BAD_REQUEST, "Password mismatch
");
            }

            Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authentication);

            return GlobalDto.res(HttpStatus.OK, "login success");
        } catch (UsernameNotFoundException e) {
            return GlobalDto.res(HttpStatus.BAD_REQUEST, "not found user.");
        } catch (Exception e) {
            return GlobalDto.res(HttpStatus.INTERNAL_SERVER_ERROR, "login error");
        }
    }
}

第一个月

2024-01-05T14:00:55.177+09:00 DEBUG 16940 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy        : Securing POST /user/join
2024-01-05T14:00:55.182+09:00 DEBUG 16940 --- [nio-8080-exec-1] o.s.s.w.a.AnonymousAuthenticationFilter  : Set SecurityContextHolder to anonymous SecurityContext
2024-01-05T14:00:55.182+09:00 DEBUG 16940 --- [nio-8080-exec-1] o.s.s.w.session.SessionManagementFilter  : Request requested invalid session id 304D6DC94BC6F98DD9EE189B781AC75B
2024-01-05T14:00:55.183+09:00 DEBUG 16940 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy        : Secured POST /user/join
2024-01-05T14:00:55.185+09:00 DEBUG 16940 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : POST "/user/join", parameters={}
2024-01-05T14:00:55.187+09:00 DEBUG 16940 --- [nio-8080-exec-1] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to com.example.mozosmartfarmbackend.controller.UserController#saveUser(UserRegisterDto)
2024-01-05T14:00:55.241+09:00 DEBUG 16940 --- [nio-8080-exec-1] m.m.a.RequestResponseBodyMethodProcessor : Read "application/json;charset=UTF-8" to [com.example.mozosmartfarmbackend.dto.request.UserRegisterDto@5b3956ec]
2024-01-05T14:00:55.321+09:00 DEBUG 16940 --- [nio-8080-exec-1] org.hibernate.SQL                        : select u1_0.id from users u1_0 where u1_0.user_id=? fetch first ? rows only
2024-01-05T14:00:55.424+09:00 DEBUG 16940 --- [nio-8080-exec-1] org.hibernate.SQL                        : insert into users (authority,location_tag,name,password,register_date,user_id,id) values (?,?,?,?,?,?,default)
2024-01-05T14:00:55.459+09:00 DEBUG 16940 --- [nio-8080-exec-1] m.m.a.RequestResponseBodyMethodProcessor : Using 'application/json', given [*/*] and supported [application/json, application/*+json]
2024-01-05T14:00:55.468+09:00 DEBUG 16940 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed 200 OK
2024-01-05T14:00:57.371+09:00 DEBUG 16940 --- [nio-8080-exec-4] o.s.security.web.FilterChainProxy        : Securing POST /user/login
2024-01-05T14:00:57.371+09:00 DEBUG 16940 --- [nio-8080-exec-4] o.s.s.w.a.AnonymousAuthenticationFilter  : Set SecurityContextHolder to anonymous SecurityContext
2024-01-05T14:00:57.371+09:00 DEBUG 16940 --- [nio-8080-exec-4] o.s.s.w.session.SessionManagementFilter  : Request requested invalid session id 304D6DC94BC6F98DD9EE189B781AC75B
2024-01-05T14:00:57.373+09:00 DEBUG 16940 --- [nio-8080-exec-4] o.s.security.web.FilterChainProxy        : Secured POST /user/login
2024-01-05T14:00:57.373+09:00 DEBUG 16940 --- [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet        : POST "/user/login", parameters={}
2024-01-05T14:00:57.373+09:00 DEBUG 16940 --- [nio-8080-exec-4] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to com.example.mozosmartfarmbackend.controller.LoginController#login(UserLoginDto, HttpServletRequest, HttpServletResponse)
2024-01-05T14:00:57.374+09:00 DEBUG 16940 --- [nio-8080-exec-4] m.m.a.RequestResponseBodyMethodProcessor : Read "application/json;charset=UTF-8" to [com.example.mozosmartfarmbackend.dto.request.UserLoginDto@23d1a764]
2024-01-05T14:00:57.446+09:00 DEBUG 16940 --- [nio-8080-exec-4] org.hibernate.SQL                        : select u1_0.id,u1_0.authority,u1_0.location_tag,u1_0.name,u1_0.password,u1_0.register_date,u1_0.user_id from users u1_0 where u1_0.user_id=?
2024-01-05T14:00:57.451+09:00 DEBUG 16940 --- [nio-8080-exec-4] org.hibernate.SQL                        : select u1_0.id,u1_0.authority,u1_0.location_tag,u1_0.name,u1_0.password,u1_0.register_date,u1_0.user_id from users u1_0 where u1_0.user_id=?
2024-01-05T14:00:57.516+09:00 DEBUG 16940 --- [nio-8080-exec-4] o.s.s.a.dao.DaoAuthenticationProvider    : Authenticated user
2024-01-05T14:00:57.545+09:00 DEBUG 16940 --- [nio-8080-exec-4] w.c.HttpSessionSecurityContextRepository : Stored SecurityContextImpl [Authentication=UsernamePasswordAuthenticationToken [Principal=com.example.mozosmartfarmbackend.entity.SecurityUsers [Username=aa1, Password=[PROTECTED], Enabled=true, AccountNonExpired=true, CredentialsNonExpired=true, AccountNonLocked=true, Granted Authorities=[USER]], Credentials=[PROTECTED], Authenticated=true, Details=WebAuthenticationDetails [RemoteIpAddress=0:0:0:0:0:0:0:1, SessionId=null], Granted Authorities=[USER]]] to HttpSession [org.apache.catalina.session.StandardSessionFacade@542b99d6]
2024-01-05T14:00:57.614+09:00 DEBUG 16940 --- [nio-8080-exec-4] org.hibernate.SQL                        : select u1_0.id,u1_0.authority,u1_0.location_tag,u1_0.name,u1_0.password,u1_0.register_date,u1_0.user_id from users u1_0 where u1_0.user_id=?
2024-01-05T14:00:57.616+09:00 DEBUG 16940 --- [nio-8080-exec-4] org.hibernate.SQL                        : select u1_0.id,u1_0.authority,u1_0.location_tag,u1_0.name,u1_0.password,u1_0.register_date,u1_0.user_id from users u1_0 where u1_0.user_id=?
2024-01-05T14:00:57.691+09:00 DEBUG 16940 --- [nio-8080-exec-4] o.s.s.a.dao.DaoAuthenticationProvider    : Authenticated user
2024-01-05T14:00:57.692+09:00 DEBUG 16940 --- [nio-8080-exec-4] w.c.HttpSessionSecurityContextRepository : Stored SecurityContextImpl [Authentication=UsernamePasswordAuthenticationToken [Principal=com.example.mozosmartfarmbackend.entity.SecurityUsers [Username=aa1, Password=[PROTECTED], Enabled=true, AccountNonExpired=true, CredentialsNonExpired=true, AccountNonLocked=true, Granted Authorities=[USER]], Credentials=[PROTECTED], Authenticated=true, Details=null, Granted Authorities=[USER]]] to HttpSession [org.apache.catalina.session.StandardSessionFacade@542b99d6]
2024-01-05T14:00:57.692+09:00 DEBUG 16940 --- [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet        : Completed 200 OK
2024-01-05T14:01:00.608+09:00 DEBUG 16940 --- [nio-8080-exec-3] o.s.security.web.FilterChainProxy        : Securing GET /modify/update
2024-01-05T14:01:00.609+09:00 DEBUG 16940 --- [nio-8080-exec-3] o.s.s.w.a.AnonymousAuthenticationFilter  : Set SecurityContextHolder to anonymous SecurityContext
2024-01-05T14:01:00.614+09:00 DEBUG 16940 --- [nio-8080-exec-3] o.s.s.w.s.HttpSessionRequestCache        : Saved request http://localhost:8080/modify/update?continue to session
2024-01-05T14:01:00.614+09:00 DEBUG 16940 --- [nio-8080-exec-3] o.s.s.w.a.Http403ForbiddenEntryPoint     : Pre-authenticated entry point called. Rejecting access
2024-01-05T14:01:00.626+09:00 DEBUG 16940 --- [nio-8080-exec-3] o.s.security.web.FilterChainProxy        : Securing GET /error
2024-01-05T14:01:00.627+09:00 DEBUG 16940 --- [nio-8080-exec-3] o.s.s.w.a.AnonymousAuthenticationFilter  : Set SecurityContextHolder to anonymous SecurityContext
2024-01-05T14:01:00.628+09:00 DEBUG 16940 --- [nio-8080-exec-3] o.s.s.w.s.HttpSessionRequestCache        : Saved request http://localhost:8080/error?continue to session
2024-01-05T14:01:00.628+09:00 DEBUG 16940 --- [nio-8080-exec-3] o.s.s.w.a.Http403ForbiddenEntryPoint     : Pre-authenticated entry point called. Rejecting access


我们目前正在实现会话风格的登录,而不使用Spring Security表单登录。在数据库中存储为ROLE_USER。Set-Cookie JSESSIONID cookie很好地保存在访问/修改/更新端点时登录403错误的头部。如果从安全配置类中减去hasAnyRole,@AuthenticationPrincipal UserDetails userDetail将输入对象null。带有此错误“Cannot invoke我们当前正在实现会话风格的登录而不使用Spring Security表单登录。Set-Cookie JSESSIONID cookie在访问/修改/更新端点时登录403错误时很好地保存在头中。如果从安全配置类中减去hasAnyRole,@AuthenticationPrincipal UserDetails userDetail将输入null对象。“无法调用 “org.springframework.security.core.userdetails.UserDetails. getData()”,因为“userDetails”为null”

piah890a

piah890a1#

删除以下配置

.securityContext((securityContext) -> securityContext
                        .securityContextRepository(new RequestAttributeSecurityContextRepository())
                );

字符串
或更改为

.securityContext((securityContext) -> securityContext
                .securityContextRepository(new HttpSessionSecurityContextRepository())
        );

相关问题