Hej mam problem i już nie wiem co mogę zrobić, problem pewnie jest z konfiguracją ale to pierwszy projekt w springu.
Mam metodę logowania która generuje token ale jak chce wykonać jakieś zadanie jako zalogowany użytkownik to jest problem z autoryzacją.
@PermitAll
@PostMapping("/register")
public ResponseEntity<String> registerCustomer(@RequestBody Customer customer) {
if (customer.getCustomerLogin() == null) {
return new ResponseEntity<>("Bad request", HttpStatus.BAD_REQUEST);
}
if (customerLoginService.existsByEmail(customer.getCustomerLogin().getEmail())) {
return new ResponseEntity<>("this email already exists ", HttpStatus.CONFLICT);
}
String hashedPassword = passwordEncoderService.codingPassword(customer.getCustomerLogin().getPassword());
customer.getCustomerLogin().setPassword(hashedPassword);
customerService.createCustomer(customer);
return new ResponseEntity<>("Correct register", HttpStatus.CREATED);
}
@PermitAll
@PostMapping("/login")
public ResponseEntity<String> loginCustomer(@RequestBody CustomerLogin customerLogin) {
CustomerLogin storedCustomerLogin = customerLoginService.findPasswordByEmail(customerLogin.getEmail());
if (storedCustomerLogin != null) {
String hashedPasswordFromDatabase = storedCustomerLogin.getPassword();
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
if (passwordEncoder.matches(customerLogin.getPassword(), hashedPasswordFromDatabase)) {
String token = jwtTokenService.generateJwtToken(customerLogin);
return new ResponseEntity<>(token, HttpStatus.OK);
} else {
logger.info("Attempting to log in customer with email: {}", customerLogin.getEmail());
return new ResponseEntity<>("Invalid credentials", HttpStatus.UNAUTHORIZED);
}
} else {
logger.error("Error during customer login for email: {}", customerLogin.getEmail());
return new ResponseEntity<>("User not found", HttpStatus.NOT_FOUND);
}
}
}
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf()
.ignoringRequestMatchers("/customer/register", "/customer/login", "/admin/**", "/common/**", "/customer/**")
.and()
.authorizeHttpRequests((authz) -> authz
.requestMatchers("/customer/register", "/customer/login", "/admin/**", "/common/**").permitAll()
.anyRequest().authenticated()
);
return http.build();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
@Service
public class JwtTokenServiceImpl {
CustomerService customerService;
SecretKey key = Keys.secretKeyFor(SignatureAlgorithm.HS256);
@Autowired
public JwtTokenServiceImpl(CustomerService customerService) {
this.customerService = customerService;
}
public String generateJwtToken(CustomerLogin customerLogin) {
return Jwts.builder()
.setSubject((customerLogin.getEmail()))
.signWith(key)
.compact();
}
public String extractEmailFromToken(String token) {
Claims claims = Jwts.parserBuilder()
.setSigningKey(key)
.build()
.parseClaimsJws(token)
.getBody();
return claims.getSubject();
}
public boolean isAuthenticated(String token) {
try {
Claims claims = Jwts.parserBuilder()
.setSigningKey(key)
.build()
.parseClaimsJws(token)
.getBody();
Date now = new Date();
return now.before(claims.getExpiration());
} catch (Exception e) {
return false;
}
}
@GetMapping("/loggedCustomer")
public ResponseEntity<Customer> getDataLoggedCustomer(@RequestHeader("Authorization") String token) {
String email = jwtTokenService.extractEmailFromToken(token);
if (email != null) {
Customer loggedCustomer = customerService.findByEmail(email);
if (loggedCustomer != null) {
logger.info("Klient o adresie e-mail {} został pomyślnie uwierzytelniony.", email);
return new ResponseEntity<>(loggedCustomer, HttpStatus.OK);
}
}
logger.error("Błąd podczas uwierzytelniania klienta z adresem e-mail: {}", token);
return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
}
To jest w postmanie:
The request was a legal request, but the server is refusing to respond to it. Unlike a 401 Unauthorized response, authenticating will make no difference.
A tu logi:
2023-09-13T14:25:54.951+02:00 DEBUG 27392 --- [nio-8085-exec-1] o.s.security.web.FilterChainProxy : Securing POST /customer/login
2023-09-13T14:25:54.980+02:00 DEBUG 27392 --- [nio-8085-exec-1] o.s.security.web.FilterChainProxy : Secured POST /customer/login
2023-09-13T14:25:55.417+02:00 DEBUG 27392 --- [nio-8085-exec-1] o.s.s.w.a.AnonymousAuthenticationFilter : Set SecurityContextHolder to anonymous SecurityContext
2023-09-13T14:26:25.703+02:00 DEBUG 27392 --- [nio-8085-exec-3] o.s.security.web.FilterChainProxy : Securing POST /customer/loggedCustomer
2023-09-13T14:26:25.715+02:00 DEBUG 27392 --- [nio-8085-exec-3] o.s.s.w.a.AnonymousAuthenticationFilter : Set SecurityContextHolder to anonymous SecurityContext
2023-09-13T14:26:25.717+02:00 DEBUG 27392 --- [nio-8085-exec-3] o.s.s.w.a.Http403ForbiddenEntryPoint : Pre-authenticated entry point called. Rejecting access
2023-09-13T14:26:25.724+02:00 DEBUG 27392 --- [nio-8085-exec-3] o.s.security.web.FilterChainProxy : Securing POST /error
2023-09-13T14:26:25.727+02:00 DEBUG 27392 --- [nio-8085-exec-3] o.s.s.w.a.AnonymousAuthenticationFilter : Set SecurityContextHolder to anonymous SecurityContext
2023-09-13T14:26:25.728+02:00 DEBUG 27392 --- [nio-8085-exec-3] o.s.s.w.a.Http403ForbiddenEntryPoint : Pre-authenticated entry point called. Rejecting access