Spring Boot整合Security系列步骤及问题排查(二)—— 自定义登录页面

1.完善WebSecurityConfig:

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 加密解密官方实现
     *
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        // 默认/表单登录方式
//        http.httpBasic()
        http.formLogin()
                // 自定义登录页面
                .loginPage("/login.html")
                .loginProcessingUrl("/authentication/form")
                .and()
                // 对任何请求授权
                .authorizeRequests()
                // 匹配页面授权所有权限
                .antMatchers("/swagger-ui.html", "/login.html").permitAll()
                // 任何请求
                .anyRequest()
                // 都需要被认证
                .authenticated()
                .and()
                // 请求伪造防护功能关闭
                .csrf().disable();

    }

}

2.resources下新建resources文件夹及页面login.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Security自定义登录页</title>
</head>
<body>
<h2>Security自定义登录页</h2>
<form action="authentication/form" method="post">
    <div><label>用户名</label><input type="text" name="username" placeholder="请输入用户名"/></div>
    <div><label>&nbsp;&nbsp;&nbsp;&nbsp;</label><input type="password" name="password" placeholder="请输入密码"/></div>
    <div><input type="submit" value="登录"/></div>
</form>
</body>
</html>

默认url为/xx/xx...,如果配置了项目名则改为xx/xx...

3.启动访问要访问的接口,输入用户名密码

问题排查:

SpringBoot2 Security 静态资源访问404问题

/**
 * 解决Spring Boot2 swagger-ui.html及静态资源 404问题
 * @author zhaohaibin
 */
@Configuration
public class WebMvcConfigurer extends WebMvcConfigurerAdapter {

    /**
     * 防止@EnableMvc把默认的静态资源路径覆盖了,手动设置的方式
     *
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        /**
         * SpringBoot自动配置本身并不会把/swagger-ui.html
         * 这个路径映射到对应的目录META-INF/resources/下面
         * 采用WebMvcConfigurerAdapter将swagger的静态文件进行发布;
         */
//        registry.addResourceHandler("swagger-ui.html")
        registry.addResourceHandler("/**")
                .addResourceLocations("classpath:/META-INF/resources/")
                .addResourceLocations("classpath:/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
        //将所有/static/** 访问都映射到classpath:/static/ 目录下
        registry.addResourceHandler("/static/**").addResourceLocations(ResourceUtils.CLASSPATH_URL_PREFIX + "/static/");
        super.addResourceHandlers(registry);
    }

}
发布了81 篇原创文章 · 获赞 12 · 访问量 17万+

猜你喜欢

转载自blog.csdn.net/u012382791/article/details/105262704