繁体   English   中英

如何在 spring 引导中验证具有特定角色的用户?

[英]How to authenticate user with specific role in spring boot?

SecurityConfiguration

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    CustomUserDetailService customUserDetailService;

    @Autowired
    CustomSuccessHandler successHandler;

    @Autowired
    CustomFailureHandler failureHandler;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    CustomBeanDefinition customBeanDefinition;


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        UserDetailsService userDetailsService = customBeanDefinition.jpaUserDetails();
        auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/login").permitAll()
                .antMatchers("/signup").permitAll()
                .antMatchers("/register").permitAll()
                .antMatchers("/book/index").hasAuthority("ADMIN")
                .anyRequest().authenticated()
                .and()
                .csrf().disable()
                .formLogin()
                .successHandler(successHandler)
                .loginPage("/login")
                .failureHandler(failureHandler)
                .usernameParameter("username")
                .passwordParameter("password")
                .and().logout().permitAll();

    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web
                .ignoring()
                .antMatchers("/resources/**", "/static/**", "/css/**", "/js/**", "/img/**", "/icon/**");
    }
}

CustomUserDetailService

@Service
public class CustomUserDetailService implements UserDetailsService {

    @Autowired
    UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userRepository.findByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("User not found");
        }
        List<GrantedAuthority> authorities = getUserAuthority(user.getRoles());
        UserDetails userDetails = buildUserForAuthentication(user, authorities);
        return userDetails;
    }

    private List<GrantedAuthority> getUserAuthority(Set<Role> userRoles) {
        Set<GrantedAuthority> roles = new HashSet<>();
        for (Role role : userRoles) {
            roles.add(new SimpleGrantedAuthority(role.getAuthority()));
        }
        return new ArrayList<>(roles);
    }

    private UserDetails buildUserForAuthentication(User user, List<GrantedAuthority> authorities) {
        return new org.springframework.security.core.userdetails.User(
                user.getUsername(), user.getPassword(), authorities);
    }
}

CustomBeanDefinition

@Configuration
public class CustomBeanDefinition {

    @Bean
    public UserDetailsService jpaUserDetails() {
        return new CustomUserDetailService();
    }

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

UserService

@Service
public class UserService {

    private UserRepository userRepository;
    private RoleRepository roleRepository;
    private BCryptPasswordEncoder passwordEncoder;

    @Autowired
    public UserService(UserRepository userRepository,
                       RoleRepository roleRepository, BCryptPasswordEncoder passwordEncoder) {
        this.userRepository = userRepository;
        this.roleRepository = roleRepository;
        this.passwordEncoder = passwordEncoder;
    }

    public void save(String username, String email, String password, String name) {
        User user = userRepository.findByUsername(username);
        if (user == null) {
            user = new User();
            user.setName(name);
            user.setUsername(username);
            user.setEmail(email);
            user.setPassword(passwordEncoder.encode(password));
            user.setActive(true);
            Role role = roleRepository.findByAuthority("ADMIN");
            user.setRoles(new HashSet<>(Collections.singletonList(role)));
            userRepository.save(user);
            System.out.println("...user saved with ADMIN role");
        }
    }
}

在我的应用程序中,用户当前已成功保存并与特定角色绑定。

但是,当我尝试使用保存的用户对我的应用程序进行身份验证时,它永远不会继续成功处理程序,它会将我重定向到失败处理程序。 看起来身份验证不起作用。

任何帮助,将不胜感激。

更改您的安全配置,如下所示的 configure() 方法,

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  auth.userDetailsService(customUserDetailService).
        passwordEncoder(bCryptPasswordEncoder);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM