栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

SpringSecurity中registerGlobal(),configure(),configureGlobal(),configureGlobalSecurity之间的区别

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringSecurity中registerGlobal(),configure(),configureGlobal(),configureGlobalSecurity之间的区别

实际上,您只有2个不同的选项。

选项1:仅使用注释 (它涵盖了示例1、3和4-请注意,样本中未包含相关注释)

registerGlobal
configureGlobal
configureGlobalSecurity
是准确的做事方式相同。您可以根据自己的喜好命名方法。唯一的约束是:

  • 注释方法
    @Autowired
  • 该方法必须在带有以下任一注释的类中:@EnableWebSecurity,@EnableWebMvcSecurity,@EnableGlobalMethodSecurity或@EnableGlobalAuthentication
  • (当然,该方法的参数类型为
    AuthenticationManagerBuilder

(如您所见,方法的名称并不重要,这就是为什么在搜索代码示例时发现这么多不同的方法名称的原因)

这是一个看起来像的例子:

@EnableWebSecuritypublic class MyConfiguration {    @Autowired    public void whatever(AuthenticationManagerBuilder auth) throws Exception {        auth.inMemoryAuthentication()          .withUser("user").password("password").roles("USER").and()          .withUser("admin").password("password").roles("USER", "ADMIN");    }    ...}

选项2:使用注释+方法覆盖 (涵盖示例2)

覆盖

configure
WebSecurityConfigurerAdapter
(或实现的任何@Configuration类的
WebSecurityConfigurer
)子类中的一种便捷方法,但与其他选项具有相同的效果。

如何选择正确的方法?

这只是口味/编程风格的问题,因为两种方法具有相同的效果。

当您希望/需要将配置保留在一个类中时,第一个选项才有意义,但是您的@Configuration类已经扩展了其他一些类(并且您不想实现整个WebSecurityConfigurer接口)。


让我们更详细地解释我的最后一点。Spring提供了许多 Adapter 类,您可以扩展它们以加快Spring配置的开发速度。

作为一个例子,让我们常用的适配器:

WebMvcConfigurerAdapter
。您将从这样一个非常简单的配置开始:

@EnableWebMvc@Configuration@ComponentScan({ "com.company.mypackage" })public class SpringWebConfig extends WebMvcConfigurerAdapter {}

重要的是:您的类已经扩展了 Adapter 类,因此您不能扩展另一个

现在,您需要添加安全配置。您可以选择将其包含在现有

SpringWebConfig
配置类中还是创建新的 特定于安全性的 配置类。这是两种方法的示例:

1)单@Configuration类方法

这里要注意的重要事项:SpringWebConfig 扩展了WebMvcConfigurerAdapter +
@EnableWebSecurity

@EnableWebMvc@Configuration@ComponentScan({ "com.company.mypackage" })@EnableWebSecuritypublic class SpringWebConfig extends WebMvcConfigurerAdapter {    @Autowired    public void whatever(AuthenticationManagerBuilder auth) throws Exception {        auth.inMemoryAuthentication()          .withUser("user").password("password").roles("USER").and()          .withUser("admin").password("password").roles("USER", "ADMIN");    }     }

2)特定的安全@Configuration类

这里要注意的重要事项:MySecurityConfig 扩展了WebSecurityConfigurerAdapter

保持 SpringWebConfig不变 ,并创建一个新

@Configuration
类:

@Configuration@EnableWebSecuritypublic class MySecurityConfig extends WebSecurityConfigurerAdapter {    @Overide    public void configure(AuthenticationManagerBuilder auth) throws Exception {        auth.inMemoryAuthentication()          .withUser("user").password("password").roles("USER").and()          .withUser("admin").password("password").roles("USER", "ADMIN");    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/569804.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号