1. 程式人生 > 其它 >spring boot+spring security 入門案例

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)就行了