当前位置: 首页 > 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…...

基于算法竞赛的c++编程(28)结构体的进阶应用

结构体的嵌套与复杂数据组织 在C中&#xff0c;结构体可以嵌套使用&#xff0c;形成更复杂的数据结构。例如&#xff0c;可以通过嵌套结构体描述多层级数据关系&#xff1a; struct Address {string city;string street;int zipCode; };struct Employee {string name;int id;…...

地震勘探——干扰波识别、井中地震时距曲线特点

目录 干扰波识别反射波地震勘探的干扰波 井中地震时距曲线特点 干扰波识别 有效波&#xff1a;可以用来解决所提出的地质任务的波&#xff1b;干扰波&#xff1a;所有妨碍辨认、追踪有效波的其他波。 地震勘探中&#xff0c;有效波和干扰波是相对的。例如&#xff0c;在反射波…...

超短脉冲激光自聚焦效应

前言与目录 强激光引起自聚焦效应机理 超短脉冲激光在脆性材料内部加工时引起的自聚焦效应&#xff0c;这是一种非线性光学现象&#xff0c;主要涉及光学克尔效应和材料的非线性光学特性。 自聚焦效应可以产生局部的强光场&#xff0c;对材料产生非线性响应&#xff0c;可能…...

微软PowerBI考试 PL300-选择 Power BI 模型框架【附练习数据】

微软PowerBI考试 PL300-选择 Power BI 模型框架 20 多年来&#xff0c;Microsoft 持续对企业商业智能 (BI) 进行大量投资。 Azure Analysis Services (AAS) 和 SQL Server Analysis Services (SSAS) 基于无数企业使用的成熟的 BI 数据建模技术。 同样的技术也是 Power BI 数据…...

盘古信息PCB行业解决方案:以全域场景重构,激活智造新未来

一、破局&#xff1a;PCB行业的时代之问 在数字经济蓬勃发展的浪潮中&#xff0c;PCB&#xff08;印制电路板&#xff09;作为 “电子产品之母”&#xff0c;其重要性愈发凸显。随着 5G、人工智能等新兴技术的加速渗透&#xff0c;PCB行业面临着前所未有的挑战与机遇。产品迭代…...

关于iview组件中使用 table , 绑定序号分页后序号从1开始的解决方案

问题描述&#xff1a;iview使用table 中type: "index",分页之后 &#xff0c;索引还是从1开始&#xff0c;试过绑定后台返回数据的id, 这种方法可行&#xff0c;就是后台返回数据的每个页面id都不完全是按照从1开始的升序&#xff0c;因此百度了下&#xff0c;找到了…...

鸿蒙中用HarmonyOS SDK应用服务 HarmonyOS5开发一个医院挂号小程序

一、开发准备 ​​环境搭建​​&#xff1a; 安装DevEco Studio 3.0或更高版本配置HarmonyOS SDK申请开发者账号 ​​项目创建​​&#xff1a; File > New > Create Project > Application (选择"Empty Ability") 二、核心功能实现 1. 医院科室展示 /…...

cf2117E

原题链接&#xff1a;https://codeforces.com/contest/2117/problem/E 题目背景&#xff1a; 给定两个数组a,b&#xff0c;可以执行多次以下操作&#xff1a;选择 i (1 < i < n - 1)&#xff0c;并设置 或&#xff0c;也可以在执行上述操作前执行一次删除任意 和 。求…...

三体问题详解

从物理学角度&#xff0c;三体问题之所以不稳定&#xff0c;是因为三个天体在万有引力作用下相互作用&#xff0c;形成一个非线性耦合系统。我们可以从牛顿经典力学出发&#xff0c;列出具体的运动方程&#xff0c;并说明为何这个系统本质上是混沌的&#xff0c;无法得到一般解…...

C++ 求圆面积的程序(Program to find area of a circle)

给定半径r&#xff0c;求圆的面积。圆的面积应精确到小数点后5位。 例子&#xff1a; 输入&#xff1a;r 5 输出&#xff1a;78.53982 解释&#xff1a;由于面积 PI * r * r 3.14159265358979323846 * 5 * 5 78.53982&#xff0c;因为我们只保留小数点后 5 位数字。 输…...