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

相关推荐
程序员Xu1 小时前
【LeetCode热题100道笔记】二叉搜索树中第 K 小的元素
笔记·算法·leetcode
DKPT1 小时前
JVM中如何调优新生代和老生代?
java·jvm·笔记·学习·spring
喂完待续3 小时前
【序列晋升】29 Spring Cloud Task 微服务架构下的轻量级任务调度框架
java·spring·spring cloud·云原生·架构·big data·序列晋升
我真的是大笨蛋4 小时前
K8S-基础架构
笔记·云原生·容器·kubernetes
Volunteer Technology5 小时前
三高项目-缓存设计
java·spring·缓存·高并发·高可用·高数据量
程序员Xu7 小时前
【LeetCode热题100道笔记】腐烂的橘子
笔记·算法·leetcode
IT19957 小时前
Wireshark笔记-DHCP两步交互流程与数据解析
网络·笔记·wireshark
ST.J7 小时前
SQL与数据库笔记
数据库·笔记·sql
肥肠可耐的西西公主7 小时前
后端(JDBC)学习笔记(CLASS 1):基础篇(一)
笔记·学习
zzywxc7878 小时前
AI在金融、医疗、教育、制造业等领域的落地案例(含代码、流程图、Prompt示例与图表)
人工智能·spring·机器学习·金融·数据挖掘·prompt·流程图