当前位置: 首页 > news >正文

Spring Security面试题

Spring Security面试题

基础概念

Q1: Spring Security的核心功能有哪些?

public class SecurityBasicDemo {// 1. 基本配置public class SecurityConfigExample {public void configDemo() {@Configuration@EnableWebSecuritypublic class SecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/public/**").permitAll().antMatchers("/admin/**").hasRole("ADMIN").anyRequest().authenticated().and().formLogin().loginPage("/login").defaultSuccessUrl("/dashboard").and().logout().logoutUrl("/logout").logoutSuccessUrl("/login");}@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.inMemoryAuthentication().withUser("user").password(passwordEncoder().encode("password")).roles("USER");}@Beanpublic PasswordEncoder passwordEncoder() {return new BCryptPasswordEncoder();}}}}// 2. 认证流程public class AuthenticationExample {public void authDemo() {// 自定义认证提供者@Componentpublic class CustomAuthenticationProvider implements AuthenticationProvider {@Overridepublic Authentication authenticate(Authentication auth) throws AuthenticationException {String username = auth.getName();String password = auth.getCredentials().toString();// 验证用户if (validateUser(username, password)) {List<GrantedAuthority> authorities = Arrays.asList(new SimpleGrantedAuthority("ROLE_USER"));return new UsernamePasswordAuthenticationToken(username, password, authorities);}throw new BadCredentialsException("Invalid credentials");}@Overridepublic boolean supports(Class<?> authentication) {return authentication.equals(UsernamePasswordAuthenticationToken.class);}}}}
}

Q2: Spring Security的认证和授权机制是怎样的?

public class AuthenticationAuthorizationDemo {// 1. 认证机制public class AuthenticationMechanismExample {public void authMechanismDemo() {// 用户详情服务@Servicepublic class CustomUserDetailsService implements UserDetailsService {@Overridepublic UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {User user = userRepository.findByUsername(username);if (user == null) {throw new UsernameNotFoundException(username);}return new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(),getAuthorities(user.getRoles()));}private Collection<? extends GrantedAuthority> getAuthorities(Collection<Role> roles) {return roles.stream().map(role -> new SimpleGrantedAuthority(role.getName())).collect(Collectors.toList());}}}}// 2. 授权机制public class AuthorizationMechanismExample {public void authorizationDemo() {// 方法级安全@Configuration@EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled = true,jsr250Enabled = true)public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {@Overrideprotected MethodSecurityExpressionHandler createExpressionHandler() {DefaultMethodSecurityExpressionHandler expressionHandler = new DefaultMethodSecurityExpressionHandler();expressionHandler.setPermissionEvaluator(new CustomPermissionEvaluator());return expressionHandler;}}// 使用注解@Servicepublic class UserService {@PreAuthorize("hasRole('ADMIN')")public void createUser(User user) {// 创建用户}@PostAuthorize("returnObject.username == authentication.name")public User getUser(Long id) {// 获取用户return userRepository.findById(id).orElse(null);}}}}
}

高级特性

Q3: Spring Security的OAuth2.0实现是怎样的?

public class OAuth2Demo {// 1. 授权服务器public class AuthorizationServerExample {public void authServerDemo() {@Configuration@EnableAuthorizationServerpublic class AuthServerConfig extends AuthorizationServerConfigurerAdapter {@Overridepublic void configure(ClientDetailsServiceConfigurer clients) throws Exception {clients.inMemory().withClient("client").secret(passwordEncoder.encode("secret")).authorizedGrantTypes("authorization_code","password","client_credentials","refresh_token").scopes("read", "write").accessTokenValiditySeconds(3600).refreshTokenValiditySeconds(86400);}@Overridepublic void configure(AuthorizationServerSecurityConfigurer security) {security.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()").allowFormAuthenticationForClients();}}}}// 2. 资源服务器public class ResourceServerExample {public void resourceServerDemo() {@Configuration@EnableResourceServerpublic class ResourceServerConfig extends ResourceServerConfigurerAdapter {@Overridepublic void configure(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/api/**").authenticated().anyRequest().permitAll().and().cors().and().csrf().disable();}@Overridepublic void configure(ResourceServerSecurityConfigurer resources) {resources.resourceId("resource_id");}}}}
}

