英文:
How to query users by user id in spring security?
问题
以下是您提供的内容的翻译:
我有一个使用Spring Security的Spring Boot应用,我已经扩展了 org.springframework.security.core.userdetails.User 类来创建一个自定义用户对象。由于我只需要一些用户来测试一些功能,我正在硬编码用户。我如何根据用户ID或电子邮件ID查询和获取特定用户?这些是我添加的自定义变量。是否有一种方法可以在不切换到JDBC身份验证等的情况下实现这一点,因为我觉得那样可能会使问题变得过于复杂?
我的自定义用户类:
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import java.util.Collection;
import java.util.List;
public class Guest extends User {
    public Guest(String username, String password, boolean enabled, boolean accountNonExpired,
                       boolean credentialsNonExpired, boolean accountNonLocked,
                       Collection<? extends GrantedAuthority> authorities) {
        super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
    }
    private long id;
    private String firstName;
    private String lastName;
    private String emailAddress;
    private String phoneNumber;
    
    //一些getter和setter方法
    public Guest(long id, String firstName, String lastName, String emailAddress, String phoneNumber, String username, String password, List<GrantedAuthority> authorities,
                 boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked) {
        super(username, password, enabled, accountNonExpired, credentialsNonExpired,
                accountNonLocked, authorities) ;
        this.id=id;
        this.firstName=firstName;
        this.lastName=lastName;
        this.emailAddress=emailAddress;
        this.phoneNumber=phoneNumber;
    }
}
我的新userDetailsService类:
@Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService {
    private static List<Guest> users = new ArrayList();
    public MyUserDetailsService() { 
    //硬编码用户
}
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    //在这里构建用户
}
SecurityConfig.java
@Configuration
@EnableWebSecurity
public class ApplicationSecurityConfiguration extends WebSecurityConfigurerAdapter{
    
    @Autowired
    @Qualifier("userDetailsService")
    private UserDetailsService userDetailsService;
    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    };
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
       //授权逻辑在这里
    }
}
英文:
I have a Spring Boot app with Spring Security where I have extended the org.springframework.security.core.userdetails.User class to create a custom user object.I am hard-coding users since I only need a few to test out some feaures.How can I query and fetch a certain user based on its user-id or email-id,which are custom variables I have added ?Is there a way to do this without shifting to jdbc authentication etc,since I feel it might complicate it too much ?
My custom user class:
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import java.util.Collection;
import java.util.List;
public class Guest extends User {
    public Guest(String username, String password, boolean enabled, boolean accountNonExpired,
                       boolean credentialsNonExpired, boolean accountNonLocked,
                       Collection<? extends GrantedAuthority> authorities) {
        super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
    }
    private long id;
    private String firstName;
    private String lastName;
    private String emailAddress;
    private String phoneNumber;
    
    //some getters and setters
    public Guest(long id, String firstName, String lastName, String emailAddress, String phoneNumber, String username, String password, List<GrantedAuthority> authorities,
                 boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked) {
        super(username, password, enabled, accountNonExpired, credentialsNonExpired,
                accountNonLocked, authorities) ;
        this.id=id;
        this.firstName=firstName;
        this.lastName=lastName;
        this.emailAddress=emailAddress;
        this.phoneNumber=phoneNumber;
    }
}
My new userdetailsService class:
@Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService {
    private static List<Guest> users = new ArrayList();
    public MyUserDetailsService() { 
    //hard-coding users
}
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    //building user here
}
SecurityConfig.java
@Configuration
@EnableWebSecurity
public class ApplicationSecurityConfiguration extends WebSecurityConfigurerAdapter{
    
    @Autowired
    @Qualifier("userDetailsService")
    private UserDetailsService userDetailsService;
    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    };
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
       //authorization logic here        
    }
}
答案1
得分: -1
以下是翻译好的部分:
您可以像以下示例一样使用硬编码的值。如果您需要用于模拟实现,
public UserDetails loadUserByUsername(String userName){
    
    // 使用您自定义的“List<Guest> users”硬编码的值来创建User对象
    
    User user = new User(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked,
                    authorities);
    return user;
}
注意:loadUserByUsername(String username)。在这里,userName可以是包含您想要的任何信息的userToken(通常用于查询数据库以获取用户名和密码)。在这种情况下,假设为Id。一旦您获得了上述的id(作为userToken/用户名),您可以将其与您的guest列表进行比较,以加载User对象。
英文:
You can do like below sample with hardcoded values.. if you needed it for mock implementation
public UserDetails loadUserByUsername(String userName){
		
//use your custom 'List<Guest> users' hardcoded values to create User object
User user = new User(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked,
				authorities);
return user;
}
note:- loadUserByUsername(String username).. here userName can be userToken containing any info you want as ref. (which usually you use to query db for fetching usrname & pass) .. in this cases lets say Id.. once you get id (as userToken/userName) above you can compare with ur guest list to load User object
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论