如何调试和修复Spring Security 403禁止使用Java/Angular应用程序

yshpjwxd  于 2023-01-05  发布在  Spring
关注(0)|答案(1)|浏览(166)

我第一次尝试使用Spring Security来保护一个带有Angular 前端的Java Web应用程序。
我能够成功登录到"/login"端点。
登录后,对安全端点"/excel/**"的任何请求都将失败,并且403被禁止(GET或POST)。
我已经读了几个SOF的问题,并试图解决我的问题与他们的答案,但没有任何工作。
错误响应中未提供特定消息。
在安全配置的开发阶段禁用cors和csrf。
以下是安全配置的配置方法:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .authorizeRequests()
            .antMatchers(HttpMethod.POST, "/excel/upload").hasAuthority(ROLE_ADMIN) // need Admin role to upload
            .antMatchers(HttpMethod.GET, "/excel/test").authenticated() // test endpoint to see if I can get through authentication
            .antMatchers("/users", "/auth/**").permitAll() // Permit all to display users list and to login / logout in "/auth" endpoints
            .anyRequest().authenticated()
            .and()
            .exceptionHandling().defaultAuthenticationEntryPointFor(
                    new CustomHttp403EntryPoint(),
                    new AntPathRequestMatcher("/excel/**")) // Custom EntryPoint for 403
            .and()
            .cors().disable() //Cors is disabled
            .csrf().disable(); // Csrf is disabled

}

下面是我的登录端点:

@PostMapping("/login")
public ResponseEntity<AuthenticationResponse> login(@RequestBody UserLogin userLogin) {
    Authentication authentication = this.authenticationManager.authenticate(
            new UsernamePasswordAuthenticationToken(userLogin.getUserName(), userLogin.getPassword())
    );

    AuthenticationResponse response = new AuthenticationResponse();
    if(authentication.isAuthenticated()) {
        UUID uuid = UUID.randomUUID();
        String token = uuid.toString();
        response.setToken(token);
        response.setMessage("Connected !");
        this.tokenSessionManager.getSessions().putIfAbsent(userLogin.getUserName(), token);
        return new ResponseEntity<>(response, HttpStatus.OK);
    } else {
        response.setToken(null);
        response.setMessage("Connection failed !");
        return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
    }
}

和我的安全端点:

@PostMapping(path = "/upload")
public ResponseEntity<ExcelUploadResponse> upload(@RequestParam("excelFile") MultipartFile file, HttpServletRequest request) {

    String token = this.tokenSessionManager.getSessions().get(this.adminUsername);
    if(!request.getHeader("Authorization").equals(token)) {
        return new ResponseEntity<>(new ExcelUploadResponse("Not authorized !"), HttpStatus.UNAUTHORIZED);
    }

    if(file != null &&
            file.getContentType() != null &&
            ExcelUploadUtils.isExcelFile(file)) {
        boolean success = this.excelUploadService.upload(file);
        if(success) {
            return new ResponseEntity<>(new ExcelUploadResponse("Your file has been updated"), HttpStatus.OK);
        } else {
            return new ResponseEntity<>(new ExcelUploadResponse("Update failed"), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    } else {
        return new ResponseEntity<>(new ExcelUploadResponse("Wrong type of file"), HttpStatus.BAD_REQUEST);
    }
}

@GetMapping(path = "/test")
public ResponseEntity<ExcelUploadResponse> test() {
    LOGGER.info("In test");
    return new ResponseEntity<>(new ExcelUploadResponse("Test OK!"), HttpStatus.OK);
}

我曾尝试在我的控制台中使用控制器中的slf4j记录器记录该问题,但它甚至没有达到,所以我没有更多的线索。
我已经在www.example.com中使用logging.level.org.springframework.security=DEBUG启用了Spring Security调试application.properties,但调试消息对我来说不是很清楚:

2023-01-03 13:36:15.600 DEBUG 14292 --- [nio-8080-exec-3] o.s.security.web.FilterChainProxy        : Securing POST /excel/payload
2023-01-03 13:36:15.600 DEBUG 14292 --- [nio-8080-exec-3] s.s.w.c.SecurityContextPersistenceFilter : Set SecurityContextHolder to empty SecurityContext
2023-01-03 13:36:15.600 DEBUG 14292 --- [nio-8080-exec-3] o.s.s.w.a.AnonymousAuthenticationFilter  : Set SecurityContextHolder to anonymous SecurityContext
2023-01-03 13:36:15.601 DEBUG 14292 --- [nio-8080-exec-3] o.s.s.w.a.i.FilterSecurityInterceptor    : Failed to authorize filter invocation [POST /excel/payload] with attributes [authenticated]
2023-01-03 13:36:29.469 ERROR 14292 --- [nio-8080-exec-3] f.g.a.security.CustomHttp403EntryPoint   : Error 403: Full authentication is required to access this resource with request session null
2023-01-03 13:36:29.469 DEBUG 14292 --- [nio-8080-exec-3] o.s.s.w.a.Http403ForbiddenEntryPoint     : Pre-authenticated entry point called. Rejecting access
2023-01-03 13:36:29.469 DEBUG 14292 --- [nio-8080-exec-3] w.c.HttpSessionSecurityContextRepository : Did not store empty SecurityContext
2023-01-03 13:36:29.469 DEBUG 14292 --- [nio-8080-exec-3] w.c.HttpSessionSecurityContextRepository : Did not store empty SecurityContext
2023-01-03 13:36:29.469 DEBUG 14292 --- [nio-8080-exec-3] s.s.w.c.SecurityContextPersistenceFilter : Cleared SecurityContextHolder to complete request

我已经实现了一个自定义的Http403ForbiddenEntryPoint来记录错误消息,但我仍然搞不清楚我的SecurityConfig出了什么问题:

@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException {
    LOGGER.error("Error 403: {}", e.getMessage());
    super.commence(request, response, e);
}

由于我是Spring Security的新手,有人知道我如何修复或查找有关403错误的更多信息吗?谢谢。

hgtggwj0

hgtggwj01#

必须创建一个控制器,而不是注解jwtFilter类和注解filter类,并通过控制器命中请求

相关问题