Q4: Spring Security的会话管理是怎样的?

public class SessionManagementDemo {// 1. 会话配置public class SessionConfigExample {public void sessionConfigDemo() {@Configurationpublic class SecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED).maximumSessions(1).maxSessionsPreventsLogin(true).expiredUrl("/login?expired").and().sessionFixation().migrateSession().and().csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());}}}}// 2. 会话事件监听public class SessionEventExample {public void sessionEventDemo() {@Componentpublic class SecurityEventListener implements ApplicationListener<AbstractAuthenticationEvent> {@Overridepublic void onApplicationEvent(AbstractAuthenticationEvent event) {if (event instanceof AuthenticationSuccessEvent) {// 认证成功事件处理logAuthenticationSuccess(event);} else if (event instanceof AuthenticationFailureEvent) {// 认证失败事件处理logAuthenticationFailure(event);} else if (event instanceof InteractiveAuthenticationSuccessEvent) {// 交互式认证成功事件处理logInteractiveAuthenticationSuccess(event);}}}}}
}

Q5: Spring Security的安全防护有哪些?

public class SecurityProtectionDemo {// 1. CSRF防护public class CSRFProtectionExample {public void csrfDemo() {@Configurationpublic class SecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()).ignoringAntMatchers("/api/webhook/**");}}// CSRF Token处理@Componentpublic class CSRFTokenHandler extends OncePerRequestFilter {@Overrideprotected void doFilterInternal(HttpServletRequest request,HttpServletResponse response,FilterChain filterChain) throws ServletException, IOException {CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class.getName());if (csrf != null) {response.setHeader("X-CSRF-TOKEN", csrf.getToken());}filterChain.doFilter(request, response);}}}}// 2. XSS防护public class XSSProtectionExample {public void xssDemo() {// XSS过滤器@Componentpublic class XSSFilter implements Filter {@Overridepublic void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws IOException, ServletException {XSSRequestWrapper wrappedRequest = new XSSRequestWrapper((HttpServletRequest) request);chain.doFilter(wrappedRequest, response);}}// 请求包装器public class XSSRequestWrapper extends HttpServletRequestWrapper {public XSSRequestWrapper(HttpServletRequest request) {super(request);}@Overridepublic String[] getParameterValues(String parameter) {String[] values = super.getParameterValues(parameter);if (values == null) {return null;}int count = values.length;String[] encodedValues = new String[count];for (int i = 0; i < count; i++) {encodedValues[i] = cleanXSS(values[i]);}return encodedValues;}private String cleanXSS(String value) {// XSS清理逻辑return value.replaceAll("<", "&lt;").replaceAll(">", "&gt;");}}}}// 3. SQL注入防护public class SQLInjectionProtectionExample {public void sqlInjectionDemo() {// 参数绑定@Repositorypublic class UserRepository {@Autowiredprivate JdbcTemplate jdbcTemplate;public User findByUsername(String username) {return jdbcTemplate.queryForObject("SELECT * FROM users WHERE username = ?",new Object[]{username},(rs, rowNum) ->new User(rs.getLong("id"),rs.getString("username"),rs.getString("password")));}}// 输入验证@Componentpublic class InputValidator {public boolean isValidInput(String input) {// 输入验证逻辑return input != null && input.matches("[a-zA-Z0-9_]+");}}}}
}

面试关键点

  1. 理解Spring Security的核心功能
  2. 掌握认证和授权机制
  3. 熟悉OAuth2.0的实现
  4. 了解会话管理机制
  5. 理解安全防护措施
  6. 掌握配置和扩展方法
  7. 注意性能和安全平衡
  8. 关注最佳实践

相关文章:

Spring Security面试题

Spring Security面试题 基础概念 Q1: Spring Security的核心功能有哪些&#xff1f; public class SecurityBasicDemo {// 1. 基本配置public class SecurityConfigExample {public void configDemo() {ConfigurationEnableWebSecuritypublic class SecurityConfig extends …...

从零开始构建基于DeepSeek的智能客服系统

