Доброго времени суток.
Изучаю 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 ()
На что обратить внимание? Заранее благодарен.