I'm new in spring boot and trying to create authentication app, but after writing it i found an error in postman app :
"timestamp": "2022-06-18T06:42:20.072 00:00", "status": 403, "error": "Forbidden"
This is my code :
i have 2 classes, one in Auth request and another is Auth response and I have a controller for both of them, this is the AuthRequest model:
public class AuthRequest {
@Email @Length(max = 50 , min = 5)
private String email;
@Length(max = 50 , min = 2)
private String password;
public AuthRequest(String email ,String password) {
this.email = email;
this.password = password;
}
and this is my Auth response model :
public class AuthResponse {
private String email ;
private String accessToken;
public AuthResponse(){}
public AuthResponse(String email, String accessToken) {
this.email = email;
this.accessToken = accessToken;
}
This Auth Request controller:
@RestController
public class AuthController {
@Autowired
AuthenticationManager authenticationManager;
@PostMapping("/login")
public ResponseEntity<?> login(@RequestBody @Valid AuthRequest authRequest){
try {
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(authRequest.getEmail(),authRequest.getPassword()));
Employee employee = (Employee) authentication.getPrincipal();
String accessToken = "JWT access token here";
AuthResponse authResponse = new AuthResponse(employee.getEmail(), accessToken);
return ResponseEntity.ok(authResponse);
}catch (BadCredentialsException ex) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
}
}
}
and this is my **config security class** :
@EnableWebSecurity
@CrossOrigin
public class ApplicationSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private IEmployeeRepository employeeRepository;
@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(username -> employeeRepository.findByEmail(username)
.orElseThrow(() -> new UsernameNotFoundException("User " username " not found. ")));
}
@Bean
public AuthenticationManager AuthenticationManagerBean() throws Exception {
return super.authenticationManager();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable();
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.authorizeRequests().anyRequest().permitAll();
}
}
and then, I post it to postman and this gave an error message and do not confirm :
Trace : and i save it in the database :
CodePudding user response:
The property isDeleted
of the Employee
object returned by the call to employeeRepository.findByEmail(username)
is null and it's defined as not nullable (boolean
).
Either return a not null value or change the property's type to Boolean
.