【发布时间】:2020-06-02 23:45:55
【问题描述】:
我有以下问题:我创建了共享一些端点的 Spring Boot API。我也有过滤器,它确定可以使用/不使用 JSON Web Token 到达哪些端点。一切正常,Postman 返回正确的对象,但 React 无法处理。我不知道什么会导致问题。
WebSecurityConfig:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable()
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeRequests().antMatchers("/auth/**").permitAll()
.anyRequest().authenticated();
http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
}
登录接口:
@CrossOrigin(origins = "http://localhost:3000", allowedHeaders = "*")
@PostMapping("/login")
public ResponseEntity<?> authenticateUser(@RequestBody LoginRequest loginRequest) {
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()));
SecurityContextHolder.getContext().setAuthentication(authentication);
String jwt = jwtUtils.generateJwtToken(authentication);
UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
List<String> roles = userDetails.getAuthorities().stream()
.map(item -> item.getAuthority())
.collect(Collectors.toList());
return ResponseEntity.ok(new JwtResponse(jwt,
userDetails.getId(),
userDetails.getUsername(),
roles));
}
React 代码片段:
const authenticate = async () => {
let usr = {
username: userName,
password: password
};
await fetch(`http://localhost:8080/auth/login`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(usr)
}).then((response) => {
console.log(response);
});
}
请求来自服务器,因为在调试期间我可以读取服务器端的所有数据。我还发现在处理整个请求之前,React 会取消请求。我尝试使用不同的 API(例如https://www.balldontlie.io/#get-all-games)并获取返回代码 200。
编辑
我可以从另一个 API 端点获取数据,但我必须自己在 fetch/axios 请求中添加 JWToken:
const getInitBooks = async () => {
await axios("http://localhost:8080/api/books/all", {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization' : "Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJhZG1pbiIsImlhdCI6MTU5MTE4MDkwMiwiZXhwIjoxNTkxMTgxODAyfQ.aN8mch_CCgeByLGDUkstiNLxV7x3364OEUeDgqyfWVQ"
},
}).then((response) => {
console.log(response);
setBooks(response.data)
setInitBooks(response.data)
});
所以错误只出现在 POST 请求中。我不知道现在出了什么问题。
解决方案
我想通了,这不是 Spring 问题,而是在 React 函数中添加 e.preventDefault() 有效。
代码sn-p:
const authenticate = async (e) => {
e.preventDefault();
await axios({
url: "http://localhost:8080/authentication/login/",
method: "POST",
data: {
username: userName,
password: password
},
}).then(res => {
console.log(res);
setLoggedIn(true);
})
.catch((err) => console.log(err));
};
【问题讨论】:
标签: reactjs spring-boot api http-post