Spring security UserDetails 和控制器(获取用户)

Posted

技术标签:

【中文标题】Spring security UserDetails 和控制器(获取用户)【英文标题】:Spring security UserDetails and controller (get user) 【发布时间】:2021-06-09 11:53:35 【问题描述】:

UserDetailLoginController

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接收到的这个用户?

我这样做是为了不重新连接到数据库。因此,我想知道如果用户被阻止 - enabledaccountNonExpiredcredentialsNonExpiredaccountNonLocked,他是如何被阻止的>

【问题讨论】:

【参考方案1】:

你可以通过自动装配从你的 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";
    


【讨论】:

以上是关于Spring security UserDetails 和控制器(获取用户)的主要内容,如果未能解决你的问题,请参考以下文章

Spring mvc / security:从spring security中排除登录页面

Spring Security:2.4 Getting Spring Security

没有 JSP 的 Spring Security /j_spring_security_check

Spring-Security

Spring Security 登录错误:HTTP 状态 404 - /j_spring_security_check

未调用 Spring Security j_spring_security_check