控制访问方法
1.授权匹配方法
ant/regex/mvc
//授权 有顺序 先找放行的 anyRequest放在最后
http.authorizeRequests()
//放行登录界面 ant表达式
.antMatchers("/css/**","js/**","**/*.png").permitAll()
.antMatchers("/login.html").permitAll()
.antMatchers("/error.html").permitAll()
//限制请求方式
.antMatchers(HttpMethod.POST,"/login").permitAll()
//正则表达式
.regexMatchers().permitAll()
//有资源路径写法
.mvcMatchers("/test").servletPath("/xxx").permitAll()
.anyRequest().authenticated();
2.权限判断
config类
http.authorizeRequests()
.antMatchers("/login.html").permitAll()
.antMatchers("/error.html").permitAll()
//权限 严格区分大小写
.antMatchers("/index1.html").hasAnyAuthority("admin")
//多个权限
.antMatchers("/index1.html").hasAnyAuthority("admin","ADMIN")
.anyRequest().authenticated();
3.角色判断
config类
http.authorizeRequests()
.antMatchers("/login.html").permitAll()
.antMatchers("/error.html").permitAll()
//角色 严格区分大小写
.antMatchers("/index1.html").hasRole("abc")
.anyRequest().authenticated();
4.IP判断
config类
http.authorizeRequests()
.antMatchers("/login.html").permitAll()
.antMatchers("/error.html").permitAll()
//IP地址
.antMatchers("/index1.html").hasIpAddress("127.0.1.1")
.anyRequest().authenticated();
5.UserDetailServiceImpl类
配置权限和角色
角色创建ROLE_名
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
System.out.println("UserDetail");
//1.根据用户名数据库查询 不存在抛UsernameNotFound异常
if(!"admin".equals(username)){
throw new UsernameNotFoundException("用户名不存在");
}
//2.比较密码
String password = passwordEncoder.encode("123");
return new User(username,password,
//创建权限和角色
AuthorityUtils.commaSeparatedStringToAuthorityList("admin,normal,ROLE_aaa"));
}
6.access访问控制
前面都是基于实现access表达式来实现的
可以改写
.antMatchers("/index1.html").hasIpAddress("127.0.1.1")
.antMatchers("/index1.html").access("hasIpAddress('11.11.11.1')")
自定义access实现
MyServiceImpl类
@Service
public class MyServiceImpl implements MyService {
@Override
public boolean hasPermission(HttpServletRequest httpServletRequest, Authentication authentication) {
//获取主体
Object obj = authentication.getPrincipal();
if(obj instanceof UserDetails){
//获取权限
UserDetails userDetails = (UserDetails) obj;
Collection<? extends GrantedAuthority> authorities = userDetails.getAuthorities();
//判断请求的URI是否在权限里
return authorities.contains(new SimpleGrantedAuthority(httpServletRequest.getRequestURI()));
}
return false;
}
}
配置类中
//.anyRequest().authenticated()
//自定义实现
.anyRequest().access("@myServiceImpl.hasPermission(request,authentication)");
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律