# 第一步
~~~
@Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService {
@Autowired
private UsersMapper usersMapper;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
String password = passwordEncoder.encode("aaa");//加密密碼
//使用userMapper方法,使用用戶名查詢數據庫
QueryWrapper<Users> wrapper = new QueryWrapper<>();//查詢構造器
wrapper.eq("username",username);//條件
Users users= usersMapper.selectOne(wrapper);//查詢一條數據
if (users==null){//用戶不存在
throw new UsernameNotFoundException("用戶不存在");
}
List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("admin");//權限集合
return new User(users.getUsername(),password,auths);//用戶名,密碼,權限
}
}
~~~
# 第二步
~~~
.antMatchers("/edu").hasAuthority("admin")
~~~
~~~
//第二種
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService)//自定義設置類
.passwordEncoder(password());
}
@Bean //加密方式
public PasswordEncoder password(){
return new BCryptPasswordEncoder();
}
@Override
public void configure(HttpSecurity http) throws Exception {
http.formLogin()//設置自定義的登錄頁面
.loginPage("/login.html")//登錄頁面設置
.loginProcessingUrl("/user/login")//登錄訪問的路徑Security 的
.defaultSuccessUrl("/edu").permitAll() //登錄成功,跳轉路徑
.and().authorizeRequests()//設置被保護的路徑
.antMatchers("/").permitAll()//設置不需要驗證的路徑
//表示當前用戶只有admin權限才可以訪問這個路徑
.antMatchers("/edu").hasAuthority("admin")
.anyRequest().authenticated()//設置所有路徑都可以訪問
.and().csrf().disable();//關閉csrf防護
}
}
~~~
`注意: 這個針對某個角色時 設置多個角色時需要多個角色同時有才行`
# hasAnyAuthority 針對某一個權限有一個角色就行
~~~
.antMatchers("/edu").hasAnyAuthority("admin,mesage")
~~~
# hasRole 會在角色前加ROLE_
~~~
.antMatchers("/edu").hasRole("admin")
~~~
# hasAanRole 多個角色會在角色前加ROLE_
.antMatchers("/edu").hasAndRole("admin,msg")