具有Spring Security的多个用户

问题描述 投票:1回答:1

我有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个回答
0
投票

既然你在谈论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,由过滤器创建,通常是BasicAuthenticationFilterUsernamePasswordAuthenticationFilter。在此之后,Authentication被给予ProviderManagerAuthenticationProvider询问每个Authentication是否可以验证这种类型的AuthenticationProvider(这是支持()方法的用途)。一旦找到合适的Authentication,就会要求它进行身份验证 - 这是您进行数据库查找并从数据库中查找角色的位置,并根据数据库中的角色构建一个包含GrantedAuthorities列表的新HttpSecurity

请注意,您应该将“ROLE_”放在角色的前面(除非您将它们存储起来),否则它将不适用于使用@Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/","/home").permitAll() .antMatchers("/admin/**").access("hasRole('ADMIN')") // more lines } 配置的声明性访问

GrantedAuthority

这里ADMIN映射到qazxswpoi ROLE_ADMIN。

© www.soinside.com 2019 - 2024. All rights reserved.