spring security自定义UserDetailsService

验证身份就是加载响应的UserDetails,看看是否和用户输入的账号、密码、权限等信息匹配。此步骤由实现AuthenticationProvider的DaoAuthenticationProvider(它利用UserDetailsService验证用户名、密码和授权)处理。包含 GrantedAuthority 的 UserDetails对象在构建 Authentication对象时填入数据。

 

spring security自定义UserDetailsService_第1张图片

@Component
public class MyUserDetaisService implements UserDetailsService, SocialUserDetailsService {

    /* (non-Javadoc)
     * @see org.springframework.security.core.userdetails.UserDetailsService#loadUserByUsername(java.lang.String)
     */

//注入数据库操作
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        return loadUserByUserId(username);
    }

    @Override
    public SocialUserDetails loadUserByUserId(String userId) throws UsernameNotFoundException {
       在数据库中进行比对

 if(StringUtils.equals(userId, "zhangsan")){
            String password = new BCryptPasswordEncoder().encode("111111");
            return new SocialUser("zhangsan", password, AuthorityUtils.createAuthorityList("admin","xxxx"));
        }
        return null;
    }

安全配置:

@Configuration
@EnableWebSecurity
//@EnableGlobalMethodSecurity(prePostEnabled = true)
//@EnableOAuth2Sso
public class SecurityConfig extends WebSecurityConfigurerAdapter {
      //注入自定义MyUserDetaisService

 @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(myUserDetaisService)
            .passwordEncoder(new BCryptPasswordEncoder());
    }

}
 

你可能感兴趣的:(spring,boot)