SpringSecurity实现自定义登录页面

接着自定义用户名与密码后:https://blog.csdn.net/hjjjjjjj_/article/details/120235512

一、先创建登录页面




    
    登录页面


用户名:
密码:

二、配置类

注:一定要关闭csrf保护,否则无法进行认证 

设置点击登录后访问的路径只需要写个路径就可以了,内部的东西SpringSecurity会自动配好

认证登录后走/user/login路径,SpringSecurity内部会进行认证,认证成功后会自动跳转至指定成功后跳转的路径

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()    //自定义登录页面
                .loginPage("/login.html")    //登录页面设置
                .loginProcessingUrl("/user/login")   //点击登录后访问的路径
                .defaultSuccessUrl("/index").permitAll()   //登录成功后跳转路径,permitAll表示无条件进行访问
                .and().authorizeRequests()
                .mvcMatchers("/","/hello","/user/login").permitAll() //设置不需要认证可以直接访问的路径
                .anyRequest().authenticated()
                .and().csrf().disable();    //关闭csrf保护
    }

}

三、控制层

@RestController
public class loginController {

    @GetMapping("/hello")
    public String hello(){
        return "hello SpringSecurity";
    }

    //登录成功后的返回地址
    @GetMapping("/index")
    public String index(){
        return "登录成功";
    }
}

四、测试

当访问hello路径时不会被认证,可以直接访问

 当访问index路径时会被认证,自动重定向至自定义的登录页面

SpringSecurity实现自定义登录页面_第1张图片

 登录成功后访问

SpringSecurity实现自定义登录页面_第2张图片

你可能感兴趣的:(Spring,Security,java,spring)