開啓security過濾支持:java
建立一個初始化類繼承spring
AbstractSecurityWebApplicationInitializer
在配置類中添加@EnableWebSecutity 註解。springboot
配置認證與受權:ide
繼承 WebSecurityConfigurerAdapterspring-boot
實現configure 方法fetch
configure(AuthenticationManagerBuilder auth)
針對用戶管理(用戶來源,用戶密碼效驗規則)ui
configure(HttpSecurity http)
請求攔截。this
自定義數據源:spa
實現 UserDetailsService 接口code
重寫加載用戶的方法:
@Service public class SysUserServiceImpl implements UserDetailsService, SysUserService { @Autowired SysUserRepo repo; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { SysUser user = repo.findByName(username); if(user==null){ throw new UsernameNotFoundException("用戶不存在"); } return user; } }
註冊bean
@Bean public UserDetailsService userDetailsService(){ return new SysUserServiceImpl(); }
用戶受權配置
@Override protected void configure(HttpSecurity http) throws Exception { // super.configure(http); // http 用戶受權請求 http.authorizeRequests() // .antMatchers("/admin/**") // .hasAnyRole("ROLE_ADMIN") // 任何請求進行受權驗證 .anyRequest().authenticated() .and() // 登陸註冊 .formLogin() .loginPage("/login") .failureUrl("/login?error") .permitAll() .and() .logout().permitAll(); }
springboot 添加依賴:
implementation 'org.springframework.boot:spring-boot-starter-security'
經過實體類實現UserDetails接口,並重寫獲取受權方法,而且新建一個實現UserDetailsService 的類,並註冊bean
getAuthorities
package com.duoke.demo.pojo; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import javax.persistence.*; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * 定義系統用戶 */ @Entity public class SysUser implements UserDetails{ @Id private String id; private String name; private String password; @ManyToMany(cascade = {CascadeType.REFRESH},fetch = FetchType.EAGER) private List<SysRole> roles; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public void setPassword(String password) { this.password = password; } public List<SysRole> getRoles() { return roles; } public void setRoles(List<SysRole> roles) { this.roles = roles; } @Override // 添加用戶叫角色受權信息 public Collection<? extends GrantedAuthority> getAuthorities() { List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); List<SysRole> roles = this.getRoles(); for (SysRole role:roles) { authorities.add(new SimpleGrantedAuthority(role.getName())); } return authorities; } @Override public String getPassword() { return password; } @Override public String getUsername() { return null; } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return true; } }