springSecurity学习之springSecurity简

2024-07-18  本文已影响0人  墨线宝

springSecurity简介

Spring Security 基于 Spring 框架,提供了一套 Web 应用安全性的完整解决方案,是一种基于Spring AOP和Servlet规范中的Filter实现的安全框架,其本质是一个过滤器链

名词解释

主体(principal)使用系统的用户或设备或从其他系统远程登录的用户等等,谁在使用该系统

认证(authentication)权限管理系统确认一个主体的身份,允许主体进入系统,“主体”证明自己是谁

授权(authorization)将操作系统的“权力”授予“主体”,这样主体就具备了操作系统中特定功能的能力,授权就是给用户分配权限

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-security</artifactId>
</dependency>

核心类

进行认证

UsernamePasswordAuthenticationFilter

对/login 的 POST 请求做拦截,校验表单中用户名,密码

public Authentication attemptAuthentication(HttpServletRequest request,
      HttpServletResponse response) throws AuthenticationException {
   if (postOnly && !request.getMethod().equals("POST")) {
      throw new AuthenticationServiceException(
            "Authentication method not supported: " + request.getMethod());
   }

   String username = obtainUsername(request);
   String password = obtainPassword(request);

   if (username == null) {
      username = "";
   }

   if (password == null) {
      password = "";
   }

   username = username.trim();
    // 用户名和密码被过滤器获取到,封装成 Authentication,通常情况下是 UsernamePasswordAuthenticationToken这个实现类
   UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
         username, password);

   // Allow subclasses to set the "details" property
   setDetails(request, authRequest);
    // AuthenticationManager 身份管理器负责验证这个 Authentication
   return this.getAuthenticationManager().authenticate(authRequest);
}
# 配置用户名,密码
security:
  user:
    name: admin
    password: admin

其中的用户名密码都是spring security生成或者配置的,但是在实际使用中用户名和密码都是从数据库去进行读取的,所以这段逻辑需要进行自定义,如果需要自定义逻辑时,需要实现 UserDetailsService 接口

public interface UserDetailsService {
   
   UserDetails loadUserByUsername(String username) throws UsernameNotFoundException;
}

https://zhhll.icu/2021/框架/springSecurity/1.springSecurity简介/

上一篇 下一篇

猜你喜欢

热点阅读