SpringBoot - WebSecurityConfigurerAdapter的作用是什么?

写在前面

WebSecurityConfigurer 只是一个空接口,WebSecurityConfigurerAdapter 就是针对这个空接口提供一个具体的实现,最终目的还是为了方便配置 WebSecurity。

public abstract class WebSecurityConfigurerAdapter 
		        implements WebSecurityConfigurer<WebSecurity> {}

一句话:Spring Security提供了一个抽象类WebSecurityConfigurerAdapter,它实现了默认的认证和授权,允许用户自定义一个WebSecurity类,重写其中的三个configure来实现自定义的认证和授权,这三个方法如下:

// 自定义身份认证的逻辑
protected void configure(AuthenticationManagerBuilder auth) throws Exception { }
// 自定义全局安全过滤的逻辑
public void configure(WebSecurity web) throws Exception { }
// 自定义URL访问权限的逻辑
protected void configure(HttpSecurity http) throws Exception { }

SpringBoot - HttpSecurity是什么?
SpringBoot - WebMvcConfigurer的作用是什么?

作用是什么?

WebSecurityConfigurerAdapter 管理着Spring Security的整个配置体系,主要包括用户身份认证的管理、全局安全过滤管理和URL访问权限控制的管理。

身份认证

/**
 * 身份认证接口
 */
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
}

/**
 * 强散列哈希加密实现
 */
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
    return new BCryptPasswordEncoder();
}

全局过滤

我们一般不会过多来自定义 WebSecurity , 使用较多的使其ignoring() 方法用来忽略 Spring Security 对静态资源的控制。

访问控制

@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
    // 注解标记允许匿名访问的url
    ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = httpSecurity.authorizeRequests();
    permitAllUrl.getUrls().forEach(url -> registry.antMatchers(url).permitAll());

    httpSecurity
            // CSRF禁用,因为不使用session
            .csrf().disable()
            // 认证失败处理类
            .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
            // 基于token,所以不需要session
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
            // 过滤请求
            .authorizeRequests()
            // 1. 对于登录、注册和验证码等方法允许匿名访问
            .antMatchers("/login", "/register", "/captchaImage").anonymous()
            // 2. 对于静态资源允许任何用户访问
            .antMatchers(HttpMethod.GET, "/", "/*.html", "/**/*.html", "/**/*.css", "/**/*.js", "/profile/**").permitAll()
            // 3. 对于SWAGGER相关信息允许任何用户访问
            .antMatchers("/swagger-ui.html", "/swagger-resources/**", "/webjars/**", "/*/api-docs", "/druid/**").permitAll()
            // 除上面1.2.3.以外的所有请求全部需要鉴权认证
            .anyRequest().authenticated()
            .and()
            .headers().frameOptions().disable();

    // 添加自定义的登出处理器
    httpSecurity.logout().logoutUrl("/logout").logoutSuccessHandler(logoutSuccessHandler);
    // 在UsernamePasswordAuthenticationFilter之前添加自定义的JWT过滤器
    httpSecurity.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
    // 在自定义的JWT过滤器前添加跨域过滤器
    httpSecurity.addFilterBefore(corsFilter, JwtAuthenticationTokenFilter.class);
    // 在用户登出过滤器前添加跨域过滤器
    httpSecurity.addFilterBefore(corsFilter, LogoutFilter.class);
}

WebSecurityConfigurerAdapter 和 ResourceServerConfigurerAdapter的区别

① 模块不同

A. WebSecurityConfigurerAdapter:是spring-security-config包中的;
B. ResourceServerConfigurerAdapter:是spring-security-oauth2中包中的;

② 优先级不同

①. 默认自动注册时@Order的优先级不同,@Order(数字),数字值越小,优先级越高,然后相同的方法只使用优先级高的,这也就是为啥同时使用资源服务配置与安全配置的时候,且不手动指定@Order注解的值的时候,后者的配置不生效,当然可以通过手动指定@Order(数字)来调整优先级的高低。
②. ResourceServerConfigurerAdapter与WebSecurityConfigurerAdapter同时使用只有ResourceServerConfigurerAdapter生效。
③. 如果想让WebSecurityConfigurerAdapter比ResourceServerConfigurerAdapter优先级高的话,只须将前者的@Order值设置的比后者的@Order值更低即可。

A. WebSecurityConfigurerAdapter:@Order(数字),数字大,优先级低;
B. ResourceServerConfigurerAdapter:@Order(数字),数字小,优先级高;

  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
您好!对于未授权的springboot-actuator,您可以尝试以下解决方案: 1. 检查配置文件:确保您的应用程序的配置文件中已正确配置了安全认证。您可以在application.properties或application.yml文件中查找以下配置项: management.security.enabled=true 如果该配置项已启用,并且您仍然遇到未授权的问题,请继续尝试下一个解决方案。 2. 添加访问权限:您可以为actuator端点添加访问权限。在您的配置文件中添加以下配置来设置允许访问的角色: management.endpoints.web.exposure.include=* management.endpoint.health.roles=ACTUATOR_ADMIN 这将允许所有角色访问所有的actuator端点。您可以根据需要更改角色名称或将其限制为特定角色。 3. 自定义安全配置:如果默认的安全配置不适用于您的需求,您可以自定义Spring Security配置。创建一个类,继承自WebSecurityConfigurerAdapter,并重写configure方法。在该方法中,您可以定义自己的安全规则和访问规则。 例如,您可以创建一个类似于以下示例的配置: ```java @Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/actuator/**").hasRole("ACTUATOR_ADMIN") .anyRequest().authenticated() .and() .httpBasic(); } } ``` 这将要求用户在访问actuator端点时进行身份验证,并且只有具有ACTUATOR_ADMIN角色的用户才能访问。 请注意,根据您的具体需求,您可能需要调整上述解决方案的细节。希望这些提示对您有帮助!如有更多问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值