Skip to content

Commit

Permalink
add principal type check when get user info
Browse files Browse the repository at this point in the history
  • Loading branch information
lepdou committed Sep 13, 2017
1 parent 0018445 commit a416903
Showing 1 changed file with 16 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,28 @@
import com.ctrip.framework.apollo.portal.spi.UserInfoHolder;

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;

import java.security.Principal;

public class SpringSecurityUserInfoHolder implements UserInfoHolder {

@Override
public UserInfo getUser() {
UserInfo userInfo = new UserInfo();
String userId = ((User) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername();
userInfo.setUserId(userId);
userInfo.setUserId(getCurrentUsername());
return userInfo;
}

private String getCurrentUsername() {
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if (principal instanceof UserDetails) {
return ((UserDetails) principal).getUsername();
}
if (principal instanceof Principal) {
return ((Principal) principal).getName();
}
return String.valueOf(principal);
}

}

0 comments on commit a416903

Please sign in to comment.