When making a request to the API with the user's credentials from keycloak authentication From the intercepter before the method of the controller class is called Note that I had a hard time not knowing that there is a getUserPrincipal () method to get user information.
intercepterTestClass.java
@Autowired
private UserDto userDto;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
//
//If you don't have your credentials
if (request.getUserPrincipal() == null) {
System.out.println("Dummy setting because there is no authentication information");
userDto.setUserid("U0001");
userDto.setUserName("guest");
return true;
}
//
final KeycloakSecurityContext context = KeycloakPrincipal.class.cast(request.getUserPrincipal()).getKeycloakSecurityContext();
userDto.setUserName(context.getToken().getPreferredUsername());
userDto.setUserId(String.valueOf(context.getToken().getOtherClaims().get("user_id")));
//
return true;
See another article for the implementation of keycloak authentication. By obtaining the authentication information with the interceptor The versatility has improved because it is no longer necessary to describe it in each Controller class. Until now, I've only used Spring Security as the authentication function, Spring Security doesn't seem to be very suitable for API implementation.
Recommended Posts