spring安全userdetails和controller(get user)

t5zmwmid  于 2021-07-23  发布在  Java
关注(0)|答案(1)|浏览(421)

有userdetail和logincontroller。
userdetail从数据库获取用户。
用户详细信息

public class UserDetail implements UserDetailsService {

        private final
        UserServiceJpa userServiceJpa;

        public UserDetail(UserServiceJpa userServiceJpa) {
            this.userServiceJpa = userServiceJpa;
        }

        @Override
        public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {

            // Get user
            User user = userServiceJpa.findUserByEmail(email);

            if (user == null){
                throw new UsernameNotFoundException("There is no such user " + email);
            }

            return new org.springframework.security.core.userdetails.User(user.getEmail(),
                    user.getPassword(),
                    user.getEnabled(),
                    user.getAccount_non_expired(),
                    user.getCredentials_non_expired(),
                    user.getAccount_non_locked(),
                    getAuthorities());

        }

        private Collection<? extends GrantedAuthority> getAuthorities(){

            List<SimpleGrantedAuthority> authList = new ArrayList<>();
            authList.add(new SimpleGrantedAuthority("ROLE_USER"));
            authList.add(new SimpleGrantedAuthority("ROLE_ADMIN"));

            return authList;

        }

    }

登录控制器

@Controller
    public class LoginController {

        @GetMapping(value = "/login")
        public String login () {

            return "/login";
        }

    }

问题!如何在logincontroller中获取userdetail接收到的此用户?
我这样做是为了不重新连接到数据库。因此,我想知道如果用户被阻止了,他是如何被阻止的-enabled,accountnonexpired,credentialsnexpired,accountnonlocked

7vhp5slm

7vhp5slm1#

您可以通过自动连接从logincontroller创建userdetails类,然后在登录类中调用该函数。

@Controller
public class LoginController {

    @Autowired
    private UserDetails userDetails;

    @GetMapping(value = "/login")
    public String login (@QueryParam("email")String email) {
        userDetails.loadUserByUsername(email);
        return "/login";
    }

}

相关问题