在当今的数字化时代,智能客服系统已经成为企业与客户沟通的重要桥梁。它不仅能够提升客户体验,还能大幅降低企业的运营成本。本文将带领你从零开始,使用PHP和DeepSeek技术构建一个功能强大的智能客服系统。我们将通过具体的案例和代码示例,深入探讨如何实现这一目标。 1. …...

Linux故障排查和性能优化面试题及参考答案

目录 如何查看 Linux 系统中的 CPU、内存、磁盘等资源使用情况? 什么是 Linux 中的负载(Load Average)?如何解读它? 如何通过 top 和 htop 命令监控系统性能? 如何使用 mpstat 命令来查看 CPU 的利用情况? 如何分析系统 CPU 瓶颈? 如何分析 CPU 瓶颈?如何优化 CP…...

【无人集群系列---大疆无人集群技术进展、技术路线与未来发展方向】

大疆无人集群技术进展、技术路线与未来发展方向 一、技术进展1. 核心技术创新&#xff08;1&#xff09;集群协同控制技术&#xff08;2&#xff09;感知与能源系统升级 2. 行业应用落地&#xff08;1&#xff09;智慧城市与安防&#xff08;2&#xff09;应急救援&#xff08;…...

【亲测有效】百度Ueditor富文本编辑器添加插入视频、视频不显示、和插入视频后二次编辑视频标签不显示,显示成img标签,二次保存视频被替换问题,解决方案

【亲测有效】项目使用百度Ueditor富文本编辑器上传视频相关操作问题 1.百度Ueditor富文本编辑器添加插入视频、视频不显示 2.百度Ueditor富文本编辑器插入视频后二次编辑视频标签不显示&#xff0c;在编辑器内显示成img标签&#xff0c;二次保存视频被替换问题 问题1&#xff1…...

ubuntu windows双系统踩坑

我有个台式机&#xff0c;先安装的ubuntu&#xff0c;本来想专门用来做开发&#xff0c;后面儿子长大了&#xff0c;给他看了一下星际争霸、魔兽争霸&#xff0c;立马就迷上了。还有一台windows的笔记本&#xff0c;想着可以和他联局域网一起玩&#xff0c;在ubuntu上用wine跑魔…...

嵌入式八股文(五)硬件电路篇

一、名词概念 1. 整流和逆变 &#xff08;1&#xff09;整流&#xff1a;整流是将交流电&#xff08;AC&#xff09;转变为直流电&#xff08;DC&#xff09;。常见的整流电路包括单向整流&#xff08;二极管&#xff09;、桥式整流等。 半波整流&#xff1a;只使用交流电的正…...

flink使用demo

1、添加不同数据源 package com.baidu.keyue.deepsight.memory.test;import com.baidu.keyue.deepsight.memory.WordCount; import com.baidu.keyue.deepsight.memory.WordCountData; import org.apache.flink.api.common.RuntimeExecutionMode; import org.apache.flink.api.…...

OpenCV(8):图像直方图

在图像处理中&#xff0c;直方图是一种非常重要的工具&#xff0c;它可以帮助我们了解图像的像素分布情况。通过分析图像的直方图&#xff0c;我们可以进行图像增强、对比度调整、图像分割等操作。 1 什么是图像直方图&#xff1f; 图像直方图是图像像素强度分布的图形表示&am…...

力扣LeetCode:1656 设计有序流

题目&#xff1a; 有 n 个 (id, value) 对&#xff0c;其中 id 是 1 到 n 之间的一个整数&#xff0c;value 是一个字符串。不存在 id 相同的两个 (id, value) 对。 设计一个流&#xff0c;以 任意 顺序获取 n 个 (id, value) 对&#xff0c;并在多次调用时 按 id 递增的顺序…...

NGINX配置TCP负载均衡

前言 之前本人做项目需要用到nginx的tcp负载均衡&#xff0c;这里是当时配置做的笔记&#xff1b;欢迎收藏 关注&#xff0c;本人将会持续更新 文章目录 配置Nginx的负载均衡 配置Nginx的负载均衡 nginx编译安装需要先安装pcre、openssl、zlib等库&#xff0c;也可以直接编译…...

vm和centos

