如何在Spring Boot中对具有特定角色的用户进行身份验证?

huangapple 未分类评论43阅读模式
英文:

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");
        }
    }
}

在我的应用程序中,用户目前可以成功保存并绑定到特定角色。

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

任何帮助将不胜感激。

英文:
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(&quot;/&quot;).permitAll()
                .antMatchers(&quot;/login&quot;).permitAll()
                .antMatchers(&quot;/signup&quot;).permitAll()
                .antMatchers(&quot;/register&quot;).permitAll()
                .antMatchers(&quot;/book/index&quot;).hasAuthority(&quot;ADMIN&quot;)
                .anyRequest().authenticated()
                .and()
                .csrf().disable()
                .formLogin()
                .successHandler(successHandler)
                .loginPage(&quot;/login&quot;)
                .failureHandler(failureHandler)
                .usernameParameter(&quot;username&quot;)
                .passwordParameter(&quot;password&quot;)
                .and().logout().permitAll();

    }

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

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(&quot;User not found&quot;);
        }
        List&lt;GrantedAuthority&gt; authorities = getUserAuthority(user.getRoles());
        UserDetails userDetails = buildUserForAuthentication(user, authorities);
        return userDetails;
    }

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

    private UserDetails buildUserForAuthentication(User user, List&lt;GrantedAuthority&gt; 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(&quot;ADMIN&quot;);
            user.setRoles(new HashSet&lt;&gt;(Collections.singletonList(role)));
            userRepository.save(user);
            System.out.println(&quot;...user saved with ADMIN role&quot;);
        }
    }
}

In my application user is currently being saved successfully and binding with specific role.

However, when i try to authenticate my application with saved user, it never goes on success handler, it redirects me on failure handler.
It looks like authentication is not working.

Any help would be appreciated.

答案1

得分: -1

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

Change your Security Configuration, configure() method like below,

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

huangapple
  • 本文由 发表于 2020年4月5日 03:15:21
  • 转载请务必保留本文链接:https://java.coder-hub.com/61033478.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定