首页 > 其他分享 >springSecurity初入门

springSecurity初入门

时间:2024-07-30 13:59:46浏览次数:7  
标签:return 入门 用户 springSecurity user new 权限 public

引入依赖(引入后即可启动服务器,会自动进行页面拦截,未登录用户会跳转到默认的登陆页面,账号为user,密码在服务器启动时会在控制台输出:Using generated security password:......)

  <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-security</artifactId>
  </dependency>

修改配置文件application只在需要定义一个账号和密码的时候进行修改)

#定义账号和密码,这里只能定义一个账号和密码
spring.security.user.name=admin
spring.security.user.password=123456

编写service类(基于数据库查询用户时编写该类,使用数据库查询不需要编写基于内存定义的代码)

@Service
public class MyUserDetailService implements UserDetailsService {
 @Autowired
 private UserMapper userMapper;	//注入对应mapper使用sql进行数据库操作
 @Autowired
 private PermissionMapper permissionMapper;	//注入权限表mapper进行数据库操作
 @Override
 public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
     //根据账号查询用户信息,username必须唯一
     QueryWrapper<User> wrapper=new QueryWrapper<>();
     wrapper.eq("username",username);
     User user = userMapper.selectOne(wrapper);	//在数据库根据username查询该用户新
     if(Objects.nonNull(user)){	//判断用户是否存在
         //如果存在查询该用户具有的权限
         List<Permission> permissions = permissionMapper.selectByUserId(user.getUserid());
         //将存放权限的集合转化为返回值要求的集合类型
         List<SimpleGrantedAuthority> collect = permissions.stream().map(item -> new SimpleGrantedAuthority(item.getPercode())).collect(Collectors.toList());
         //转换集合方法等价于该遍历的方法(两个方法存在一个即可)
         List<SimpleGrantedAuthority> list=new ArrayList<>() ;
         for(Permission  p:permissions){
             SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(p.getPercode());
             list.add(simpleGrantedAuthority);
         }
         return new org.springframework.security.core.userdetails.User(username,user.getUserpwd(),collect);
     }
     return null;
 }
}

编写配置类(在启动类application中使用EnableGlobalMethodSecurity(prePostEnabled=true)开启权限绑定的注解驱动 )

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter{
@Bean	//设置密码加密器	使用:先new出该对象PasswordEncoder passwordEncoder=new BCryptPasswordEncoder();
public PasswordEncoder passwordEncoder() {	//passwordEncoder.encode("密码")进行加密
  return new BCryptPasswordEncoder();	//passwordEncoder.matches("密码", 加密后的密码)比较密码是否一致
}
@Autowired
private MyUserDetailService userDetailService;	//注入自定义的service类,用于基于数据库进行用户验证
@Override	//基于数据库定义用户,使用该方法后不需要基于内存定义的代码
 protected void configure(AuthenticationManagerBuilder auth) throws Exception{
     auth.userDetailsService(userDetailService);
 }
@Override	//基于内存定义多用户,定义后配置文件中的账号密码会失效,基于数据库时不使用该方法
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()	//基于内存完成认证和授权
      .withUser("user1")	//用户名
      .password(passwordEncoder().encode("123456"))	//密码
      .roles("admin")	//当前用户具有的角色
      .authorities("user:select","user:delete","user:insert","user:update")	//当前用户具有的权限
      .and()	//下一个角色的连接符
      .withUser("user2")
      .password(passwordEncoder().encode("123456"))
      .roles("user")
      .authorities("user:select","user:export");
}
@Override	//一些额外的配置
protected void configure(HttpSecurity http) throws Exception {
  http.formLogin()
          .loginPage("/login.html")	//未登录时跳转的登录页面
          .loginProcessingUrl("/login")	//登录页面提交的处理路径 默认为/login
          .successForwardUrl("/success")	//登录成功跳转的路径 必须为post请求
          .failureForwardUrl("/fail")	//登录失败跳转的路径 必须为post请求
          .permitAll();	//上面的请求路径无需登录
  http.exceptionHandling().accessDeniedPage("/403.html")	//权限不足时跳转的页面
  http.csrf().disable();	//禁用跨域伪造请求的过滤器(必带)
  http.authorizeRequests().anyRequest().authenticated();	//除了其之上的请求,其他请求都需要登录验证
}
}

controller层(权限绑定需在启动类开启绑定注解驱动,使用该绑定就不需要在配置类中进行绑定了)

@GetMapping("info")
@PreAuthorize("hasAuthority('user:info')")	//资源执行前判断当前用户是否拥有user:info权限
public Authentication info(){	//获取当前用户信息
  SecurityContext context = SecurityContextHolder.getContext();	//获取SecurityContext对象
	 Authentication authentication = context.getAuthentication();	//把用户信息封装到Authontication中
  UserDetails principal = (UserDetails) authentication.getPrincipal();	//获取用户账号密码等信息
  return authentication;
}
@GetMapping("insert")
@PreAuthorize("hasAuthority('user:select')")	//资源执行前判断当前用户是否拥有user:select权限
 public String insert(){
     System.out.println("添加用户");
     return "添加用户";
 }
