【问题标题】:Multiple users with Spring Security使用 Spring Security 的多个用户
【发布时间】:2017-05-22 23:57:42
【问题描述】:

我有 4 种不同类型的用户。每种类型都有自己的角色和附加属性。 用户是父母,3 个继承人。

我也使用 Spring Data。

我可以通过哪种方式实现 UserDetailsS​​ervice 来使用 4 种不同类型的用户?

现在我有:

@Inheritance(strategy = InheritanceType.JOINED)
public class User implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue
    private Long id;
    private String username;
    private String password;
    private String email;
    @ManyToMany
    @JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
    private Set<Role> roles;

}

还有

public class Employee extends User implements Serializable {

    private static final long serialVersionUID = 1L;


    private String fullName;
    @ManyToMany(mappedBy = "employees")
    private Set<Project> projects;
    @OneToMany(mappedBy = "employee")
    private Set<Task> tasks;

}

还有其他的。

【问题讨论】:

    标签: java spring spring-boot spring-security spring-data


    【解决方案1】:

    既然您在谈论UserDetailsService,我假设您使用Spring Security。如果您只需要对用户进行身份验证/授权,我不确定您是否需要 UserDetailsService 提供的完整用户管理。定义一个AuthenticationProvider 并在此处查询可能就足够了

    @Configuration
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
        @PersistenceContext
        private EntityManager entityManager;
    
        @Override
        public void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.authenticationProvider(new AuthenticationProvider() {
                @Override
                public Authentication authenticate(Authentication authentication) throws AuthenticationException {
                    // Do you database query here
                    ArrayList<GrantedAuthority> authorities = new ArrayList<>();
                    authorities.add(new SimpleGrantedAuthority("ROLE_"));  // list of roles from database 
                    return new UsernamePasswordAuthenticationToken(authentication.getPrincipal(),
                               authentication.getCredentials(), authorities);
                }
    
                @Override
                public boolean supports(Class<?> authentication) {
                    return true;
                }
            })
        }
    }
    

    这个例子是内联的,你应该把AuthenticationProvider 变成一个真正的类。

    AuthenticationProvider 使用未经身份验证的Authentication 调用,该Authentication 由过滤器创建,通常为BasicAuthenticationFilterUsernamePasswordAuthenticationFilter。在此之后,Authentication 被提供给ProviderManager,它询问每个AuthenticationProvider 是否可以验证这种类型的Authentication(这就是 supports() 方法的用途)。一旦找到合适的AuthenticationProvider,它就会被要求进行身份验证——这是您进行数据库查找并从数据库中查找角色的地方,并根据来自数据库。

    请注意,您应该将“ROLE_”放在角色前面(除非您这样存储它们),否则它将无法与使用 HttpSecurity 配置的声明式访问一起使用

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
          .authorizeRequests()
             .antMatchers("/","/home").permitAll()
             .antMatchers("/admin/**").access("hasRole('ADMIN')")
             // more lines 
    }
    

    这里 ADMIN 映射到GrantedAuthority ROLE_ADMIN。

    【讨论】:

      猜你喜欢
      • 2016-08-31
      • 2011-08-02
      • 2017-04-02
      • 1970-01-01
      • 1970-01-01
      • 2016-02-12
      • 1970-01-01
      • 2018-11-15
      • 2014-07-16
      相关资源
      最近更新 更多