安装 VMware Workstation Pro 1. 下载 VMware Workstation Pro 访问 VMware 官方网站&#xff08;https://www.vmware.com/cn/products/workstation-pro/workstation-pro-evaluation.html &#xff09;&#xff0c;在该页面中点击 “立即下载” 按钮&#xff0c;选择适合你操作…...

c#丰田PLC ToyoPuc TCP协议快速读写 to c# Toyota PLC ToyoPuc读写

源代码下载 <------下载地址 历史背景与发展 TOYOPUC协议源于丰田工机&#xff08;TOYODA&#xff09;的自动化技术积累。丰田工机成立于1941年&#xff0c;最初是丰田汽车的机床部门&#xff0c;后独立为专注于工业机械与控制系统的公司。2006年与光洋精工&#xff08;Ko…...

量子计算的数学基础:复数、矩阵和线性代数

量子计算是基于量子力学原理的一种新型计算模式,它与经典计算机在信息处理的方式上有着根本性的区别。在量子计算中,信息的最小单位是量子比特(qubit),而不是传统计算中的比特。量子比特的状态是通过量子力学中的数学工具来描述的,因此,理解量子计算的数学基础对于深入学…...

【JavaScript】《JavaScript高级程序设计 (第4版) 》笔记-Chapter22-处理 XML

二十二、处理 XML 处理 XML XML 曾一度是在互联网上存储和传输结构化数据的标准。XML 的发展反映了 Web 的发展&#xff0c;因为DOM 标准不仅是为了在浏览器中使用&#xff0c;而且还为了在桌面和服务器应用程序中处理 XML 数据结构。在没有 DOM 标准的时候&#xff0c;很多开发…...

一个不错的API测试框架——Karate

Karate 是一款开源的 API 测试工具,基于 BDD(行为驱动开发)框架 Cucumber 构建,但无需编写 Java 或 JavaScript 代码即可直接编写测试用例。它结合了 API 测试、模拟(Mocking)和性能测试功能,支持 HTTP、GraphQL 和 WebSocket 等协议,语法简洁易读。 Karate详细介绍 K…...

文字语音相互转换

目录 1.介绍 2.思路 3.安装python包 3.程序&#xff1a; 4.运行结果 1.介绍 当我们使用一些本地部署的语言模型的时候&#xff0c;往往只能进行文字对话&#xff0c;这一片博客教大家如何实现语音转文字和文字转语音&#xff0c;之后接入ollama的模型就能进行语音对话了。…...

DeepSeek-R1:通过强化学习激发大语言模型的推理能力

注&#xff1a;此文章内容均节选自充电了么创始人&#xff0c;CEO兼CTO陈敬雷老师的新书《自然语言处理原理与实战》&#xff08;人工智能科学与技术丛书&#xff09;【陈敬雷编著】【清华大学出版社】 文章目录 DeepSeek大模型技术系列三DeepSeek大模型技术系列三》DeepSeek-…...

MATLAB中fft函数用法

目录 语法 说明 示例 含噪信号 高斯脉冲 余弦波 正弦波的相位 FFT 的插值 fft函数的功能是对数据进行快速傅里叶变换。 语法 Y fft(X) Y fft(X,n) Y fft(X,n,dim) 说明 ​Y fft(X) 用快速傅里叶变换 (FFT) 算法计算 X 的离散傅里叶变换 (DFT)。 如果 X 是向量&…...

【SpringBoot】【JWT】使用JWT的claims()方法存入Integer类型数据自动转为Double类型

生成令牌时使用Map存入Integer类型数据&#xff0c;将map使用claims方法放入JWT令牌后&#xff0c;取出时变成Double类型&#xff0c;强转报错&#xff1a; 解决&#xff1a; 将Integer转为String后存入JWT令牌&#xff0c;不会被自动转为其他类型&#xff0c;取出后转为Integ…...

wordpress后台更新后 前端没变化的解决方法

使用siteground主机的wordpress网站&#xff0c;会出现更新了网站内容和修改了php模板文件、js文件、css文件、图片文件后&#xff0c;网站没有变化的情况。 不熟悉siteground主机的新手&#xff0c;遇到这个问题&#xff0c;就很抓狂&#xff0c;明明是哪都没操作错误&#x…...

