Spring Security面试题

news/2025/2/25 11:21:29

Spring Security面试题

基础概念

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

java">public class SecurityBasicDemo {
    // 1. 基本配置
    public class SecurityConfigExample {
        public void configDemo() {
            @Configuration
            @EnableWebSecurity
            public class SecurityConfig extends WebSecurityConfigurerAdapter {
                @Override
                protected 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");
                }
                
                @Override
                protected void configure(AuthenticationManagerBuilder auth) 
                    throws Exception {
                    auth
                        .inMemoryAuthentication()
                            .withUser("user")
                            .password(passwordEncoder().encode("password"))
                            .roles("USER");
                }
                
                @Bean
                public PasswordEncoder passwordEncoder() {
                    return new BCryptPasswordEncoder();
                }
            }
        }
    }
    
    // 2. 认证流程
    public class AuthenticationExample {
        public void authDemo() {
            // 自定义认证提供者
            @Component
            public class CustomAuthenticationProvider 
                implements AuthenticationProvider {
                
                @Override
                public 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");
                }
                
                @Override
                public boolean supports(Class<?> authentication) {
                    return authentication.equals(
                        UsernamePasswordAuthenticationToken.class);
                }
            }
        }
    }
}

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

java">public class AuthenticationAuthorizationDemo {
    // 1. 认证机制
    public class AuthenticationMechanismExample {
        public void authMechanismDemo() {
            // 用户详情服务
            @Service
            public class CustomUserDetailsService 
                implements UserDetailsService {
                
                @Override
                public 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 {
                
                @Override
                protected MethodSecurityExpressionHandler createExpressionHandler() {
                    DefaultMethodSecurityExpressionHandler expressionHandler = 
                        new DefaultMethodSecurityExpressionHandler();
                    expressionHandler.setPermissionEvaluator(
                        new CustomPermissionEvaluator());
                    return expressionHandler;
                }
            }
            
            // 使用注解
            @Service
            public 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实现是怎样的?

java">public class OAuth2Demo {
    // 1. 授权服务器
    public class AuthorizationServerExample {
        public void authServerDemo() {
            @Configuration
            @EnableAuthorizationServer
            public class AuthServerConfig 
                extends AuthorizationServerConfigurerAdapter {
                
                @Override
                public 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);
                }
                
                @Override
                public void configure(
                    AuthorizationServerSecurityConfigurer security) {
                    security
                        .tokenKeyAccess("permitAll()")
                        .checkTokenAccess("isAuthenticated()")
                        .allowFormAuthenticationForClients();
                }
            }
        }
    }
    
    // 2. 资源服务器
    public class ResourceServerExample {
        public void resourceServerDemo() {
            @Configuration
            @EnableResourceServer
            public class ResourceServerConfig 
                extends ResourceServerConfigurerAdapter {
                
                @Override
                public void configure(HttpSecurity http) throws Exception {
                    http
                        .authorizeRequests()
                            .antMatchers("/api/**").authenticated()
                            .anyRequest().permitAll()
                        .and()
                        .cors()
                        .and()
                        .csrf().disable();
                }
                
                @Override
                public void configure(ResourceServerSecurityConfigurer resources) {
                    resources.resourceId("resource_id");
                }
            }
        }
    }
}

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

