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")
        ;
    }
}

原文地址:https://www.cnblogs.com/fly-book/p/12221344.html