OpenLayers 可视化之热力图

注&#xff1a;当前使用的是 ol 5.3.0 版本&#xff0c;天地图使用的key请到天地图官网申请&#xff0c;并替换为自己的key 热力图&#xff08;Heatmap&#xff09;又叫热点图&#xff0c;是一种通过特殊高亮显示事物密度分布、变化趋势的数据可视化技术。采用颜色的深浅来显示…...

【kafka】Golang实现分布式Masscan任务调度系统

要求&#xff1a; 输出两个程序&#xff0c;一个命令行程序&#xff08;命令行参数用flag&#xff09;和一个服务端程序。 命令行程序支持通过命令行参数配置下发IP或IP段、端口、扫描带宽&#xff0c;然后将消息推送到kafka里面。 服务端程序&#xff1a; 从kafka消费者接收…...

DeepSeek 赋能智慧能源:微电网优化调度的智能革新路径

目录 一、智慧能源微电网优化调度概述1.1 智慧能源微电网概念1.2 优化调度的重要性1.3 目前面临的挑战 二、DeepSeek 技术探秘2.1 DeepSeek 技术原理2.2 DeepSeek 独特优势2.3 DeepSeek 在 AI 领域地位 三、DeepSeek 在微电网优化调度中的应用剖析3.1 数据处理与分析3.2 预测与…...

Redis相关知识总结(缓存雪崩,缓存穿透,缓存击穿,Redis实现分布式锁,如何保持数据库和缓存一致)

文章目录 1.什么是Redis&#xff1f;2.为什么要使用redis作为mysql的缓存&#xff1f;3.什么是缓存雪崩、缓存穿透、缓存击穿&#xff1f;3.1缓存雪崩3.1.1 大量缓存同时过期3.1.2 Redis宕机 3.2 缓存击穿3.3 缓存穿透3.4 总结 4. 数据库和缓存如何保持一致性5. Redis实现分布式…...

【Redis技术进阶之路】「原理分析系列开篇」分析客户端和服务端网络诵信交互实现(服务端执行命令请求的过程 - 初始化服务器)

服务端执行命令请求的过程 【专栏简介】【技术大纲】【专栏目标】【目标人群】1. Redis爱好者与社区成员2. 后端开发和系统架构师3. 计算机专业的本科生及研究生 初始化服务器1. 初始化服务器状态结构初始化RedisServer变量 2. 加载相关系统配置和用户配置参数定制化配置参数案…...

Ubuntu系统复制(U盘-电脑硬盘)

所需环境 电脑自带硬盘&#xff1a;1块 (1T) U盘1&#xff1a;Ubuntu系统引导盘&#xff08;用于“U盘2”复制到“电脑自带硬盘”&#xff09; U盘2&#xff1a;Ubuntu系统盘&#xff08;1T&#xff0c;用于被复制&#xff09; &#xff01;&#xff01;&#xff01;建议“电脑…...

沙箱虚拟化技术虚拟机容器之间的关系详解

问题 沙箱、虚拟化、容器三者分开一一介绍的话我知道他们各自都是什么东西&#xff0c;但是如果把三者放在一起&#xff0c;它们之间到底什么关系&#xff1f;又有什么联系呢&#xff1f;我不是很明白&#xff01;&#xff01;&#xff01; 就比如说&#xff1a; 沙箱&#…...

jdbc查询mysql数据库时,出现id顺序错误的情况

我在repository中的查询语句如下所示&#xff0c;即传入一个List<intager>的数据&#xff0c;返回这些id的问题列表。但是由于数据库查询时ID列表的顺序与预期不一致&#xff0c;会导致返回的id是从小到大排列的&#xff0c;但我不希望这样。 Query("SELECT NEW com…...

OPENCV图形计算面积、弧长API讲解(1)

一.OPENCV图形面积、弧长计算的API介绍 之前我们已经把图形轮廓的检测、画框等功能讲解了一遍。那今天我们主要结合轮廓检测的API去计算图形的面积&#xff0c;这些面积可以是矩形、圆形等等。图形面积计算和弧长计算常用于车辆识别、桥梁识别等重要功能&#xff0c;常用的API…...