java">public class SessionManagementDemo {
    // 1. 会话配置
    public class SessionConfigExample {
        public void sessionConfigDemo() {
            @Configuration
            public class SecurityConfig extends WebSecurityConfigurerAdapter {
                @Override
                protected 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() {
            @Component
            public class SecurityEventListener 
                implements ApplicationListener<AbstractAuthenticationEvent> {
                
                @Override
                public 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的安全防护有哪些?

java">public class SecurityProtectionDemo {
    // 1. CSRF防护
    public class CSRFProtectionExample {
        public void csrfDemo() {
            @Configuration
            public class SecurityConfig extends WebSecurityConfigurerAdapter {
                @Override
                protected void configure(HttpSecurity http) throws Exception {
                    http
                        .csrf()
                            .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
                            .ignoringAntMatchers("/api/webhook/**");
                }
            }
            
            // CSRF Token处理
            @Component
            public class CSRFTokenHandler extends OncePerRequestFilter {
                @Override
                protected 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过滤器
            @Component
            public class XSSFilter implements Filter {
                @Override
                public 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);
                }
                
                @Override
                public 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() {
            // 参数绑定
            @Repository
            public class UserRepository {
                @Autowired
                private 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")
                            )
                    );
                }
            }
            
            // 输入验证
            @Component
            public 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. 关注最佳实践

http://www.niftyadmin.cn/n/5865430.html

相关文章

1. EXCEL基础、界面介绍《AI赋能Excel 》

欢迎来到滔滔讲AI。 Excel表格是一种强大的电子表格软件&#xff0c;它不仅可以用来存储和组织数据&#xff0c;还可以进行复杂的计算、数据分析和可视化。无论是在工作,学习,还是日常生活中&#xff0c;Excel都经常用到&#xff0c;帮助人们管理和分析大量数据&#xff0c;做出…

【附源码】基于opencv+pyqt5搭建的人脸识别系统

文章目录 前言一、人脸检测二、人脸识别1.训练识别器2.识别人脸 三、界面相关1.Qlabel展示图片2.表格跟随内容而增加和减少3.选择图片文件4.警告框 四、源码获取总结 前言 人脸识别技术作为人工智能领域的一颗璀璨明珠&#xff0c;正逐渐渗透到我们生活的每一个角落&#xff0…

一周掌握Flutter开发--2、状态管理

文章目录 状态管理核心问题必学方案2.1 简单场景&#xff1a;StatefulWidget setState2.2 复杂场景&#xff1a;Provider、Riverpod、Bloc 或 GetX2.3 理解 InheritedWidget 和 ValueNotifier 的原理 总结 状态管理 状态管理是 Flutter 开发中的核心问题之一&#xff0c;尤其…

python 判断 字符串在字典列表中 并获取对应字典

在Python中&#xff0c;如果你想判断一个字符串是否存在于一个字典列表中&#xff0c;并获取对应的字典&#xff0c;你可以使用多种方法。下面是一些常见的方法来实现这个功能&#xff1a; 方法1&#xff1a;使用列表推导式和any() 如果你想要检查字符串是否存在于字典列表中的…

【ECMAScript6】

【ECMAScript6】 01. ES6介绍02. let和const命令03. 模板字符串04. 函数之默认值、剩余参数05. 函数之扩展运算符、箭头函数06. 箭头函数this指向和注意事项07. 解构赋值08. 扩展的对象的功能&#xff08;简写&#xff09;09. Symbol类型10. Set集合数据类型11. Map数据类型12.…

java23种设计模式-组合模式

组合模式&#xff08;Composite Pattern&#xff09;学习笔记 &#x1f31f; 定义 组合模式属于结构型设计模式&#xff0c;用于将对象组合成树形结构以表示"部分-整体"层次结构。它使得用户对单个对象和组合对象的使用具有一致性。 &#x1f3af; 适用场景 需要表…

Docker(Nginx)部署Vue

简介&#xff1a;目标使用docker将vue生成的dist文件&#xff0c;结合nginx生成镜像&#xff0c;然后运行&#xff1b; 1、首选确保vue项目正确运行&#xff0c;并能正确打包dist文件&#xff1b; 2、查看已经生成的dist文件 3、将dist文件打包为rar文件或者zip文件&#xf…

2025年能源工程与电气技术国际学术会议(EEET2025)

2025年能源工程与电气技术国际学术会议&#xff08;EEET2025&#xff09; 2025 International Conference on Energy Engineering and Electrical Technology 中国 广州 2025年03月28日—30日 【重要信息】 会议时间&#xff1a;2025年03月28-30日 会议地点&#xff1a;中…