SpringBoot学习(二)—— springboot快速整合spring security组件

Dear 丶 2023-06-13 09:35 64阅读 0赞

SpringBoot学习(一)—— idea 快速搭建 Spring boot 框架

SpringBoot学习(二)—— springboot快速整合spring security组件

SpringBoot学习(三)—— springboot快速整合swagger文档

SpringBoot学习(四)—— springboot快速整合Mybatis组件

SpringBoot学习(五)—— springboot快速整合Druid

SpringBoot学习(六)—— springboot快速整合RabbitMQ

SpringBoot学习(七)—— springboot快速整合Redis

Spring Security

简介

spring security的核心功能为认证(Authentication),授权(Authorization),即认证用户是否能访问该系统,和授权用户可以在系统中进行哪些操作。

引入spring security组件

在 pom.xml 中加入

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-security</artifactId>
  4. </dependency>
  5. <dependency>
  6. <groupId>org.springframework.security</groupId>
  7. <artifactId>spring-security-test</artifactId>
  8. <scope>test</scope>
  9. </dependency>

验证组件是否起到作用,现在不更改框架内的任何内容,启动项目,浏览器中依旧输入 http://localhost:8080 ,可看到如下界面,之前可以直接进入spring boot的初始界面,现在已经看不见了,spring security 导入后默认已经开启了验证,必须先登录验证通过后才能访问。

\[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-4UZ4rXKM-1573807374683)(assets/1573802625147.png)\]

如果代码中不做任何设置,默认的账户是 user,默认的密码随着项目的启动,会打印在控制台中。
在这里插入图片描述

输入账号密码,即可进入默认的初始界面。
在这里插入图片描述

代码实战

为了最快最简单最直接的认识这个组件,直接把用户密码写入内存中,项目启动即存在,避免还有建表,实体类,数据库操作等与之无关的内容。命名使用最为简单粗暴的方式,排除一切干扰,用最少的精力掌握该组件的使用。

新增代码目录
在这里插入图片描述

index.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. </head>
  7. <body>
  8. SPRING BOOT !!!
  9. </body>
  10. </html>

error.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. </head>
  7. <body>
  8. 错误
  9. </body>
  10. </html>

UserController

  1. package com.example.controller;
  2. import org.springframework.stereotype.Controller;
  3. import org.springframework.web.bind.annotation.RequestMapping;
  4. import org.springframework.web.bind.annotation.ResponseBody;
  5. @Controller
  6. @RequestMapping("user")
  7. public class UserController {
  8. @RequestMapping("/addUser")
  9. @ResponseBody
  10. String addUser() {
  11. return "这是添加用户!!!";
  12. }
  13. @RequestMapping("/deleteUser")
  14. @ResponseBody
  15. String deleteUser() {
  16. return "这是删除用户!!!";
  17. }
  18. @RequestMapping("/updateUser")
  19. @ResponseBody
  20. String updateUser() {
  21. return "这是修改用户!!!";
  22. }
  23. @RequestMapping("/findAllUsers")
  24. @ResponseBody
  25. String findAllUsers() {
  26. return "这是查询用户!!!";
  27. }
  28. }

UserSecurityConfig

  1. package com.example.config;
  2. import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
  3. import org.springframework.security.config.annotation.web.builders.HttpSecurity;
  4. import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
  5. import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
  6. //注解开启 Spring Security 安全认证与授权
  7. @EnableWebSecurity
  8. public class UserSecurityConfig extends WebSecurityConfigurerAdapter {
  9. //用户认证
  10. @Override
  11. protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  12. //内存里面放着
  13. auth.inMemoryAuthentication().passwordEncoder(new MyPasswordEncoder())
  14. //添加用户,密码,角色
  15. .withUser("zs").password("123456").roles("AAA")
  16. //链式编程
  17. .and()
  18. .withUser("ls").password("123456").roles("BBB")
  19. .and()
  20. .withUser("ww").password("123456").roles("CCC", "primary")
  21. .and()
  22. .withUser("zl").password("123456").roles("primary");
  23. }
  24. //用户授权
  25. @Override
  26. protected void configure(HttpSecurity http) throws Exception {
  27. /** * permitAll():允许一切用户访问 * hasRole():url请求允许访问的角色 * hasAnyRole() : url请求允许访问的多个角色 * access():允许访问的角色,permitAll、hasRole、hasAnyRole 底层都是调用 access 方法 * access("permitAll") 等价于 permitAll() */
  28. http.authorizeRequests().antMatchers("/").permitAll(); // "/":应用首页所以用户都可以访问
  29. http.authorizeRequests()
  30. .antMatchers("/user/addUser").hasRole("AAA") // 首斜杠"/"表示应用上下文,/user/addUser 请求允许 AAA 角色访问
  31. .antMatchers("/user/deleteUser/**").hasAnyRole("AAA", "BBB") //"/user/deleteUser/**"允许 "AAA", "BBB" 角色访问,/**匹配任意
  32. .antMatchers("/user/updateUser").hasAnyRole("AAA", "BBB", "CCC")//除了这种链式编程,也可以分开写
  33. .antMatchers("/user/findAllUsers").access("permitAll");
  34. http.authorizeRequests().anyRequest().authenticated();
  35. /**
  36. * formLogin:指定支持基于表单的身份验证
  37. * 当用户没有登录、没有权限时就会自动跳转到登录页面(默认 /login)
  38. * 当登录失败时,默认跳转到 /error
  39. * 登录成功时会放行
  40. */
  41. http.formLogin();
  42. }
  43. }

MyPasswordEncoder

  1. package com.example.config;
  2. import org.springframework.security.crypto.password.PasswordEncoder;
  3. //密码编码,Spring Security 高版本必须进行密码编码,否则报错
  4. public class MyPasswordEncoder implements PasswordEncoder {
  5. @Override
  6. public String encode(CharSequence charSequence) {
  7. return charSequence.toString();
  8. }
  9. @Override
  10. public boolean matches(CharSequence charSequence, String s) {
  11. return s.equals(charSequence.toString());
  12. }
  13. }

亲测效果是

以用户名 zs 登录(其角色权限为AAA),可以进入系统,浏览器输入地址可以访问, localhost:8080,localhost:8080/user/addUser,localhost:8080/user/deleteUser,localhost:8080/user/updateUser,localhost:8080/user/findAllUsers

以用户名 ls 登录(其角色权限为BBB),可以进入系统,浏览器输入地址可以访问, localhost:8080,localhost:8080/user/deleteUser,localhost:8080/user/updateUser,localhost:8080/user/findAllUsers

以用户名 ww 登录(其角色权限为CCC),可以进入系统,浏览器输入地址可以访问, localhost:8080,localhost:8080/user/deleteUser,localhost:8080/user/updateUser,localhost:8080/user/findAllUsers

以用户名 zl 登录(其角色权限为CCC),可以进入系统,浏览器输入地址可以访问, localhost:8080,localhost:8080/user/updateUser,localhost:8080/user/findAllUsers

以用户名 admin 登录,不可以进入系统,因为系统中还没有该用户。

发表评论

表情:
评论列表 (有 0 条评论,64人围观)

还没有评论,来说两句吧...

相关阅读

    相关 springboot整合spring-security

    在web开发中,安全性问题比较重要,一般会使用过滤器或者拦截器的方式对权限等进行验证过滤。此博客根据b站up主,使用demo示例进行展示spring-security的一些功能