Spring Security login and logout configuration

1. Configure in the configuration class that inherits WebSecurityConfigurerAdapter

    public void configure(HttpSecurity httpSecurity) throws Exception {
    
    
        httpSecurity.formLogin()    /* 自定义自己编写的登录界面 */
                .loginPage("/login")   /* 登录页面设置 */
                .loginProcessingUrl("/user/login")  /* 登录访问路径 */
                .defaultSuccessUrl("/success").permitAll()    /* 登陆成功后跳转路径 */
                .and().authorizeRequests()  /* 指定哪些url可以访问,那些不能访问 */
                .antMatchers("/test/index","/user/login").permitAll()    /* 设置那些路径不需要认证可以访问 */
                .anyRequest().authenticated()   /* 所有请求都可以访问 */
                .and().csrf().disable();     /* 关闭csrf防护 */
        //用户注销
        httpSecurity.logout()
                .logoutUrl("/logout")   /* 注销访问路劲 */
                .logoutSuccessUrl("/test/index").permitAll();   /* 注销成功跳转路径 */
    }

2. Login interface and controller settings
Controller

@Controller
public class LoginController {
    
    
    @RequestMapping("/login")
    public String login(){
    
    
        return "login";
    }
    @RequestMapping("success")
    public String success(){
    
    
        return "success";
    }
}

@Controller
@RequestMapping("/test")
public class TestController {
    
    
    @RequestMapping("/index")
    public String index(){
    
    
        return "index";
    }

    @RequestMapping("/hello")
    @ResponseBody
    public String hello(@AuthenticationPrincipal UserDetails users){
    
        /* 认证之后通过UserDetails获取表单参数 */
        return "hello "+users.getUsername();
    }
}

Login interface: /login

<body>
    <h1>my login page</h1>
    <!-- action要与配置中的登录访问路径一致 -->
    <form action="/user/login" method="post">
        用户名:<input type="text" name="username"><br>
        密码:<input type="password" name="password"><br>
        <input type="submit" value="login">
    </form>
</body>

Successful login redirect page: /logout

<body>
    <h1>登入成功</h1>
    <a href="/logout">注销</a>
</body>

3. Operation effect
Insert picture description here

Guess you like

Origin blog.csdn.net/magicproblem/article/details/112599826