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

Spring Security面试题

Spring Security面试题

基础概念

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

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的认证和授权机制是怎样的?

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实现是怎样的?

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的会话管理是怎样的?

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的安全防护有哪些?

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. 关注最佳实践

相关文章:

  • BFS 解决 拓扑排序(典型算法思想)—— OJ例题算法解析思路
  • 爬虫解析库:parsel的详细使用
  • 类和对象之间的区别是什么
  • Vue3项目与pnpm使用教程
  • 若依前后端分离框架修改3.8.9版本(重点在安全框架讲解与微信小程序登录集成)
  • gihub上适合练手的Python项目(2)
  • P8772 [蓝桥杯 2022 省 A] 求和--简单题的陷阱——(不开long long见祖宗!!!
  • SpringSecurity处理器:登录成功处理器、登录失败处理器、无权限处理器、注销成功处理器
  • TVS管学习记录
  • Threejs教程一【三要素】
  • 01.Zabbix 概述
  • 算法日常刷题笔记(2)
  • c++面试准备
  • 基于Docker的前端环境管理:从开发环境到生产部署的实现方案
  • 【MySQL】表的增删查改(CRUD)(上)
  • 20250224解决在WIN10下东芝HGST的AIC 3.2T的PCIE3.0接口企业级固态只能怪找到1.8T的问题
  • LeetCode刷题---栈---844
  • MySQL数据库——多版本并发控制MVCC
  • 毕业离校管理系统的开发与需求分析
  • 软件需求管理办法,软件开发管理指南(Word原件)
  • 手机网站测试/百度ocpc如何优化
  • 传奇网页游戏制作/seo查询 站长之家
  • 在哪些网站可以做企业名称预审/文明seo
  • 天津网站建设市场/深圳百度推广电话
  • 网站国际化怎么做/舆情网站入口
  • 网站设计需要注意什么/网店网络推广方案