使用自己的数据库中的用户进行验证
1.User 表结构
CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(18) DEFAULT NULL, `password` varchar(18) DEFAULT 'zzz123', `sex` varchar(2) DEFAULT NULL, `age` int(11) DEFAULT NULL, `disabled` bit(1) NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=22 DEFAULT CHARSET=utf8;
2. 引用依赖 POM.XML
org.springframework.boot spring-boot-starter-security org.springframework.security spring-security-test test
3. User.java
@Entitypublic class User implements UserDetails { @Transient Listlist = new ArrayList (); @Transient private String name; @Id @GeneratedValue private Long id; @Column(nullable = false) private String username; @Column(nullable = false) private String password; @Column(nullable = false) private Integer age; private boolean disabled; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public Collection getAuthorities() { return list; } public void setAuthorities(List list) { this.list = list; } @Override public String getPassword() { // TODO Auto-generated method stub return password; } public void setPassword(String password) { // TODO Auto-generated method stub this.password = password; } @Override public String getUsername() { // TODO Auto-generated method stub return username; } public void setUsername(String username){ this.username = username; } @Override public boolean isAccountNonExpired() { // TODO Auto-generated method stub return true; } @Override public boolean isAccountNonLocked() { // TODO Auto-generated method stub return true; } @Override public boolean isCredentialsNonExpired() { // TODO Auto-generated method stub return true; } @Override public boolean isEnabled() { // TODO Auto-generated method stub return true; }}
4. UserRepository.java
public interface UserRepository extends JpaRepository{ List findByUsername(String username);}
6. UserServiceImpl.java
@Servicepublic class UserServiceImpl implements IUserService { private static final Log logger = LogFactory.getLog(UserServiceImpl.class); @Autowired UserRepository dao; @Override public void AddUser(User user) { // TODO Auto-generated method stub dao.save(user); logger.info("add user"); } @Override public ListfindUserByUsername(String username) { // TODO Auto-generated method stub return dao.findByUsername(username); }}
7. SecurityConfig.java 主要配置文件
@Configuration@EnableWebSecurity@EnableGlobalMethodSecuritypublic class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired @Qualifier("customUserDetailService") private UserDetailsService userDetailsService; /**定义认证用户信息获取来源,密码校验规则等*/ @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { //auth.inMemoryAuthentication().withUser("shili").password("zzz123").roles("USER"); //auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()); auth.userDetailsService(userDetailsService); } /**定义安全策略*/ @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests()//配置安全策略 .antMatchers("/css/**","/js/**","/img/**","/sayhello").permitAll()//不需要权限的URL .anyRequest().authenticated()//其他任意URL都需要验证权限 .and() .logout() .permitAll() .and() .formLogin(); } @Bean public BCryptPasswordEncoder passwordEncoder(){ BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(); return encoder; } }
8.CustomUserDetailService 使用自己的数据库中的用户
@Service("customUserDetailService")public class CustomUserDetailService implements UserDetailsService { @Autowired private IUserService userService; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { // TODO Auto-generated method stub Listusers = userService.findUserByUsername(username); if(users==null||users.size()==0){ throw new UsernameNotFoundException(""); } User user = users.get(0); List authorities = new ArrayList<>(); authorities.add(new SimpleGrantedAuthority("ROLE_USER")); user.setAuthorities(authorities); return user; }}
随便写一个控制器测试一下
@RestControllerpublic class HelloSecurity { @RequestMapping("/security") public String security() { return "hello world security"; } }