当前位置:首页 > 科技  > 软件

全新Spring Security安全管理配置使用详解

来源: 责编: 时间:2024-02-02 17:00:41 295观看
导读环境:SpringBoot2.7.12 + JDK211. 简介Spring Security 是一个提供身份验证、授权和防护常见攻击的框架。它为确保命令式和反应式应用程序的安全提供一流的支持,是确保基于 Spring 的应用程序安全的事实标准。Spring Sc

环境:SpringBoot2.7.12 + JDK21DgJ28资讯网——每日最新资讯28at.com

1. 简介

Spring Security 是一个提供身份验证、授权和防护常见攻击的框架。它为确保命令式和反应式应用程序的安全提供一流的支持,是确保基于 Spring 的应用程序安全的事实标准。DgJ28资讯网——每日最新资讯28at.com

Spring Scurity核心分为2大模块:DgJ28资讯网——每日最新资讯28at.com

  1. 认证(Authentication):认证是建立一个他声明的主体的过程(一个主体一般是指用户、设备或一些可以在你的应用程序中执行的其他系统)。常见的身份认证一般要求用户提供用户名和密码。系统通过校验用户名和密码来完成认证过程。
  2. 授权(Authorization):当身份认证通过后,去访问系统的资源,系统会判断用户是否拥有访问该资源的权限,只允许访问有权限的系统资源,没有权限的资源将无法访问,这个过程叫用户授权。比如会员管理模块有增删改查功能,有的用户只能进行查询,而有的用户可以进行修改、删除。一般来说,系统会为不同的用户分配不同的角色,而每个角色则对应一系列的权限。

从Spring Security5.7开始之前的安全配置方式及Web授权处理方式发生了变化,接下来将详细介绍配置的变化。DgJ28资讯网——每日最新资讯28at.com

2. 安全配置

2.1 配置方式

在5.7之前的版本自定义安全配置通过如下方式:DgJ28资讯网——每日最新资讯28at.com

