Программисты JAVA общаются здесь
Anonymous
Возникла несанкционированная ошибка 401 при отправке даты, дня и мыслей на сервер.
Сообщение
Anonymous » 29 окт 2024, 11:58
У меня возникла несанкционированная ошибка 401. Я пытаюсь опубликовать три вещи: дату, день и мысли в моей базе данных postgresSQL, используя весеннюю загрузку. Когда я нажимаю на функцию из внешнего интерфейса, она выдает ошибку. Я делюсь своим классом конфигурации безопасности и контроллером вместе с кодом функции. Нужна помощь в решении этой проблемы.
Код: Выделить всё
** security config class : **
package com.diaries.diaryproject.SecurityConfig;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.cors(cors -> cors.disable())
.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(auth -> auth
.requestMatchers("/user/add").permitAll()
.requestMatchers("/user/login").permitAll()
.requestMatchers("/data/save").permitAll()
.requestMatchers("/data/mydata").permitAll()
// .requestMatchers("/data/save").authenticated()
// .requestMatchers("/data/mydata").authenticated()
.anyRequest().authenticated()
);
return http.build();
}
}
** controller class : **
package com.diaries.diaryproject.UsersDataController;
import java.security.Principal;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.diaries.diaryproject.UsersDataModel.UsersData;
import com.diaries.diaryproject.UsersDataService.UsersDataService;
import com.diaries.diaryproject.model.Users;
import com.diaries.diaryproject.service.UsersService;
@RestController
@RequestMapping("/data")
@CrossOrigin
public class UsersDataController {
@Autowired
private UsersDataService usersDataService;
@Autowired
private UsersService userService;
@PostMapping("/save")
public ResponseEntity saveData(@RequestBody UsersData data, Principal principal) {
if (principal == null) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(null);
}
// Retrieve user from database based on Principal username
Users user = userService.findByUsername(principal.getName());
data.setUser(user);
return ResponseEntity.ok(usersDataService.saveUsersData(data));
}
@GetMapping("/mydata")
public ResponseEntity getMyData(Principal principal) {
if (principal == null) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(null);
}
Users user = userService.findByUsername(principal.getName());
return ResponseEntity.ok(usersDataService.getUsersData(user));
}
}
** handleDataSubmit function :**
const handleDataSubmit = async (e) => {
e.preventDefault();
const userData = {
"date" : date,
"day" : day,
"thoughts" : thoughts
}
try{
const response = await fetch("http://localhost:8080/data/save" ,
{
method : 'POST',
headers : {
'Content-Type' : 'application/json'
},
body : JSON.stringify(userData)
}
)
if(response.status === 200){
console.log("data submitted successfully")
}
else if(response.status === 401){
console.log("an error has occured")
}
else{
console.log("nothing")
}
}
catch(error){
console.log(error.message)
}
}
Я предполагаю, что мне нужно отправить что-то в заголовках, например какой-то токен, но я не уверен, что и где находится этот токен.
Подробнее здесь:
https://stackoverflow.com/questions/791 ... s-to-the-b
1730192325
Anonymous
У меня возникла несанкционированная ошибка 401. Я пытаюсь опубликовать три вещи: дату, день и мысли в моей базе данных postgresSQL, используя весеннюю загрузку. Когда я нажимаю на функцию из внешнего интерфейса, она выдает ошибку. Я делюсь своим классом конфигурации безопасности и контроллером вместе с кодом функции. Нужна помощь в решении этой проблемы. [code]** security config class : ** package com.diaries.diaryproject.SecurityConfig; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.web.SecurityFilterChain; @Configuration @EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .cors(cors -> cors.disable()) .csrf(csrf -> csrf.disable()) .authorizeHttpRequests(auth -> auth .requestMatchers("/user/add").permitAll() .requestMatchers("/user/login").permitAll() .requestMatchers("/data/save").permitAll() .requestMatchers("/data/mydata").permitAll() // .requestMatchers("/data/save").authenticated() // .requestMatchers("/data/mydata").authenticated() .anyRequest().authenticated() ); return http.build(); } } ** controller class : ** package com.diaries.diaryproject.UsersDataController; import java.security.Principal; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.diaries.diaryproject.UsersDataModel.UsersData; import com.diaries.diaryproject.UsersDataService.UsersDataService; import com.diaries.diaryproject.model.Users; import com.diaries.diaryproject.service.UsersService; @RestController @RequestMapping("/data") @CrossOrigin public class UsersDataController { @Autowired private UsersDataService usersDataService; @Autowired private UsersService userService; @PostMapping("/save") public ResponseEntity saveData(@RequestBody UsersData data, Principal principal) { if (principal == null) { return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(null); } // Retrieve user from database based on Principal username Users user = userService.findByUsername(principal.getName()); data.setUser(user); return ResponseEntity.ok(usersDataService.saveUsersData(data)); } @GetMapping("/mydata") public ResponseEntity getMyData(Principal principal) { if (principal == null) { return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(null); } Users user = userService.findByUsername(principal.getName()); return ResponseEntity.ok(usersDataService.getUsersData(user)); } } ** handleDataSubmit function :** const handleDataSubmit = async (e) => { e.preventDefault(); const userData = { "date" : date, "day" : day, "thoughts" : thoughts } try{ const response = await fetch("http://localhost:8080/data/save" , { method : 'POST', headers : { 'Content-Type' : 'application/json' }, body : JSON.stringify(userData) } ) if(response.status === 200){ console.log("data submitted successfully") } else if(response.status === 401){ console.log("an error has occured") } else{ console.log("nothing") } } catch(error){ console.log(error.message) } } [/code] Я предполагаю, что мне нужно отправить что-то в заголовках, например какой-то токен, но я не уверен, что и где находится этот токен. Подробнее здесь: [url]https://stackoverflow.com/questions/79134172/experiencing-401-unauthorized-error-when-sending-date-day-and-thoughts-to-the-b[/url]