How to access user details in Controller using Spring Security?

我只是一个虾纸丫 提交于 2020-06-17 09:58:04

问题


I need to access currently logged-in user details (id or email address) in Controller. This is how I am trying to do so right now, and this doesn't work.

ApplicationUser is an @Entity in database.

UserDetailsService:

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    private ApplicationUserRepository applicationUserRepository;

    public UserDetailsServiceImpl(ApplicationUserRepository applicationUserRepository) {
        this.applicationUserRepository = applicationUserRepository;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        ApplicationUser applicationUser = applicationUserRepository.findByUsername(username);
        if (applicationUser == null) {
            throw new UsernameNotFoundException(username);
        }
        return builtCustomUser(applicationUser);
    }

    private User builtCustomUser(ApplicationUser applicationUser) {
        String username = applicationUser.getUsername();
        String password = applicationUser.getPassword();
        boolean enabled = true;
        boolean accountNonExpired = true;
        boolean credentialsNonExpired = true;
        boolean accountNonLocked = true;

        MyUser myUser = new MyUser(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, emptyList());

        return myUser;
    }
}

Custom User class:

public class MyUser extends User implements UserDetails {
    public MyUser(String username, String password, Collection<? extends GrantedAuthority> authorities) {
        super(username, password, authorities);
    }

    public MyUser(String username, String password, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired,
                  boolean accountNonLocked, Collection<? extends GrantedAuthority> authorities) {
        super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
    }
}

That's how I am trying to access it in Controller:

MyUser mu = (MyUser) authentication.getPrincipal();

And this is error:

java.lang.ClassCastException: class java.lang.String cannot be cast to class MyUser

回答1:


On this code, actual type of Authentication is UsernamePasswordAuthenticationToken, and return type of getPrincipal() is String, username.

You can set any other Authentication implementation instead of UsernamePasswordAuthenticationToken to SecurityContext, and principal type is free(so you can set MyUser), too.



来源:https://stackoverflow.com/questions/62303630/how-to-access-user-details-in-controller-using-spring-security

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!