@Componentpublic class SecurityConfig extends WebSecurityConfigurerAdapter {  protected void configure(HttpSecurity http) throws Exception {    // ...  }}

在5.7之后推荐如下配置方式DgJ28资讯网——每日最新资讯28at.com

@Configurationpublic class SecurityConfig {  @Bean  @Order(Ordered.HIGHEST_PRECEDENCE)  SecurityFilterChain controllerFilterChain(HttpSecurity http) throws Exception {    // ...    return http.build() ;  }}

通过配置安全过滤器链的方式配置,具体内部的配置细节还都是围绕着HttpSecurity进行配置。DgJ28资讯网——每日最新资讯28at.com

2.2 配置不同的过滤器链

在一个配置文件中我们可以非常方便的配置多个过滤器链,针对不同的请求进行拦截。DgJ28资讯网——每日最新资讯28at.com

@Configurationpublic class SecurityConfig {  @Bean  @Order(1)  SecurityFilterChain controllerFilterChain(HttpSecurity http) {    // 当前过滤器链只对/demos/**, /login, /logout进行拦截    http.requestMatchers(matchers -> matchers.antMatchers("/demos/**", "/login", "/logout")) ;    http.authorizeHttpRequests().antMatchers("/**").authenticated() ;    http.formLogin(Customizer.withDefaults()) ;    // ...    return http.build() ;  }  @Bean  @Order(2)  SecurityFilterChain managementSecurityFilterChain(HttpSecurity http) throws Exception {    // 该过滤器只会对/ac/**的请求进行拦截    http.requestMatchers(matchers -> matchers.antMatchers("/ac/**")) ;    // ...    http.formLogin(Customizer.withDefaults());    return http.build();  }}

以上配置了2个过滤器链,根据配置的@Order值,优先级分别:controllerFilterChain,managementSecurityFilterChain。当访问除上面指定的uri模式以为的请求都将自动放行。DgJ28资讯网——每日最新资讯28at.com

2.3 用户验证配置

在5.7版本之前,我们通过如下配置配置内存用户DgJ28资讯网——每日最新资讯28at.com

public class SecurityConfig extends WebSecurityConfigurerAdapter {  @Override  protected void configure(AuthenticationManagerBuilder auth) throws Exception {    auth.inMemoryAuthentication()      .passwordEncoder(NoOpPasswordEncoder.getInstance())      .withUser("admin")      .password("123123")      .authorities(Arrays.asList(new SimpleGrantedAuthority("ROLE_ADMIN"))) ;  }}

5.7 只有由于推荐的是通过自定义SecurityFilterChain的方式,所以我们需要通过如下的方式进行配置:DgJ28资讯网——每日最新资讯28at.com

@Configurationpublic class SecurityConfig {  @Bean  @Order(0)  SecurityFilterChain controllerFilterChain(HttpSecurity http) throws Exception {    AuthenticationManagerBuilder builder = http.getSharedObject(AuthenticationManagerBuilder.class) ;    builder.inMemoryAuthentication()      .passwordEncoder(NoOpPasswordEncoder.getInstance())      .withUser("admin")      .password("123123")      .authorities(Arrays.asList(new SimpleGrantedAuthority("ROLE_ADMIN"))) ;    // ...  }}

2.4 授权方式

在5.7之后推荐配置认证授权的方式如下DgJ28资讯网——每日最新资讯28at.com

@Beanpublic SecurityFilterChain apiSecurityFilterChain(HttpSecurity http) throws Exception {  http.authorizeHttpRequests().antMatchers("/users/**").hasAnyRole("ADMIN") ;  // ...  return http.build() ;}

通过上面的authorizeHttpRequests方式进行授权配置,会向过滤器链中添加AuthorizationFilter过滤器。在该过滤器中会进行权限的验证。DgJ28资讯网——每日最新资讯28at.com

2.5 自定义授权决策

如果需要对请求的uri进行更加精确的匹配验证,如:/users/{id},需要验证只有这里的id值为666才方向。DgJ28资讯网——每日最新资讯28at.com

@Beanpublic SecurityFilterChain apiSecurityFilterChain(HttpSecurity http) throws Exception {  http.authorizeHttpRequests(registry -> {    registry.antMatchers("/users/{id}").access(new AuthorizationManager<RequestAuthorizationContext>() {      @Override      public AuthorizationDecision check(Supplier<Authentication> authentication,          RequestAuthorizationContext object)        // 获取路径上的值信息,其中key=id,value=xxx        Map<String, String> variables         // 这里的第一个参数是boolean,确定了授权是否通过        return new AuthorityAuthorizationDecision(variables.get("id").equals("666"), Arrays.asList(new SimpleGrantedAuthority("D"))) ;      }    }) ;  }) ;}

2.6 全局认证

如果配置了多个不同的SecurityFilterChain,而每个认证都使用相同的用户体系,那么我们可以定义AuthenticationProvider或者UserDetailsService 类型的Bean即可。DgJ28资讯网——每日最新资讯28at.com

@BeanUserDetailsService userDetailsService() {  return new UserDetailsService() {    @Override    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {      return null;    }  } ;}@BeanAuthenticationProvider authenticationProvider() {  return new AuthenticationProvider() {    @Override    public Authentication authenticate(Authentication authentication) throws AuthenticationException {      return null;    }    @Override    public boolean supports(Class<?> authentication) {      return false;    }  } ;}


DgJ28资讯网——每日最新资讯28at.com

以上是本篇文章的全部内容, 希望对你有所帮助。DgJ28资讯网——每日最新资讯28at.com

完毕!!!DgJ28资讯网——每日最新资讯28at.com

本文链接:http://www.28at.com/showinfo-26-71943-0.html全新Spring Security安全管理配置使用详解

声明:本网页内容旨在传播知识,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。邮件:2376512515@qq.com

上一篇: 我们一起聊聊如何提高API性能的综合策略

下一篇: Nodejs - 九步开启JWT身份验证

标签:
  • 热门焦点
  • 7月安卓手机性能榜:红魔8S Pro再夺榜首

    7月份的手机市场风平浪静,除了红魔和努比亚带来了两款搭载骁龙8Gen2领先版处理器的新机之外,别的也想不到有什么新品了,这也正常,通常6月7月都是手机厂商修整的时间,进入8月份之
  • Raft算法:保障分布式系统共识的稳健之道

    1. 什么是Raft算法?Raft 是英文”Reliable、Replicated、Redundant、And Fault-Tolerant”(“可靠、可复制、可冗余、可容错”)的首字母缩写。Raft算法是一种用于在分布式系统
  • 从 Pulsar Client 的原理到它的监控面板

    背景前段时间业务团队偶尔会碰到一些 Pulsar 使用的问题,比如消息阻塞不消费了、生产者消息发送缓慢等各种问题。虽然我们有个监控页面可以根据 topic 维度查看他的发送状态,
  • 得物效率前端微应用推进过程与思考

    一、背景效率工程随着业务的发展,组织规模的扩大,越来越多的企业开始意识到协作效率对于企业团队的重要性,甚至是决定其在某个行业竞争中突围的关键,是企业长久生存的根本。得物
  • WebRTC.Net库开发进阶,教你实现屏幕共享和多路复用!

    WebRTC.Net库:让你的应用更亲民友好,实现视频通话无痛接入! 除了基本用法外,还有一些进阶用法可以更好地利用该库。自定义 STUN/TURN 服务器配置WebRTC.Net 默认使用 Google 的
  • 共享单车的故事讲到哪了?

    来源丨海克财经与共享充电宝相差不多,共享单车已很久没有被国内热点新闻关照到了。除了一再涨价和用户直呼用不起了。近日多家媒体再发报道称,成都、天津、郑州等地多个共享单
  • 2纳米决战2025

    集微网报道 从三强争霸到四雄逐鹿,2nm的厮杀声已然隐约传来。无论是老牌劲旅台积电、三星,还是誓言重回先进制程领先地位的英特尔,甚至初成立不久的新
  • iQOO Neo8 Pro评测:旗舰双芯加持 最强性能游戏旗舰

    【Techweb评测】去年10月,iQOO推出了一款Neo7手机,该机搭载了联发科天玑9000+,配备独显芯片Pro+,带来了同价位段最佳的游戏体验,一经上市便受到了诸多用
  • DRAM存储器10月价格下跌,NAND闪存本月价格与上月持平

    10月30日,据韩国媒体消息,自今年年初以来一直在上涨的 DRAM 存储器的交易价格仅在本月就下跌了近 10%,此次是全年首次降价,而NAND 闪存本月价格与上月持平。市
Top