@GetMapping("delete")
 public String delete(){
     System.out.println("删除用户");
     return "删除用户";
 }
@GetMapping("update")
 public String update(){
     System.out.println("修改用户");
     return "修改用户";
 }
@GetMapping("select")
 public String select(){
     System.out.println("查询用户");
     return "查询用户";
 }

标签:return,入门,用户,springSecurity,user,new,权限,public
From: https://blog.csdn.net/Baizeh/article/details/140791157

相关文章

  • C++入门基础—(命名空间,输入输出,缺省参数,函数重载)
    目录1.1 C++发展史1.2C++版本更新1.3C++学习参考文档1.4C++的第一个程序2命名空间2.1命名空间的价值2.2namespace的定义1.命名空间中可以定义变量/函数/类型2.命名空间可以嵌套3.多⽂件中可以定义同名namespace,他们会默认合并到⼀起,就像同⼀个namespace⼀......
  • stable diffusion 入门教程
    sd基础工作原理&入门输入提示词后有文本编码器将提示词编译成特征向量,vae编码器将特征向量传入潜空间内,特征向量在潜空间内不断降噪,最后通过vae解码器将降噪之后的特征向量解码成一个个像素组成的图片一般选中默认vae模型解码编码的模型CLIP值越大,提前停止的越快,我们提......
  • 大模型RAG入门及实践
    前言在大语言模型(LLM)飞速发展的今天,LLMs正不断地充实和改进我们周边的各种工具和应用。如果说现在基于LLM最火热的应用技术是什么,检索增强生成(RAG,RetrievalAugmentedGeneration)技术必占据重要的一席。RAG最初是为了解决LLM的各类问题的产生的,但后面大家发现在现阶......
  • SRC漏洞挖掘上分技巧(非常详细)零基础入门到精通,收藏这一篇就够了
    0x00简介今天就分享一下公益SRC漏洞的批量挖掘的技巧和所要用到的一些相关的工具和脚本出来和各位师傅交流一下,不足之处还希望师傅们多多指教。0x01国内的一些公益src漏洞平台漏洞盒子:https://www.vulbox.com``补天漏洞响应平台:https://www.butian.net``CNNVD信......
  • CTFshow web入门vip 文件上传
    web151题目提示前端校验不可靠,看源码可以看到是传到upload.php这个文件去接受文件上传,文件类型为图片,后缀限制为png然后把前端验证修改一下,把文件后缀限制改成php写个一句话木马传进去1.php<?phpeval($_POST['x']);?>url中需要加入我们传入文件的目录/upload.php,并指定/......
  • AI产品经理如何入门?
    随着人工智能技术的迅猛发展,AI产品经理成为了一个炙手可热的职业。为了更好地胜任这一角色,产品经理不仅需要具备一定的AI基础知识,还需要了解AI行业的现状以及掌握数学统计学的基本概念。本文将为您详细介绍这些必备技能。1、AI行业现状AI产品经理首先需要了解AI行业的整体......
  • 【入门】汉诺塔的移动次数 - 题解
    【入门】汉诺塔的移动次数时间限制:C/C++1000MS,其他语言2000MS内存限制:C/C++128MB,其他语言256MB描述汉诺塔的问题大家都已经很熟悉了,有三个柱子,每个柱子上有一些大小不一的金片,要把金片从\(A\)柱移动到\(C\)柱,可以借助\(B\)柱,请问\(n\)个金片的情况下,需要最少移......
  • 【入门】统计每个月兔子的总数 - 题解
    【入门】统计每个月兔子的总数时间限制:C/C++1000MS,其他语言2000MS内存限制:C/C++16MB,其他语言32MB描述有一对兔子,从出生后第3个月起每个月都生一对兔子,一对小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问第\(n\)个月(\(n<=50\))的兔子总数为多少对?输入描述......
  • LLM(大语言模型)和AIGC入门学习路线图
    01—学习路线图基础了解目标:理解人工智能、机器学习、深度学习的基本概念。资源:在线课程(如Coursera,edX上的入门课程)、博客文章、YouTube视频。专业知识目标:深入了解大型语言模型(如GPT-4)和人工智能生成内容的工作原理。资源:阅读相关的学术论文、技术......
  • Django-APP及项目入门
    1.APP定义:Django中功能的细分,每个APP有独立的数据库、表结构、HTML模版、CSS。创建APPpythonmanage.pystartappapp01重要文件介绍views.py:常用文件,urls中的函数常常在此处定义。models.py:常用文件,对数据库进行操作。2.项目入门确保app也注册(settings.py)......