SpringSecurity学习笔记(一) 核心类与接口

本文是SpringSecurity学习笔记的第一部分,主要探讨了SpringSecurity的核心类和接口,包括SecurityContextHolder、UserDetailsService和UserDetails。SecurityContextHolder用于存储应用程序的安全上下文信息,UserDetailsService是一个用于获取UserDetails的接口,而UserDetails则是代表用户的主体接口。此外,还介绍了核心服务如AuthenticationManager和AuthenticationProviders,它们在处理授权请求和验证过程中起着关键作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

SpringSecurity 核心类与接口

SecurityContextHolder

程序档安全环境的细节存储在它里边了,也包含了应用当前使用的主体细节,默认情况下,SecurityContextHolder使用ThreadLocal存储这些信息。

我们通过下面这种方法来获取当前用户信息

Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if (principal instanceof UserDetails) {
  String username = ((UserDetails)principal).getUsername();
} else {
  String username = principal.toString();
}

UserDetailsService

接口里的唯一一个方法,接收String类型的用户名参数,返回UserDetails,通常倾向于自己编写,但也可以通过使用官方提供的实现,比如InMemoryDaoImpl,JdbcDaoImpl

UserDetails loadUserByUsername(String username) throws UsernameNotFoundException;

UserDetails

Spring Security的核心接口,它代表一个主体,是扩展的。通常UserDetails转换成你系统提供的类,这样你就可以直接调用业务相关的方法了(比如getEmail(), getEmployeeNumber()等等)。

public interface UserDetails extends Serializable {
    Collection<? extends GrantedAuthority> getAuthorities();
    String getPassword();
    String getPassword();
    ....
}

核心服务

核心接口和他们的实现

AuthenticationManager

在Spring Security中的默认实现是ProviderManager 不只是处理授权请求自己,它委派了一系列配置好的AuthenticationProvider,每个按照顺序查看它是否可以执行验证。每个供应器会跑出一个异常,或者返回一个完整的 Authentication对象。

AuthenticationProviders

最常用的方式是验证一个授权请求读取 对应的UserDetails,并检查用户录入的密码。 这是通过DaoAuthenticationProvider实现的(见下面), 加载的UserDetails对象 - 特别是包含的 GrantedAuthority - 会在建立Authentication 时使用,这回返回一个成功验证,保存到SecurityContext中。

<bean id="authenticationManager"
     class="org.springframework.security.authentication.ProviderManager">
  <property name="providers">
    <list>
      <!--每个provider能够尝试进行授权,或通过返回null跳过授权。若所有实现都返回null,ProviderManager会抛出一个 ProviderNotFoundException异常-->
      <ref local="daoAuthenticationProvider"/>
    </list>
  </property>
</bean>
<!--最简单的AuthenticationProvider实现-->
<bean id="daoAuthenticationProvider"
    class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
  <property name="userDetailsService" ref="inMemoryDaoImpl"/>
  <!-- 以下都是可选项 用于提供密码的编码和解码以及用于提高密码安全性
  <property name="saltSource" ref bean="saltSource"/>
  <property name="passwordEncoder" ref="passwordEncoder"/>-->
</bean>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值