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拦截

相关推荐
lpfasd12312 分钟前
《乌合之众》精读笔记
笔记
码界奇点13 分钟前
基于Spring Boot和Vue.js的视频点播管理系统设计与实现
java·vue.js·spring boot·后端·spring·毕业设计·源代码管理
爱吃山竹的大肚肚14 分钟前
MySQL 支持的各类索引
java·数据库·sql·mysql·spring·spring cloud
高老庄小呆子18 分钟前
SpringBoot3.5.4 引入Knife4j的官方start包
spring
廋到被风吹走19 分钟前
【Spring】Spring Boot详细介绍
java·spring boot·spring
会思考的猴子23 分钟前
UE5 笔记二 GameplayAbilitySystem Dash(冲刺)
笔记·ue5
复业思维2024010844 分钟前
STM32学习和实践笔记(45):SPI-FLASH实验
笔记·stm32·学习
zore_c1 小时前
【C语言】排序算法——快速排序详解(含多种变式)!!!
c语言·数据结构·笔记·算法·排序算法·深度优先·推荐算法
梵得儿SHI1 小时前
SpringCloud 核心组件精讲:Spring Cloud Gateway 网关实战-路由配置 + 过滤器开发 + 限流鉴权(附场景配置模板)
java·spring·spring cloud·gateway·搭建基础网关·现静态/动态路由配置·全局/局部过滤器
客梦1 小时前
数据结构--哈希表
数据结构·笔记