Spring boot + весенний конфигурационный файл безопасности не работает - PullRequest
0 голосов
/ 07 апреля 2019

Я пытаюсь настроить Spring Security и запросы CORS контроллера, но предварительный запрос не работает.У меня есть контроллер, тест и весенняя конфигурация безопасности, которые связаны с проблемой.Что я делаю не так?)

Java 8, Spring Boot 2.1.4

Контроллер

@RestController
@RequestMapping("/login")
@CrossOrigin
public class LoginController {

@RequestMapping(path = "/admin", consumes = "application/json", produces = "application/json")
    public ResponseEntity<Admin> loginAdmin(@RequestBody Admin admin) {
        String username = admin.getUsername();
        String password = admin.getPassword();
        authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
        ResponseEntity<Admin> responseEntity;
        Admin foundAdmin = adminRepository.findByUsername(username);
        if (foundAdmin != null) {
            String token = jwtTokenProvider.createToken(username, adminRepository.findByUsername(username).getRoles());
            AdminAuthenticatedResponse contractorAuthenticatedResponse = new AdminAuthenticatedResponse(foundAdmin, token);
            responseEntity = new ResponseEntity<>(contractorAuthenticatedResponse, HttpStatus.ACCEPTED);
        } else {
            responseEntity = new ResponseEntity<>(admin, HttpStatus.NOT_FOUND);
        }
        return responseEntity;
    }
}

Конфигурация безопасности

@Override
    protected void configure(HttpSecurity http) throws Exception {

        http
                .httpBasic().disable()
                .csrf().disable()
                .cors().and().formLogin().and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers("/login/**").permitAll()
                .antMatchers("/register/**").permitAll()
                .antMatchers("/h2-console/**").permitAll()
                .antMatchers(HttpMethod.GET, "/restapi/customers/**").permitAll()
                .antMatchers(HttpMethod.DELETE, "/restapi/customers/**").hasRole("CUSTOMER")
                .antMatchers(HttpMethod.PUT, "/restapi/customers/**").hasRole("CUSTOMER")
                .antMatchers(HttpMethod.PATCH, "/restapi/customers/**").hasRole("CUSTOMER")
                .antMatchers(HttpMethod.GET, "/restapi/contractors/**").permitAll()
                .antMatchers(HttpMethod.DELETE, "/restapi/contractors/**").hasRole("CONTRACTOR")
                .antMatchers(HttpMethod.PUT, "/restapi/contractors/**").hasRole("CONTRACTOR")
                .antMatchers(HttpMethod.PATCH, "/restapi/contractors/**").hasRole("CONTRACTOR")
                .antMatchers(HttpMethod.PATCH, "/restapi/workRequests/**").hasAnyRole("CONTRACTOR", "CONTRACTOR", "ADMIN")
                .antMatchers(HttpMethod.PUT, "/restapi/workRequests/**").hasAnyRole("CONTRACTOR", "CONTRACTOR", "ADMIN")
                .antMatchers(HttpMethod.POST, "/restapi/workRequests/**").hasAnyRole("CONTRACTOR", "CONTRACTOR", "ADMIN")
                .antMatchers(HttpMethod.DELETE, "/restapi/workRequests/**").hasAnyRole("CONTRACTOR", "CONTRACTOR", "ADMIN")
                .antMatchers(HttpMethod.GET, "/restapi/workRequests/**").hasAnyRole("CONTRACTOR", "CONTRACTOR", "ADMIN")
                .anyRequest().authenticated()
                .and()
                .apply(new JwtConfigurer(jwtTokenProvider))
                // Allow pages to be loaded in frames from the same origin; needed for H2-Console
                .and()
                .headers()
                .frameOptions()
                .sameOrigin();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .userDetailsService(userRepositoryUserDetailsService)
                .passwordEncoder(encoder());
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList(ALL));
        configuration.setAllowedMethods(Arrays.asList(ALL));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring()
                .antMatchers("/**", "/resources/**", "/index.html", "/login/admin", "/template/**", "/",
                        "/error/**", "/h2-console", "*/h2-console/*");
    }

Тест

@Test
    public void testLogin() {
        Admin admin = new Admin("network", "network");
//        adminRepository.save(admin);
        String s = adminRepository.findByUsername("network").getUsername();
        RequestEntity<Admin> requestEntity =
                RequestEntity
                        .post(uri("/login/admin"))
                        .contentType(MediaType.APPLICATION_JSON)
                        .body(admin);
        ResponseEntity<Admin> responseEntity = this.restTemplate.exchange(requestEntity, Admin.class);
        assertNotNull(responseEntity);
        System.out.println(responseEntity.getStatusCode());
    }

Я ожидаю успешного запроса, но получаю ОШИБКУ ВНУТРЕННЕГО СЕРВЕРА.

1 Ответ

0 голосов
/ 07 апреля 2019

403 Доступ запрещен или нет. Ошибка 403 означает, что у вас нет разрешения на просмотр запрошенного файла или ресурса

Пожалуйста, попробуйте выполнить тест с @ WithMockUser

@Test
@WithMockUser
public void corsWithAnnotation() throws Exception {
        ResponseEntity<Admin> entity = this.restTemplate.exchange(
...
}

Ссылка: Предварительный тест безопасности Spring: Web Security

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...