SpringSecurity笔记整理

自定义登录页面

  1. 编写登录页面

    html 复制代码
    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org">
    <head>
        <title>Please Log In</title>
    </head>
    <body>
    <h1>Please Log In</h1>
    <form th:action="@{/login}" method="post">
        <div>
            <input type="text" name="username" placeholder="Username"/>
        </div>
        <div>
            <input type="password" name="password" placeholder="Password"/>
        </div>
        <input type="submit" value="Log in" />
    </form>
    </body>
    </html>
  2. 编写LoginController

    java 复制代码
    @Controller
    public class LoginController {
        @GetMapping("/login")
        public String login(){
            return "login" ;
        }
    }
  3. 配置SpringSecurity

    java 复制代码
    http.formLogin(form -> form
        .loginPage("/login")
        .permitAll()
    )

自定义AuthenticationManager

  1. 方式一 Publish AuthenticationManager

    java 复制代码
    @EnableWebSecurity
    public class SecurityConfig {
       @Bean
       public AuthenticationManager authenticationManager(
               UserDetailsService userDetailsService,
               PasswordEncoder passwordEncoder) {
          DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
          authenticationProvider.setUserDetailsService(userDetailsService);
          authenticationProvider.setPasswordEncoder(passwordEncoder);
          //
          ProviderManager providerManager = new ProviderManager(authenticationProvider);
          providerManager.setEraseCredentialsAfterAuthentication(false);
          //
          return providerManager;
       }
    }
  2. 方式二 Configure global AuthenticationManagerBuilder

    java 复制代码
    @EnableWebSecurity
    public class SecurityConfig {
    
       @Autowired
       public void configure(AuthenticationManagerBuilder builder) {
     	builder.eraseCredentials(false);
       }
    }

Controller 自定义登录方法

  1. 配置登录

    java 复制代码
     http.authorizeHttpRequests(authorize -> authorize
           .requestMatchers(HttpMethod.POST,"/user/login").permitAll()
           .anyRequest().authenticated()
       )
  2. 编写登录方法

    java 复制代码
     @PostMapping("/login")
     public Authentication login(@RequestBody LoginRequest loginRequest, HttpServletRequest request, HttpServletResponse response){
         //
         SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder.getContextHolderStrategy();
         //
         UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated(
                 loginRequest.username(), loginRequest.password());
         Authentication authentication = authenticationManager.authenticate(token);
         //
         SecurityContext context = securityContextHolderStrategy.createEmptyContext();
         context.setAuthentication(authentication);
         securityContextHolderStrategy.setContext(context);
         securityContextRepository.saveContext(context, request, response);
         return authentication ;
     }
  3. 注意如果启用了formLogin则Controller中的login地址不能是/login, 否则登录会被UsernamePasswordAuthenticationFilter拦截

相关推荐
2301_810746312 分钟前
CKA冲刺40天笔记 - day24 Kubernetes Clusterrole 和 Clusterrole Binding
笔记·容器·kubernetes
阿在在13 分钟前
Spring 系列(二):加载 BeanDefinition 的几种方式
java·后端·spring
stars-he25 分钟前
FPGA学习笔记-图书馆存包柜,乒乓球游戏电路设计
笔记·学习·fpga开发
1***357742 分钟前
spring loC&DI 详解
java·spring·rpc
阿在在42 分钟前
Spring 系列(一):用三条主线理解 Spring:BeanDefinition、生命周期与 AOP
spring
独自破碎E43 分钟前
介绍一下Spring AI框架
java·人工智能·spring
Gary Studio43 分钟前
simulink simscape(机器人方向)学习笔记
笔记·学习
Zeku1 小时前
20260111 - Linux驱动学习笔记:异步通知
笔记·stm32·freertos·linux驱动开发·linux应用开发
sin22011 小时前
Spring事务管理(SpringBoot)
java·spring boot·spring
C***11501 小时前
Spring TransactionTemplate 深入解析与高级用法
java·数据库·spring