How to organize user authentication by its apiKey ? I tried it like this, but the problem is that UsernamePasswordAuthenticationToken expects a password in its pure form, and it is encrypted in the database.

 @RestController @RequestMapping(value = "/rest/v1") public class ApiV1 { @Autowired UserRepository userRepository; @PostMapping("authorize") ResponseEntity<ApiError> authorize(@RequestHeader(value = "apiKey") String apiKey) { UserDetails user = userRepository.findByApiKey(apiKey); if (user == null) return new ResponseEntity<>(new ApiError("API KEY NOT FOUND"), HttpStatus.NOT_FOUND); try { Authentication authenticationToken = new UsernamePasswordAuthenticationToken(user, null) ; SecurityContextHolder.getContext().setAuthentication(authenticationToken); } catch (Exception e) { SecurityContextHolder.getContext().setAuthentication(null); return new ResponseEntity<>(new ApiError("UNAUTHORIZED", e.toString()), HttpStatus.UNAUTHORIZED); } return new ResponseEntity<>(new ApiError("OK"), HttpStatus.OK); } } 

    1 answer 1

    Can someone come in handy

     public void authWithoutPassword(User user){ List<Privilege> privileges = user.getRoles().stream() .map(role -> role.getPrivileges()) .flatMap(list -> list.stream()) .distinct().collect(Collectors.toList()); List<GrantedAuthority> authorities = privileges.stream() .map(p -> new SimpleGrantedAuthority(p.getName())) .collect(Collectors.toList()); Authentication authentication = new UsernamePasswordAuthenticationToken(user, null, authorities); SecurityContextHolder.getContext().setAuthentication(authentication); }