Spring Spring应用程序可以使用两个不同的表进行登录吗?

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

在我目前的项目中,我有两个独立的实体。

  1. 用户: - 对用户进行身份验证
  2. 客户: - 验证客户身份

我很困惑我们如何通过Spring安全性管理两个独立实体的同一项目中的登录过程?

截至目前,它正在与一个用户实体合作,现在我必须在Customer表的帮助下为客户集成一个以上的登录。

可能吗 ?

Note :- Due to some another requirement i can't use the same table for both users and customer.

我正在分享一些代码以获得更多许可。

Below code is the implementation of user detail service.

private final Logger log = LoggerFactory.getLogger(DomainUserDetailsService.class);

private final UserLoginRepository userRepository;

public DomainUserDetailsService(UserLoginRepository userRepository) {
    this.userRepository = userRepository;
}

@Override
@Transactional
public UserDetails loadUserByUsername(final String login) {
    log.debug("Authenticating {}", login);

    if (new EmailValidator().isValid(login, null)) {
        Optional<User> userByEmailFromDatabase = userRepository.findOneWithAuthoritiesByLogin(login);
        return userByEmailFromDatabase.map(user -> createSpringSecurityUser(login, user))
            .orElseThrow(() -> new UsernameNotFoundException("User with email " + login + " was not found in the database"));
    }

    String lowercaseLogin = login.toLowerCase(Locale.ENGLISH);
    Optional<User> userByLoginFromDatabase = userRepository.findOneWithAuthoritiesByLogin(lowercaseLogin);
    return userByLoginFromDatabase.map(user -> createSpringSecurityUser(lowercaseLogin, user))
        .orElseThrow(() -> new UsernameNotFoundException("User " + lowercaseLogin + " was not found in the database"));

}

private org.springframework.security.core.userdetails.User createSpringSecurityUser(String lowercaseLogin, User user) {

    List<GrantedAuthority> grantedAuthorities = user.getAuthorities().stream()
        .map(authority -> new SimpleGrantedAuthority(authority.getName()))
        .collect(Collectors.toList());
    return new org.springframework.security.core.userdetails.User(user.getLogin(),
        user.getPassword(),
        grantedAuthorities);
}

}

Below is the implantation of security config class.

private final AuthenticationManagerBuilder authenticationManagerBuilder;

private final UserDetailsService userDetailsService;

private final TokenProvider tokenProvider;

private final CorsFilter corsFilter;

private final SecurityProblemSupport problemSupport;

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

@PostConstruct
public void init() {
    try {
        authenticationManagerBuilder
            .userDetailsService(userDetailsService)
            .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");
}

@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/userLogin").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);
}

}

Login api

@PostMapping("/userLogin")
@Timed
public Response<JWTToken> authorize(
        @Valid @RequestBody UserLoginReq userLoginReq) {

    Map<String, Object> responseData = null;
    try {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
                userLoginReq.getUsername(), userLoginReq.getPassword());

        Authentication authentication = this.authenticationManager
                .authenticate(authenticationToken);

        SecurityContextHolder.getContext()
                .setAuthentication(authentication);

}

spring-boot authentication spring-security
1个回答
1
投票

起初客户也是用户,不是吗?所以也许更简单的解决方案是创建客户也作为用户(使用一些标志/数据库字段usertype ={USER|CUSTOMER|...})。如果您仍然需要管理两个实体,那么您的方法是正确的,但在您的DetailService中,只需实现另一个方法,该方法将读取客户实体,然后创建spring的用户。

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