• spring-security-oauth2之WebSecurityConfigurerAdapter浅析


    衔接上文,下面聊聊配置Oauth2服务时的配置类WebSecurityConfigurerAdapter。
    1、WebSecurityConfigurerAdapter
    WebSecurityConfigurerAdapter继承自WebSecurityConfigurer,在Spring Boot 中的自动配置实际上是通过自动配置包下的 SecurityAutoConfiguration 总配置类上导入的 Spring Boot Web 安全配置类 SpringBootWebSecurityConfiguration 来配置的。
    提供的具体方法如下:
    在这里插入图片描述
    主要配置3个configure:

    • configure(AuthenticationManagerBuilder)
    • configure(HttpSecurity)
    • configure(WebSecurity)

    第1个是配置认证管理器AuthenticationManager,第2个主要是配置 Spring Security 中的过滤器链,第3个主要是配置一些路径放行规则。

    2、AuthenticationManagerBuilder
    void configure(AuthenticationManagerBuilder auth) 用来配置认证管理器AuthenticationManager,说白了就是所有 UserDetails 相关的它都管,包含 PasswordEncoder 密码等。
    常见用法:

     //默认认证管理器DaoAuthenticationConfigurer注入用户信息
     @Override
     protected void configure(AuthenticationManagerBuilder auth) throws Exception {
         auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
     }
     //或自定义认证
     protected void configure(AuthenticationManagerBuilder auth) {
         // 自定义认证
         auth.authenticationProvider(customAuthenticationProvider());
     }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    3、HttpSecurity
    void configure(HttpSecurity http) 这个是我们使用最多的,用来配置 HttpSecurity 。 HttpSecurity 用于构建一个安全过滤器链 SecurityFilterChain ,SecurityFilterChain 最终被注入核心过滤器 。 HttpSecurity 有许多我们需要的配置,可以通过它来进行自定义安全访问策略。
    常见用法:

    	@Override
        protected void configure(HttpSecurity http) throws Exception {
            http.cors().disable();
            http.csrf().disable();
            http
                    .requestMatchers().antMatchers("/oauth/**")
                    //拦截上面匹配后的url,需要认证后访问
                    .and()
                    .authorizeRequests().antMatchers("/oauth/**").authenticated();
            http
                    .sessionManagement()
                    .invalidSessionUrl("/login")
                    .maximumSessions(1)
                    .expiredUrl("/login");
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
  • 相关阅读:
    第六章:路由交换机及操作系统
    java常用排序算法——冒泡排序,选择排序概述
    【POJ No. 1577 / UVA No. 1525】落叶 Falling Leaves
    QML使用C++ model(基本用法)
    AIGC ChatGPT4 读取接口文件并进行可视化分析
    金融统计学方法:神经网络
    基于SSM养老院管理系统毕业设计-附源码221609
    MessageQueue和Looper学习
    计算机辅助数据绘图(matlab\python\js)
    基于像素特征的kmeas聚类的图像分割方案
  • 原文地址:https://blog.csdn.net/leijie0322/article/details/126642866