第一步:导入依赖
第二步:编写实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Integer id;
private String username;
private String password;
}
第三步:编写mapper
@Mapper
public interface UserMapper extends BaseMapper<User> {
}
第四步:编写service
@Service("userDetailsService")
public class MyUser implements UserDetailsService {
//注入mapper
@Autowired
private UserMapper myUser;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//得到用户数据
QueryWrapper<comm.xiaokai.pojo.User> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("username",username);
comm.xiaokai.pojo.User users = myUser.selectOne(queryWrapper);
/*判断*/
if (users==null ){
throw new UsernameNotFoundException("用户名不存在,认证失败");
}
/*模拟角色权限*/
List<GrantedAuthority> authorities= AuthorityUtils.commaSeparatedStringToAuthorityList("roole");
/*模拟用户数据*/
System.out.println("走到这里");
return new User(users.getUsername(),new BCryptPasswordEncoder().encode(users.getPassword()),authorities);
}
}
第五步:配置Security
@Configuration
public class MySecurity 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
protected void configure(HttpSecurity http) throws Exception {
//配置没有权限访问跳转的页面
http.exceptionHandling().accessDeniedPage("/error.html");
http.formLogin() //自定义编写的登录页面
.loginPage("/index.html") //登录页面设置
.loginProcessingUrl("/user/login") //登录访问路径
.defaultSuccessUrl("/test/index").permitAll() //登录成功之后欧,跳转路径
.and().authorizeRequests()
.antMatchers("/","/test/hello","/user/index").permitAll() //设置那些路径可以直接访问,不需要认证
//多个权限访问设置
.antMatchers("/test/index").hasAnyAuthority("admin","lpe")//当前登录用户,只有具有admin权限才可以访问
//单个权限访问设置
.antMatchers("test").hasAuthority("admin")
//如果用户具备给定的角色就允许访问,否则出现403
.antMatchers("test").hasRole("admin")
//表示用户具备任何一个角色 都可以访问
.antMatchers("test").hasAnyRole("admin","role")
.anyRequest().authenticated()
.and().csrf().disable(); //关闭csrf防护
/*记住我功能*/
http.rememberMe().rememberMeParameter("jizhuwo");
}
}
最后 进行测试