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

相关推荐
黄暄1 分钟前
初识计算机网络。计算机网络基本概念,分类,性能指标
笔记·学习·计算机网络·考研
WarPigs13 分钟前
Unity光照笔记
笔记·unity·游戏引擎
亚林瓜子1 小时前
AWS Elastic Beanstalk控制台部署Spring极简工程
java·spring·云计算·aws·eb
Alice-YUE1 小时前
【HTML5学习笔记1】html标签(上)
前端·笔记·学习·html·html5
Alice-YUE1 小时前
【HTML5学习笔记2】html标签(下)
前端·笔记·html·html5
jerry6091 小时前
LLM笔记(五)概率论
人工智能·笔记·学习·概率论
烧火大爷2 小时前
现代计算机图形学Games101入门笔记(十四)
笔记
亚林瓜子2 小时前
Spring集成Redis中禁用主机名DNS检测
redis·spring·ssh
xiao--xin3 小时前
计算机网络笔记(二十七)——4.9多协议标签交换MPLS
网络·笔记·计算机网络·mpls
Ivy烎3 小时前
【嵌入式笔记】Modbus TCP
笔记·tcp/ip·嵌入式·modbus tcp