• 01.Spring Security初识,表单认证


    初识spring security

        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.security</groupId>
                <artifactId>spring-security-config</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.security</groupId>
                <artifactId>spring-security-web</artifactId>
            </dependency>
        </dependencies>
    
    @RestController
    @SpringBootApplication
    public class SecProApplication {
        @GetMapping("/")
        public String hello(){
            return "";
        }
        public static void main(String[] args){
            SpringApplication.run(SecProApplication.class);
        }
    }
    

    访问http://localhost:8080/ 输入默认用户名:user,密码为控制台上的Using generated security password就可以访问页面

    使用自定义密码

    application.properties中配置

    spring.security.user.name=fly
    spring.security.user.password=123456
    

    表单验证

    @EnableWebSecurity
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests()
                    .anyRequest().authenticated()
                    .and()
                    .formLogin().loginPage("/myLogin.html")//自定义登陆页,同时系统会用/myLogin.html注册一个POST路由,用于接收post请求
                    .permitAll()//使用登陆页允许全部
                    .and()
                    .csrf().disable();
        }
    }
    
     <form action="/myLogin.html" method="post">
            username:<input type="text" name="username"><hr>
            password:<input type="password" name="password"><hr>
            <input type="submit">
    </form>
    

    登陆成功返回json信息

    @EnableWebSecurity
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests()
                    .anyRequest().authenticated()
                    .and()
                    .formLogin().loginPage("/myLogin.html")//自定义登陆页,同时系统会用/myLogin.html注册一个POST路由,用于接收post请求
                    .loginProcessingUrl("/login")
                    .permitAll()
                    .successHandler(new AuthenticationSuccessHandler() {
                        @Override
                        public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
                            httpServletResponse.setContentType("application/json;charset=UTF-8");
                            httpServletResponse.getWriter().write("{"error_code":"0","message":"欢迎登陆"}");
                        }
                    })
                    .failureHandler(new AuthenticationFailureHandler() {
                        @Override
                        public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
                            httpServletResponse.setContentType("application/json;charset=UTF-8");
                            httpServletResponse.getWriter().write("{"error_code":"401","name":""+e.getClass()+"","message":""+e.getMessage()+""}");
                        }
                    })
                    .and()
                    .csrf().disable();
        }
    }
    
       <div>
            username:<input id="username" type="text" name="username"><hr>
            password:<input id="password" type="password" name="password"><hr>
            <button onclick="submit()">submit</button>
        </div>
        <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
        <script>
            function submit(){
                var username = $('#username').val();
                var password = $('#password').val();
                $.post("/login",{username:username,password:password},function (res) {
                    if (res.error_code=='0'){
                        window.location.href="http://localhost:8080/index"
                    }
                })
            }
        </script>
    

    内存用户存储

    @Configuration
    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.inMemoryAuthentication()
                    .passwordEncoder(new BCryptPasswordEncoder())
                    .withUser("fly")
                    .password(new BCryptPasswordEncoder().encode("123123"))
                    .authorities("ROLE_USER")
                    .and()
                    .withUser("lisi")
                    .password(new BCryptPasswordEncoder().encode("lisi123"))
                    .authorities("ROLE_USER")
            ;
        }
    }
    
    
  • 相关阅读:
    两步验证杀手锏:Java 接入 Google 身份验证器实战
    涨姿势:Spring Boot 2.x 启动全过程源码分析
    Spring Cloud 升级最新 Finchley 版本,踩了所有的坑!
    Spring Boot 2.x 启动全过程源码分析(上)入口类剖析
    推荐:7 月份值得一看的 Java 技术干货!
    屌炸天,Oracle 发布了一个全栈虚拟机 GraalVM,支持 Python!
    Spring Boot 核心配置文件 bootstrap & application 详解。
    出场率比较高的一道多线程安全面试题
    凉凉了,Eureka 2.x 停止维护,Spring Cloud 何去何从?
    读写Excel
  • 原文地址:https://www.cnblogs.com/fly-book/p/12221344.html
Copyright © 2020-2023  润新知