1

Доброго времени суток.

Изучаю Spring и столкнулся с проблемой. У меня есть REST контроллер. К которому направляется AJAX -запрос с страницы с параметром имя пользователя. В ответ он отдает из сервиса данные. Контроллер

@RestController

public class SearchController {

    UserService userService;

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @PostMapping("/search")
    public ResponseEntity<?> getSearchResultViaAjax(
            @Valid @RequestBody SearchCriteria search, Errors errors) {

        ResponseObjects result = new ResponseObjects();


        if (errors.hasErrors()) {
            result.setMsg("err");
            return ResponseEntity.badRequest().body(result);
        }

        User users = userService.findByUserNameOrEmail(search.getUsername());
        if (users==null) {
            result.setMsg("no user found!");
        } else {
            result.setMsg("success");
        }

        result.setResult(users);


        return ResponseEntity.ok(result);

    }
    @GetMapping("/search")
    public String getResp(){
        return "greeting";
    }


}

Сервис

@Service
public class UserService implements UserDetailsService{
    public UserService(UserRepo userRepo) {
        this.userRepo = userRepo; // вместо Autowired
    }
    private List<User> users;
    private final UserRepo userRepo;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        return userRepo.findByUsername(username);
    }
    public User findByUserNameOrEmail(String username) {
       return userRepo.findByUsername(username);

    }


}

AJAX

 $(document).ready(function () {


        $("#search-form").submit(function (event) {

            //stop submit the form, we will post it manually.
            event.preventDefault();

            fire_ajax_submit();

        });

    });

    function fire_ajax_submit() {

        var search = {}
        search["username"] = $("#uname").val();

        $("#btn-search").prop("disabled", true);

        $.ajax({
            type: "POST",
            contentType: "json",
            url: "http://localhost:8080/search",
            data: JSON.stringify(search),
            dataType: 'json',
            cache: false,
            timeout: 600000,
            success: function (data) {
                var json = "<h4>Ajax Response</h4><pre>"
                    + JSON.stringify(data, null, 1) + "</pre>";
                $('#feedback').html(json);

                console.log("SUCCESS : ", data);
                $("#btn-search").prop("disabled", false);

            },
            error: function (e) {

                var json = "<h4>Ajax Response</h4><pre>"
                    + e.responseText +"</pre>";
                $('#feedback').html(json);

                console.log("ERROR : ", e);
                $("#btn-search").prop("disabled", false);

            }
        });

    }

WebSecurituConfig

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserService userService;
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()  // включаем авторизацию на главной страницк
                    .antMatchers("/","/search","/registration","/activate/*") // полный доступ
                    .permitAll()
                    .anyRequest().authenticated()
                .and()
                    .formLogin()
                    .loginPage("/login")
                    .permitAll()
                .and()
                    .logout()
                    .permitAll();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
       auth
               .userDetailsService(userService)
               .passwordEncoder(NoOpPasswordEncoder.getInstance());

    }

}

В Chrome: Failed to load resource: the server responded with a status of 403 () введите сюда описание изображения

На что обратить внимание? Заранее благодарен.

4
  • До отправки ajax запроса, уже авторизовались? 25 июл 2018 в 13:50
  • Да. авторизацию прошел. GET запросы проходят. 25 июл 2018 в 14:03
  • Добавьте в вопрос значения заголовков у этого запроса, включая cookie. 25 июл 2018 в 14:14
  • Проблема решена. По неопытности или глупости забыл про csrf. 25 июл 2018 в 14:28

1 ответ 1

0

Проблема решена. По неопытности или глупости забыл про csrf Thymeleaf:

<meta id="_csrf" name="_csrf" th:content="${_csrf.token}" />
<meta id="_csrf_header" name="_csrf_header" th:content="${_csrf.headerName}" />

AJAX:

var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");

$(document).ready(function () {


    $("#search-form").submit(function (event) {

        //stop submit the form, we will post it manually.
        event.preventDefault();
        fire_ajax_submit();

    });

});


function fire_ajax_submit() {

    var search = {}
    search["username"] = $("#uname").val();

    $("#btn-search").prop("disabled", true);

    $.ajax({
        type: "POST",
        contentType: "application/json",
        url: "http://localhost:8080/search",
        data: JSON.stringify(search),
        dataType: 'json',
        cache: false,
        timeout: 600000,
        beforeSend: function(xhr) {
            xhr.setRequestHeader(header, token);
        },
        success: function (data) {
            var json = "<h4>Ajax Response</h4><pre>"
                + JSON.stringify(data, null, 1) + "</pre>";
            $('#feedback').html(json);

            console.log("SUCCESS : ", data);
            $("#btn-search").prop("disabled", false);

        },
        error: function (e) {

            var json = "<h4>Ajax Response</h4><pre>"
                + e.responseText +"</pre>";
            $('#feedback').html(json);

            console.log("ERROR : ", e);
            $("#btn-search").prop("disabled", false);

        }
    });

}

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.