SecurityConfig
@Configuration
@EnableWebSecurity
public class SecurityConfig implements WebMvcConfigurer {
@Bean
public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
//
httpSecurity.authorizeHttpRequests()
.requestMatchers("/**").hasRole("user")
.and()
.formLogin()
.and().csrf().disable();
return httpSecurity.build();
}
//指定密码加密器后不需要在加密后的密码前指定加密类型 exp:{bcrypt}
@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
//直接设置登录角色
@Bean
public UserDetailsService userDetailsService(){
UserDetails userDetails = User.withDefaultPasswordEncoder()
.username("user").password("123456").roles("user").build();
return new InMemoryUserDetailsManager(userDetails);
}
}
UserDetailsServiceImpl
@Service
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {
UserMapper userMapper;
@Autowired
void UserDetailsServiceImpl(UserMapper userMapper){
this.userMapper = userMapper;
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
UserAccount userAccount = userMapper.findByUsername(username);
if(null == userAccount) throw new UsernameNotFoundException("用户不存在");
List<GrantedAuthority> u = AuthorityUtils.createAuthorityList("ROLE_user");
PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
log.info("==================================================================================");
log.info("加密后{}",passwordEncoder.encode(userAccount.getPassword()));
log.info("加密后{}",encoder.encode(userAccount.getPassword()));
//使用 PasswordEncoderFactories.createDelegatingPasswordEncoder(); 会在加密后的字符串前加{加密器类型}
//如果在config中提前指定了加密类型,则不需要再加{类型},直接使用 BCryptPasswordEncoder加密 就行
return new User(userAccount.getName(),encoder.encode(userAccount.getPassword()), u);
}
}
标签:加密,Spring,userMapper,return,userAccount,new,Security,public
From: https://www.cnblogs.com/yinchrn/p/17306737.html