zoukankan      html  css  js  c++  java
  • (二)spring Security 自定义登录页面与校验用户

    使用 Spring Boot 的快速创建项目功能,勾选上本篇博客需要的功能:web,security,thymeleaf ;


    配置 security

    /**
     * 对 security 的配置
     *
     * @author yiaz
     * @date 2019年3月18日14:04:55
     */
    @EnableWebSecurity
    public class WebSecurityConfig {
    
        /**
         * 创建 springSecurityFilterChain 拦截器
         *
         * @return
         */
        @Bean
        public WebMvcConfigurer webMvcConfigurer() {
            return new WebMvcConfigurer() {
            };
        }
    
        /**
         * 注册 springSecurityFilterChain 拦截器
         *
         * @return
         */
        @Bean
        public AbstractSecurityWebApplicationInitializer abstractSecurityWebApplicationInitializer() {
            return new AbstractSecurityWebApplicationInitializer() {
            };
        }
    
    
        /**
         * 配置用户名和密码和拥有的角色,此时只做硬编码,后面会改成数据库中动态获取
         *
         * @return
         * @throws Exception
         */
        @Bean
        public UserDetailsService userDetailsService() throws Exception {
            InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
            manager.createUser(User.withDefaultPasswordEncoder().username("user").password("password").roles("USER").build());
            return manager;
        }
    
    
        /**
         * 配置对哪些路径进行拦截,如果方法里面什么都不写,则不拦截任何路径;
         * <p>
         * 如果,使用 super.configure(http),父类的方法:
         * ((HttpSecurity)((HttpSecurity)((AuthorizedUrl)http.authorizeRequests().anyRequest()).authenticated().and()).formLogin().and()).httpBasic();
         * <p>
         * 我们自定义下拦截规则;
         *
         * @return
         */
        @Bean
        public WebSecurityConfigurerAdapter webSecurityConfigurerAdapter() {
            return new WebSecurityConfigurerAdapter() {
                @Override
                protected void configure(HttpSecurity http) throws Exception {
                    http
                            .authorizeRequests()
                            // 拦截所有请求,静态资源等特定请求需要放放行,在这里配置 
                                .anyRequest().authenticated()
                            .and()
                            .formLogin()
                            // 地址写的是 映射的路径
                                .loginPage("/login")
                                .permitAll()
                                // 第二个参数,如果不写成true,则默认登录成功以后,访问之前被拦截的页面,而非去我们规定的页面
                                .defaultSuccessUrl("/index.html", true)
                            .and()
                            .logout()
                                .logoutUrl("/logout")
                            .and()
                            // 关闭下 CSRF ,否则表单得不到提交,或者在表单里面添加一个 hidden 属性,提交csrf;
                            .csrf()
                                .disable()
                            .httpBasic();
    
                }
            };
        }
    }
    

    配置下 MVC

    上面配置的自定义登陆界面的地址映射,需要在下面 MVC 里面配置下:

    在这里插入图片描述

    @Configuration
    public class MvcConfig {
        @Bean
        public WebMvcConfigurerAdapter webMvcConfigurerAdapter() {
            return new WebMvcConfigurerAdapter() {
                @Override
                public void addViewControllers(ViewControllerRegistry registry) {
                    registry.addViewController("/login").setViewName("login");
                    registry.addViewController("/login.html").setViewName("login");             
                }
    		};
        }
    }
    
    

    自定义登录页面

    thymeleaf 文件夹下面新建一个 login.html :

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    首页<br>
    thymeleaf
    
    <!--自定义登录页面,如果想要用内存中的用户,想security,自己帮我们校验的话,则提交地址必须是 /login -->
    <form class="form-signin" method="post" action="/login">
        <h2 class="form-signin-heading">Please sign in</h2>
        <p>
            <label for="username" class="sr-only">Username</label>
            <!-- 这里的 username,password 也不能改动,因为security帮我们校验的时候,就是用它来接受参数的-->
            <input type="text" id="username" name="username" class="form-control" placeholder="Username" required=""
                   autofocus="">
        </p>
        <p>
            <label for="password" class="sr-only">Password</label>
            <input type="password" id="password" name="password" class="form-control" placeholder="Password" required="">
        </p>
        <!-- 本来官网上给出这个东西的,但是不知道,为啥不会获取到对应的值,因此在上面配置的时候,直接关闭 csrf  -->
        <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
        <button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
    </form>
    
    </body>
    </html>
    

    自定义一个登陆成功欢迎页面

    在静态文件夹 static 文件夹下面新建一个 index.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    首页<br>
    static
    </body>
    </html>
    

    上面我们配置了成功登陆,就将页面重定向到这里;


    效果图

    1. 访问任何 URL 都会被拦截,然后重定向我们规定的首页:

      在这里插入图片描述

    2. 登陆

      使用之前硬编码配置的用户名和密码登陆;

      在这里插入图片描述

    3. 登陆成功以后,页面会被重定向配置的欢迎页:

      在这里插入图片描述

    Spring Security 自定义登陆页面就是这么简单,可以参照官网文档 自己慢慢摸索;


    小结:

    如果你不想提交的表单的用户名和密码,必须是 username,password,则在我们的配置类中,自定义规则的里面进行更改下:

      @Bean
        public WebSecurityConfigurerAdapter webSecurityConfigurerAdapter() {
            return new WebSecurityConfigurerAdapter() {
                @Override
                protected void configure(HttpSecurity http) throws Exception {
                 	   ...
                            .formLogin()
                                .passwordParameter("你想要的密码name")
                                .usernameParameter("你想要的用户名name")
                            .and()
               		   ...
    	
                }
            };
        }
    
  • 相关阅读:
    格式化dataGridview里数据
    XtraGrid gridview基本用法
    winForm中如何控制listView的滚动条高手请进
    WinForm 和 Windows Service 通信 消息队列
    抽象工厂模式
    C#之访问控制修饰符
    JavaScript之变量
    Android之传感器(二)持续更新
    备忘录模式
    JavaScript之构造函数初了解
  • 原文地址:https://www.cnblogs.com/young-youth/p/11665576.html
Copyright © 2011-2022 走看看