spring boot+spring security 入门案例

Maven 依赖

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>

三个配置类 SelfUserDetails

@Data
@Accessors(chain = true)
public class SelfUserDetails implements UserDetails {
private Set<? extends GrantedAuthority> authorities;//角色配置类
private Account account;//用户实体

@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return this.authorities;
}


@Override
public String getPassword() {
return this.account.getPassword();
}

@Override
public String getUsername() {
return this.account.getName();
}

@Override
public boolean isAccountNonExpired() {
return true;
}

@Override
public boolean isAccountNonLocked() {
return true;
}

@Override
public boolean isCredentialsNonExpired() {
return true;
}

@Override
public boolean isEnabled() {
return true;
}
public void select(String name){

Account name1 = new Account().selectOne(new MyWrapper().eq("name", name));
this.account=name1;
}
}
SelfUserDetailsService 是UserDetailService实现类
@Component
public class SelfUserDetailsService implements UserDetailsService {

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
SelfUserDetails selfUserDetails = new SelfUserDetails();
selfUserDetails.select(username);
if(selfUserDetails.getAccount()==null){
//仍需要细化处理
throw new UsernameNotFoundException("该用户不存在");
}
Set authoritiesSet = new HashSet();
// 模拟从数据库中获取用户角色
GrantedAuthority authority = new SimpleGrantedAuthority("ROLE_ADMIN");

authoritiesSet.add(authority);
selfUserDetails.setAuthorities(authoritiesSet);
return selfUserDetails;
}
}

SpringSecurityConfig是WebSecurityConfigurerAdapter实现类
@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
SelfUserDetailsService selfUserDetailsService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// 加入自定义的安全认证
// auth.authenticationProvider(provider);
auth.userDetailsService(selfUserDetailsService).passwordEncoder(new BCryptPasswordEncoder());
}

}
要注意的是密码存入数据库前需要用BCryptPasswordEncoder加密
列如:
MyWrapper<Account> wrapper=new MyWrapper<Account>();
Account account = accountService.selectList(wrapper.eq("name", "chenli12")).get(0);
System.out.println(account);
BCryptPasswordEncoder bCryptPasswordEncoder=new BCryptPasswordEncoder();
account.setPassword(bCryptPasswordEncoder.encode(account.getPassword()));
account.update(wrapper.ge("password",account.getPassword()));
如果不用加密的话 在configure函数中就可以写成
auth.userDetailsService(selfUserDetailsService)就行了
 
上一篇:Java学习笔记——封装


下一篇:冲刺博客Day7