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("<", "<").replaceAll(">", ">");}}}}// 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_]+");}}}}
}
面试关键点
- 理解Spring Security的核心功能
- 掌握认证和授权机制
- 熟悉OAuth2.0的实现
- 了解会话管理机制
- 理解安全防护措施
- 掌握配置和扩展方法
- 注意性能和安全平衡
- 关注最佳实践
相关文章:
Spring Security面试题
Spring Security面试题 基础概念 Q1: Spring Security的核心功能有哪些? 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. 核心技术创新(1)集群协同控制技术(2)感知与能源系统升级 2. 行业应用落地(1)智慧城市与安防(2)应急救援(…...
【亲测有效】百度Ueditor富文本编辑器添加插入视频、视频不显示、和插入视频后二次编辑视频标签不显示,显示成img标签,二次保存视频被替换问题,解决方案
【亲测有效】项目使用百度Ueditor富文本编辑器上传视频相关操作问题 1.百度Ueditor富文本编辑器添加插入视频、视频不显示 2.百度Ueditor富文本编辑器插入视频后二次编辑视频标签不显示,在编辑器内显示成img标签,二次保存视频被替换问题 问题1࿱…...
ubuntu windows双系统踩坑
我有个台式机,先安装的ubuntu,本来想专门用来做开发,后面儿子长大了,给他看了一下星际争霸、魔兽争霸,立马就迷上了。还有一台windows的笔记本,想着可以和他联局域网一起玩,在ubuntu上用wine跑魔…...
嵌入式八股文(五)硬件电路篇
一、名词概念 1. 整流和逆变 (1)整流:整流是将交流电(AC)转变为直流电(DC)。常见的整流电路包括单向整流(二极管)、桥式整流等。 半波整流:只使用交流电的正…...
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):图像直方图
在图像处理中,直方图是一种非常重要的工具,它可以帮助我们了解图像的像素分布情况。通过分析图像的直方图,我们可以进行图像增强、对比度调整、图像分割等操作。 1 什么是图像直方图? 图像直方图是图像像素强度分布的图形表示&am…...
力扣LeetCode:1656 设计有序流
题目: 有 n 个 (id, value) 对,其中 id 是 1 到 n 之间的一个整数,value 是一个字符串。不存在 id 相同的两个 (id, value) 对。 设计一个流,以 任意 顺序获取 n 个 (id, value) 对,并在多次调用时 按 id 递增的顺序…...
NGINX配置TCP负载均衡
前言 之前本人做项目需要用到nginx的tcp负载均衡,这里是当时配置做的笔记;欢迎收藏 关注,本人将会持续更新 文章目录 配置Nginx的负载均衡 配置Nginx的负载均衡 nginx编译安装需要先安装pcre、openssl、zlib等库,也可以直接编译…...
vm和centos
安装 VMware Workstation Pro 1. 下载 VMware Workstation Pro 访问 VMware 官方网站(https://www.vmware.com/cn/products/workstation-pro/workstation-pro-evaluation.html ),在该页面中点击 “立即下载” 按钮,选择适合你操作…...
c#丰田PLC ToyoPuc TCP协议快速读写 to c# Toyota PLC ToyoPuc读写
源代码下载 <------下载地址 历史背景与发展 TOYOPUC协议源于丰田工机(TOYODA)的自动化技术积累。丰田工机成立于1941年,最初是丰田汽车的机床部门,后独立为专注于工业机械与控制系统的公司。2006年与光洋精工(Ko…...
量子计算的数学基础:复数、矩阵和线性代数
量子计算是基于量子力学原理的一种新型计算模式,它与经典计算机在信息处理的方式上有着根本性的区别。在量子计算中,信息的最小单位是量子比特(qubit),而不是传统计算中的比特。量子比特的状态是通过量子力学中的数学工具来描述的,因此,理解量子计算的数学基础对于深入学…...
【JavaScript】《JavaScript高级程序设计 (第4版) 》笔记-Chapter22-处理 XML
二十二、处理 XML 处理 XML XML 曾一度是在互联网上存储和传输结构化数据的标准。XML 的发展反映了 Web 的发展,因为DOM 标准不仅是为了在浏览器中使用,而且还为了在桌面和服务器应用程序中处理 XML 数据结构。在没有 DOM 标准的时候,很多开发…...
一个不错的API测试框架——Karate
Karate 是一款开源的 API 测试工具,基于 BDD(行为驱动开发)框架 Cucumber 构建,但无需编写 Java 或 JavaScript 代码即可直接编写测试用例。它结合了 API 测试、模拟(Mocking)和性能测试功能,支持 HTTP、GraphQL 和 WebSocket 等协议,语法简洁易读。 Karate详细介绍 K…...
文字语音相互转换
目录 1.介绍 2.思路 3.安装python包 3.程序: 4.运行结果 1.介绍 当我们使用一些本地部署的语言模型的时候,往往只能进行文字对话,这一片博客教大家如何实现语音转文字和文字转语音,之后接入ollama的模型就能进行语音对话了。…...
DeepSeek-R1:通过强化学习激发大语言模型的推理能力
注:此文章内容均节选自充电了么创始人,CEO兼CTO陈敬雷老师的新书《自然语言处理原理与实战》(人工智能科学与技术丛书)【陈敬雷编著】【清华大学出版社】 文章目录 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类型数据,将map使用claims方法放入JWT令牌后,取出时变成Double类型,强转报错: 解决: 将Integer转为String后存入JWT令牌,不会被自动转为其他类型,取出后转为Integ…...
网络编程(Modbus进阶)
思维导图 Modbus RTU(先学一点理论) 概念 Modbus RTU 是工业自动化领域 最广泛应用的串行通信协议,由 Modicon 公司(现施耐德电气)于 1979 年推出。它以 高效率、强健性、易实现的特点成为工业控制系统的通信标准。 包…...
centos 7 部署awstats 网站访问检测
一、基础环境准备(两种安装方式都要做) bash # 安装必要依赖 yum install -y httpd perl mod_perl perl-Time-HiRes perl-DateTime systemctl enable httpd # 设置 Apache 开机自启 systemctl start httpd # 启动 Apache二、安装 AWStats࿰…...
在四层代理中还原真实客户端ngx_stream_realip_module
一、模块原理与价值 PROXY Protocol 回溯 第三方负载均衡(如 HAProxy、AWS NLB、阿里 SLB)发起上游连接时,将真实客户端 IP/Port 写入 PROXY Protocol v1/v2 头。Stream 层接收到头部后,ngx_stream_realip_module 从中提取原始信息…...
Java 加密常用的各种算法及其选择
在数字化时代,数据安全至关重要,Java 作为广泛应用的编程语言,提供了丰富的加密算法来保障数据的保密性、完整性和真实性。了解这些常用加密算法及其适用场景,有助于开发者在不同的业务需求中做出正确的选择。 一、对称加密算法…...
AI,如何重构理解、匹配与决策?
AI 时代,我们如何理解消费? 作者|王彬 封面|Unplash 人们通过信息理解世界。 曾几何时,PC 与移动互联网重塑了人们的购物路径:信息变得唾手可得,商品决策变得高度依赖内容。 但 AI 时代的来…...
HarmonyOS运动开发:如何用mpchart绘制运动配速图表
##鸿蒙核心技术##运动开发##Sensor Service Kit(传感器服务)# 前言 在运动类应用中,运动数据的可视化是提升用户体验的重要环节。通过直观的图表展示运动过程中的关键数据,如配速、距离、卡路里消耗等,用户可以更清晰…...
《C++ 模板》
目录 函数模板 类模板 非类型模板参数 模板特化 函数模板特化 类模板的特化 模板,就像一个模具,里面可以将不同类型的材料做成一个形状,其分为函数模板和类模板。 函数模板 函数模板可以简化函数重载的代码。格式:templa…...
快刀集(1): 一刀斩断视频片头广告
一刀流:用一个简单脚本,秒杀视频片头广告,还你清爽观影体验。 1. 引子 作为一个爱生活、爱学习、爱收藏高清资源的老码农,平时写代码之余看看电影、补补片,是再正常不过的事。 电影嘛,要沉浸,…...
【从零开始学习JVM | 第四篇】类加载器和双亲委派机制(高频面试题)
前言: 双亲委派机制对于面试这块来说非常重要,在实际开发中也是经常遇见需要打破双亲委派的需求,今天我们一起来探索一下什么是双亲委派机制,在此之前我们先介绍一下类的加载器。 目录 编辑 前言: 类加载器 1. …...
字符串哈希+KMP
P10468 兔子与兔子 #include<bits/stdc.h> using namespace std; typedef unsigned long long ull; const int N 1000010; ull a[N], pw[N]; int n; ull gethash(int l, int r){return a[r] - a[l - 1] * pw[r - l 1]; } signed main(){ios::sync_with_stdio(false), …...
