经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » Spring Boot » 查看文章
SpringBoot SpringSecurity 介绍(基于内存的验证)
来源:cnblogs  作者:VipSoft  时间:2023/4/28 9:36:31  对本文有异议

SpringBoot 集成 SpringSecurity + MySQL + JWT 附源码,废话不多直接盘
SpringBoot已经为用户采用默认配置,只需要引入pom依赖就能快速启动Spring Security。
目的:验证请求用户的身份,提供安全访问
优势:基于Spring,配置方便,减少大量代码

image

内置访问控制方法

  • permitAll() 表示所匹配的 URL 任何人都允许访问。
  • authenticated() 表示所匹配的 URL 都需要被认证才能访问。
  • anonymous() 表示可以匿名访问匹配的 URL 。和 permitAll() 效果类似,只是设置为 anonymous() 的 url 会执行 filter 链中
  • denyAll() 表示所匹配的 URL 都不允许被访问。
  • rememberMe() 被“remember me”的用户允许访问 这个有点类似于很多网站的十天内免登录,登陆一次即可记住你,然后未来一段时间不用登录。
  • fullyAuthenticated() 如果用户不是被 remember me 的,才可以访问。也就是必须一步一步按部就班的登录才行。

角色权限判断

  • hasAuthority(String) 判断用户是否具有特定的权限,用户的权限是在自定义登录逻辑
  • hasAnyAuthority(String ...) 如果用户具备给定权限中某一个,就允许访问
  • hasRole(String) 如果用户具备给定角色就允许访问。否则出现 403
  • hasAnyRole(String ...) 如果用户具备给定角色的任意一个,就允许被访问
  • hasIpAddress(String) 如果请求是指定的 IP 就运行访问。可以通过 request.getRemoteAddr() 获取 ip 地址

引用 Spring Security

Pom 文件中添加

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-security</artifactId>
  4. </dependency>
点击查看POM代码
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <parent>
  6. <artifactId>vipsoft-parent</artifactId>
  7. <groupId>com.vipsoft.boot</groupId>
  8. <version>1.0-SNAPSHOT</version>
  9. </parent>
  10. <modelVersion>4.0.0</modelVersion>
  11. <artifactId>vipsoft-security</artifactId>
  12. <version>1.0-SNAPSHOT</version>
  13. <dependencies>
  14. <dependency>
  15. <groupId>cn.hutool</groupId>
  16. <artifactId>hutool-all</artifactId>
  17. <version>5.3.7</version>
  18. </dependency>
  19. <dependency>
  20. <groupId>org.springframework.boot</groupId>
  21. <artifactId>spring-boot-starter-security</artifactId>
  22. </dependency>
  23. <dependency>
  24. <groupId>org.springframework.boot</groupId>
  25. <artifactId>spring-boot-starter-web</artifactId>
  26. </dependency>
  27. <dependency>
  28. <groupId>org.springframework.boot</groupId>
  29. <artifactId>spring-boot-starter-test</artifactId>
  30. <scope>test</scope>
  31. <exclusions>
  32. <exclusion>
  33. <groupId>org.junit.vintage</groupId>
  34. <artifactId>junit-vintage-engine</artifactId>
  35. </exclusion>
  36. </exclusions>
  37. </dependency>
  38. </dependencies>
  39. <build>
  40. <plugins>
  41. <plugin>
  42. <groupId>org.springframework.boot</groupId>
  43. <artifactId>spring-boot-maven-plugin</artifactId>
  44. </plugin>
  45. </plugins>
  46. </build>
  47. </project>

运行后会自动生成 password 默认用户名为: user
image

默认配置每次都启动项目都会重新生成密码,同时用户名和拦截请求也不能自定义,在实际应用中往往需要自定义配置,因此接下来对Spring Security进行自定义配置。

配置 Spring Security (入门)

在内存中(简化环节,了解逻辑)配置两个用户角色(admin和user),设置不同密码;
同时设置角色访问权限,其中admin可以访问所有路径(即/*),user只能访问/user下的所有路径。

自定义配置类,实现WebSecurityConfigurerAdapter接口,WebSecurityConfigurerAdapter接口中有两个用到的 configure()方法,其中一个配置用户身份,另一个配置用户权限:

配置用户身份的configure()方法:

SecurityConfig

  1. package com.vipsoft.web.config;
  2. import org.springframework.context.annotation.Configuration;
  3. import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
  4. import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
  5. import org.springframework.security.config.annotation.web.builders.HttpSecurity;
  6. import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
  7. import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
  8. import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
  9. import org.springframework.security.crypto.password.PasswordEncoder;
  10. @Configuration
  11. @EnableWebSecurity
  12. @EnableGlobalMethodSecurity(prePostEnabled = true)
  13. public class SecurityConfig extends WebSecurityConfigurerAdapter {
  14. /**
  15. * 配置用户身份的configure()方法
  16. *
  17. * @param auth
  18. * @throws Exception
  19. */
  20. @Override
  21. protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  22. PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
  23. //简化操作,将用户名和密码存在内存中,后期会存放在数据库、Redis中
  24. auth.inMemoryAuthentication()
  25. .passwordEncoder(passwordEncoder)
  26. .withUser("admin")
  27. .password(passwordEncoder.encode("888"))
  28. .roles("ADMIN")
  29. .and()
  30. .withUser("user")
  31. .password(passwordEncoder.encode("666"))
  32. .roles("USER");
  33. }
  34. /**
  35. * 配置用户权限的configure()方法
  36. * @param http
  37. * @throws Exception
  38. */
  39. @Override
  40. protected void configure(HttpSecurity http) throws Exception {
  41. http.authorizeRequests()
  42. //配置拦截的路径、配置哪类角色可以访问该路径
  43. .antMatchers("/user").hasAnyRole("USER")
  44. .antMatchers("/*").hasAnyRole("ADMIN")
  45. //配置登录界面,可以添加自定义界面, 没添加则用系统默认的界面
  46. .and().formLogin();
  47. }
  48. }

添加接口测试用

  1. package com.vipsoft.web.controller;
  2. import org.springframework.security.access.prepost.PreAuthorize;
  3. import org.springframework.web.bind.annotation.GetMapping;
  4. import org.springframework.web.bind.annotation.RestController;
  5. @RestController
  6. public class DefaultController {
  7. @GetMapping("/")
  8. @PreAuthorize("hasRole('ADMIN')")
  9. public String demo() {
  10. return "Welcome";
  11. }
  12. @GetMapping("/user/list")
  13. @PreAuthorize("hasAnyRole('ADMIN','USER')")
  14. public String getUserList() {
  15. return "User List";
  16. }
  17. @GetMapping("/article/list")
  18. @PreAuthorize("hasRole('ADMIN')")
  19. public String getArticleList() {
  20. return "Article List";
  21. }
  22. }

image

原文链接:https://www.cnblogs.com/vipsoft/p/17348599.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号