当前位置: 首页> 教育> 大学 > Spring Security的认证检验

Spring Security的认证检验

时间:2025/7/10 15:22:52来源:https://blog.csdn.net/weixin_53908842/article/details/139798722 浏览次数:1次

Spring Security中,认证的请求和未认证的请求的区别主要体现在请求的方式和用户的访问权限。

认证的请求

认证的请求是指用户已经通过身份验证(例如,用户名,密码)并且拥有一个有效的认证令牌(例如,Authentication对象)。这类请求的特点包括:

有一个有效的Authentication对象

  • Spring Security会在用户成功登录后创建一个Authentication对象,并将其存储在安全上下文中(SecurityContext)。
  • 通过调用SecurityContextHolder.getContext().getAuthentication()可以获取当前用户的认证信息。
可以访问受保护的资源
  • 经过认证的用户可以访问受保护的资源和功能,这些资源通常在安全配置中定义。
  • 例如,在HttpSecurity配置中,只有认证用户才能访问/user/**路径
http.authorizeRequests().antMatchers("/user/**").authenticated();

包含用户详细信息和权限

  • Authentication对象中包含了用户的详细信息(如用户名、权限等)。
  • 可以通过Authentication对象获取用户的角色和权限,从而进行访问控制和授权。

未认证的请求

访问受限

  • 未认证的用户只能访问那些在安全配置中明确允许匿名或公开访问的资源。
重定向到登录页面或返回未授权错误
  • 对于未认证用户试图访问受保护资源的请求,Spring Security会自动拦截并引导用户进行身份验证(通常重定向到登录页面)。
  • 例如,未认证用户试图访问/user/profile时会被重定向到登录页面。

处理流程

未认证请求

  • 用户访问受保护的资源。
  • Spring Security检查SecurityContext,发现没有有效的Authentication对象。
  • 根据安全配置,Spring Security引导用户进行身份验证(例如重定向到登录页面)。
  • 用户提交登录表单,Spring Security进行身份验证。
  • 身份验证成功后,Spring Security创建Authentication对象并存储在SecurityContext中。

认证请求

  • 用户访问受保护的资源。
  • Spring Security检查SecurityContext,发现有一个有效的Authentication对象。
  • Spring Security根据用户的角色和权限决定是否允许访问请求的资源。
  • 如果允许,Spring Security将请求转发到目标资源。
  • 如果不允许(例如权限不足),Spring Security返回403 Forbidden错误。
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/login", "/public/**").permitAll() // 未认证用户可以访问.antMatchers("/admin/**").hasRole("ADMIN") // 只有ADMIN角色用户可以访问.antMatchers("/user/**").authenticated() // 任何认证用户都可以访问.anyRequest().permitAll().and().formLogin().loginPage("/login") // 登录页面.permitAll().and().logout().permitAll();}
}

关键字:Spring Security的认证检验

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: