首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >弹簧安全多重UserDetailsService

弹簧安全多重UserDetailsService
EN

Stack Overflow用户
提问于 2018-10-12 16:45:21
回答 1查看 6.2K关注 0票数 7

我有三个不同的表,每个表都有用户信息。(可能用户名相同,密码不同)

另外,有3个不同的URL进行授权。是否有可能在一个配置和授权控制期间使用多个UserDetailsService来使用哪个表?

下面是我的配置代码,但我无法控制在授权期间使用哪个表:

代码语言:javascript
复制
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
@Import(SecurityProblemSupport.class)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    private final AuthenticationManagerBuilder authenticationManagerBuilder;

    @Qualifier("userDetailsService")
    private final UserDetailsService userDetailsService;

    @Qualifier("customerDetailsService")
    private final UserDetailsService customerDetailsService;

    private final TokenProvider tokenProvider;

    private final CorsFilter corsFilter;

    private final SecurityProblemSupport problemSupport;

    public SecurityConfiguration(AuthenticationManagerBuilder authenticationManagerBuilder, UserDetailsService userDetailsService, UserDetailsService customerDetailsService, TokenProvider tokenProvider, CorsFilter corsFilter, SecurityProblemSupport problemSupport) {
        this.authenticationManagerBuilder = authenticationManagerBuilder;
        this.userDetailsService = userDetailsService;
        this.customerDetailsService = customerDetailsService;
        this.tokenProvider = tokenProvider;
        this.corsFilter = corsFilter;
        this.problemSupport = problemSupport;
    }

    @PostConstruct
    public void init() {
        try {
            authenticationManagerBuilder
                .userDetailsService(userDetailsService)
                .passwordEncoder(passwordEncoder())
                .and()
                .userDetailsService(customerDetailsService)
                .passwordEncoder(passwordEncoder());
        } catch (Exception e) {
            throw new BeanInitializationException("Security configuration failed", e);
        }
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring()
            .antMatchers(HttpMethod.OPTIONS, "/**")
            .antMatchers("/app/**/*.{js,html}")
            .antMatchers("/i18n/**")
            .antMatchers("/content/**")
            .antMatchers("/swagger-ui/index.html")
            .antMatchers("/test/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .addFilterBefore(corsFilter, UsernamePasswordAuthenticationFilter.class)
            .exceptionHandling()
            .authenticationEntryPoint(problemSupport)
            .accessDeniedHandler(problemSupport)
            .and()
            .csrf()
            .disable()
            .headers()
            .frameOptions()
            .disable()
            .and()
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .authorizeRequests()
            .antMatchers("/api/register").permitAll()
            .antMatchers("/api/activate").permitAll()
            .antMatchers("/api/authenticate").permitAll()
            .antMatchers("/api/account/reset-password/init").permitAll()
            .antMatchers("/api/account/reset-password/finish").permitAll()
            .antMatchers("/api/**").authenticated()
            .antMatchers("/management/health").permitAll()
            .antMatchers("/management/info").permitAll()
            .antMatchers("/management/**").hasAuthority(AuthoritiesConstants.ADMIN)
            .antMatchers("/v2/api-docs/**").permitAll()
            .antMatchers("/swagger-resources/configuration/ui").permitAll()
            .antMatchers("/swagger-ui/index.html").hasAuthority(AuthoritiesConstants.ADMIN)
            .and()
            .apply(securityConfigurerAdapter());

    }

    private JWTConfigurer securityConfigurerAdapter() {
        return new JWTConfigurer(tokenProvider);
    }
}

userDetailsServicecustomerDetailsService是我的UserDetailsService实现,它们使用不同的表来检查凭证。但是,当请求出现时,我无法确切地控制使用哪个UserDetailsService。

EN

回答 1

Stack Overflow用户

发布于 2022-09-29 09:39:20

您可以使用本文https://sanketdaru.com/blog/multiple-sources-user-details-spring-security/。它有一个示例,其中定义了服务中的两个服务,并使用了该单个服务。就像我的用户详细服务代码。

代码语言:javascript
复制
@Override
public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
    List<UserEntity> users = userRepository.findByName(name);
    if (users.isEmpty()){
        return inMemoryUserDetailsService.loadUserByUsername(name);
    }
    return new UserDetailEntity (users.get(0));
}

@PostConstruct
public void init() {
    this.inMemoryUserDetailsService = initInMemoryUserDetailsService();
}

private UserDetailsService initInMemoryUserDetailsService() {
    List<UserDetails> userDetails = new ArrayList<>();
    UserDetails userDetails1 = new User("user1", "$2a$10$t/U97dFDQ0e8ujCq6728P.E1axs/aoAMsopoSUQtTchiKTP/Ps4um", Collections.singletonList(new SimpleGrantedAuthority("USER")));
    UserDetails userDetails2 = new User("admin1", "$2a$10$t/U97dFDQ0e8ujCq6728P.E1axs/aoAMsopoSUQtTchiKTP/Ps4um", Arrays.asList(new SimpleGrantedAuthority("USER"),new SimpleGrantedAuthority("ADMIN")));
    userDetails.add(userDetails1);
    userDetails.add(userDetails2);
    return new InMemoryUserDetailsManager(userDetails);
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52783807

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档