springboot整合spring-security

桃扇骨 2024-03-29 15:50 151阅读 0赞

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

目 录

1、创建项目

2、编写controller

3、添加spring-security依赖

4、编写spring-security配置类

5、添加thymeleaf-extras-springsecurity5 依赖

6、页面访问测试


先来最终的目录结构

843a3d8863fb45ffb27696dbe77dd275.png

pom文件:springboot版本为 2.0.9.RELEASE

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <parent>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-parent</artifactId>
  8. <version>2.0.9.RELEASE</version>
  9. <relativePath/> <!-- lookup parent from repository -->
  10. </parent>
  11. <groupId>com.ljy</groupId>
  12. <artifactId>test-spring-security</artifactId>
  13. <version>0.0.1-SNAPSHOT</version>
  14. <name>test-spring-security</name>
  15. <description>Demo project for Spring Boot</description>
  16. <properties>
  17. <java.version>1.8</java.version>
  18. </properties>
  19. <dependencies>
  20. <!-- https://mvnrepository.com/artifact/org.thymeleaf.extras/thymeleaf-extras-springsecurity4 -->
  21. <dependency>
  22. <groupId>org.thymeleaf.extras</groupId>
  23. <artifactId>thymeleaf-extras-springsecurity5</artifactId>
  24. <version>3.0.4.RELEASE</version>
  25. </dependency>
  26. <dependency>
  27. <groupId>org.springframework.boot</groupId>
  28. <artifactId>spring-boot-starter-security</artifactId>
  29. </dependency>
  30. <dependency>
  31. <groupId>org.springframework.boot</groupId>
  32. <artifactId>spring-boot-starter-thymeleaf</artifactId>
  33. </dependency>
  34. <dependency>
  35. <groupId>org.springframework.boot</groupId>
  36. <artifactId>spring-boot-starter-web</artifactId>
  37. </dependency>
  38. <dependency>
  39. <groupId>org.springframework.boot</groupId>
  40. <artifactId>spring-boot-starter-test</artifactId>
  41. <scope>test</scope>
  42. <exclusions>
  43. <exclusion>
  44. <groupId>org.junit.vintage</groupId>
  45. <artifactId>junit-vintage-engine</artifactId>
  46. </exclusion>
  47. </exclusions>
  48. </dependency>
  49. </dependencies>
  50. <build>
  51. <plugins>
  52. <plugin>
  53. <groupId>org.apache.maven.plugins</groupId>
  54. <artifactId>maven-compiler-plugin</artifactId>
  55. <version>3.8.1</version>
  56. <configuration>
  57. <source>1.8</source>
  58. <target>1.8</target>
  59. <encoding>UTF-8</encoding>
  60. </configuration>
  61. </plugin>
  62. <plugin>
  63. <groupId>org.springframework.boot</groupId>
  64. <artifactId>spring-boot-maven-plugin</artifactId>
  65. </plugin>
  66. </plugins>
  67. </build>
  68. </project>

1、创建项目

创建项目,并添加web和Thymeleaf依赖

下载静态资源,并进行导入,下载地址为:静态资源地址

2、编写controller

  1. package com.ljy.testspringsecurity.controller;
  2. import org.springframework.stereotype.Controller;
  3. import org.springframework.web.bind.annotation.PathVariable;
  4. import org.springframework.web.bind.annotation.RequestMapping;
  5. /**
  6. * @Author 不要有情绪的 ljy
  7. * @Date 2023/1/13 15:23
  8. * @Description:
  9. */
  10. @Controller
  11. public class RouterController {
  12. @RequestMapping({"/", "index"})
  13. public String index() {
  14. return "index";
  15. }
  16. @RequestMapping({"/toLogin"})
  17. public String toLogin() {
  18. return "views/login";
  19. }
  20. @RequestMapping("/level1/{id}")
  21. public String level1(@PathVariable("id") int id) {
  22. return "views/level1/" + id;
  23. }
  24. @RequestMapping("/level2/{id}")
  25. public String level2(@PathVariable("id") int id) {
  26. return "views/level2/" + id;
  27. }
  28. @RequestMapping("/level3/{id}")
  29. public String level3(@PathVariable("id") int id) {
  30. return "views/level3/" + id;
  31. }
  32. }

3、添加spring-security依赖

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-security</artifactId>
  4. </dependency>

4、编写spring-security配置类

  1. package com.ljy.testspringsecurity.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. import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
  7. /**
  8. * @Author 不要有情绪的 ljy
  9. * @Date 2023/1/13 15:39
  10. * @Description:
  11. */
  12. @EnableWebSecurity
  13. public class SecurityConfig extends WebSecurityConfigurerAdapter {
  14. //授权认证
  15. @Override
  16. protected void configure(HttpSecurity http) throws Exception {
  17. //定制请求的授权规则 其目的是:告诉有哪些权限的人才可以访问页面
  18. http.authorizeRequests()
  19. .antMatchers("/").permitAll() //首页所有人可以访问
  20. .antMatchers("/level1/**").hasRole("vip1")
  21. .antMatchers("/level2/**").hasRole("vip2")
  22. .antMatchers("/level3/**").hasRole("vip3");
  23. //开启自动配置的登录功能
  24. //没有权限默认会到登录页面
  25. //定制登陆页面("/toLogin")
  26. //登录认证("/login")
  27. http.formLogin()
  28. .usernameParameter("username")
  29. .passwordParameter("password")
  30. .loginPage("/toLogin")
  31. .loginProcessingUrl("/login");
  32. /*防止网站攻击*/ //也是解决注销报错的方法
  33. http.csrf().disable();//关闭csrf
  34. // 开启自动配置的注销的功能
  35. /*注销成功后跳到首页*/
  36. http.logout().logoutSuccessUrl("/");
  37. //记住我功能,自定义接受前端数据
  38. http.rememberMe().rememberMeParameter("remember");
  39. }
  40. //定义认证规则 其目的是:告诉哪些的用户拥有哪些权限,即给用户绑定用户角色
  41. @Override
  42. protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  43. //在内存中定义,也可以在jdbc中去拿
  44. //Spring security 5.0中新增了多种加密方式,也改变了密码的格式
  45. //要想我们的项目还能够正常登录,需要修改以下configure中的代码,我们要将前端传过来的密码进行某种方法的加密
  46. //spring security 官方推荐的是使用bcrypt加密方式。
  47. auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
  48. .withUser("kuangshen").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2", "vip3")
  49. .and()
  50. .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1", "vip2", "vip3")
  51. .and()
  52. .withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1", "vip2");
  53. }
  54. }

对以上代码进行简单描述,configure(HttpSecurity http)方法是授权认证,其目的是告诉有哪些权限的人才可以访问哪个页面,configure(AuthenticationManagerBuilder auth)方法是定义认证规则,其目的是定义哪些用户有权限,即给每个用户绑定权限。

5、添加thymeleaf-extras-springsecurity5 依赖

为了在前端实现,动态展示页面的效果,即不同权限看到的页面内容不一样,引入thymeleaf-extras-springsecurity5依赖,即使用 sec:authorize=“isAuthenticated()”;是否认证登录!来显示不同的页面。(前端页面不在描述,可以根据b站视频查看:视频地址)

6、页面访问测试

http://localhost:8080/

项目已上传到github上,地址:源码地址

发表评论

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

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

相关阅读