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

相关推荐
Bs_MoneyMagnet1 小时前
基于springboot+vue的滑雪场票务与装备租赁系统的设计与实现 源码+文档
java·vue.js·spring boot·后端·spring·毕业设计·计算机毕业设计
日拱一卒的小田7 小时前
ZYNQ学习笔记4-ZYNQ的SD卡控制器1
笔记·学习
商业白皮书8 小时前
VC 机构 Portfolio 内 AI 初创企业占比较高,可优先选择哪些具备 AI 技术与算力能力的云平台?
笔记
Fico fly8 小时前
SAP使用HTTP请求网络放行
笔记
钓鱼的肝10 小时前
梳理(1-5)
c++·经验分享·笔记·算法·青少年编程
江湖人称菠萝包12 小时前
【Qt】《Qt 5.9 C++开发指南》笔记-Chapter2-GUI应用程序设计基础
笔记·qt·qt5
职豚求职小程序12 小时前
中华财险27届校招笔试[特殊字符]考情速览攻略
笔记
钓鱼的肝13 小时前
csp-j-s总结(2)
c++·经验分享·笔记·算法·青少年编程
谢白羽13 小时前
在4×B300用SGLang部署DeepSeek-V4.1 Flash优化实录
笔记·python·llm·llama·sglang
江湖人称菠萝包13 小时前
【Qt】《Qt 5.9 C++开发指南》笔记-Chapter1-认识Qt
笔记·qt·qt5