springsecurity-自定义登录页面和自定义认证

springsecurity是默认对所有请求都要认证的,并且是有默认的认证页面的。但很多时候,页面是需要我们自己的页面,还有某些请求我们希望是不认证的,直接放行。而springsecurity也提供了方式让我们做到,如下:

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
    }

    protected void configure(HttpSecurity http) throws Exception {

        http.formLogin()
                .loginPage("/login.html") //设置我们自己的登录页面的路径
                .loginProcessingUrl("/user/login") //设置表单提交到的路径,这个路径必须和表单的一致,因为一致,springsecurity才处理
                .defaultSuccessUrl("/user/index") //校验或认证成功后跳转的路径,也就是这个是真正的controller接口的路径
            .and().authorizeRequests().antMatchers("/user/index").permitAll()  //允许指定的路径 不需要不认证;这个固定的写法
            .anyRequest().authenticated() //所有的请求都需要认证,除了上面指定过不需要认证的除外
            .and().csrf().disable(); //关闭csrf功能
    }

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder(){

        return new BCryptPasswordEncoder();
    }
}

  对自定义页面和认证权限的配置在configure(HttpSecurity http)里设置,注释也在那了

原文地址:https://www.cnblogs.com/ibcdwx/p/14366338.html