spring boot 整合 spring security 之使用資料庫驗證
阿新 • • 發佈:2019-02-19
spring boot 整合 spring security 參見上一篇文章.
重寫WebSecurityConfigurerAdapter中的configureGlobal方法
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(custProvider);
}
其中custProvider是AuthenticationProvider介面的一個實現類例項
實現AuthenticationProvider介面
@Component
public class CustAuthenticationProvider implements AuthenticationProvider {
@Autowired
private CustUserDetailsService userService;
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String username = authentication.getName();
String password = (String) authentication.getCredentials();
CustUserDetails userDetials = (CustUserDetails) userService.loadUserByUsername(username);
Collection<? extends GrantedAuthority> authorities = userDetials.getAuthorities();
return new UsernamePasswordAuthenticationToken(userDetials, password, authorities);
}
@Override
public boolean supports(Class<?> arg0) {
return true;
}
}
其中CustUserDetailsService是UserDetailsService介面的實現類;CustUserDetails是UserDetails介面的實現類
實現UserDetailsService介面
@Component
public class SnailUserDetailsService implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
return new CustUserDetails();
}
}
重寫loadUserByUsername方法,實現依據使用者名稱稱從資料庫中查詢使用者的羅輯,並返回UserDetails物件,這裡為了簡單我就直接建立了一個
實現UserDetails介面
public class CustUserDetails implements UserDetails {
private static final long serialVersionUID = -1922135614793714181L;
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
boolean flag = false;
if (flag) {
return AuthorityUtils.commaSeparatedStringToAuthorityList("");
}
StringBuilder commaBuilder = new StringBuilder();
commaBuilder.append("SUPPER MANAGER");
commaBuilder.append(",");
commaBuilder.append("hello");
commaBuilder.append(",");
commaBuilder.append("view");
return AuthorityUtils.commaSeparatedStringToAuthorityList(commaBuilder.toString());
}
@Override
public String getPassword() {
return "123456";
}
@Override
public String getUsername() {
return "administrator";
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
}
主要是實現getAuthorities方法根據使用者將使用者所有的許可權查詢出來並返回Collection