SpringBoot integrated experience Getting Started with Spring Security

I. Introduction

Spring SecurityAnd Apache Shiroall security framework that provides authentication and authorization for Java applications.

Difference between the two
  1. Spring Security: the magnitude of the security framework
  2. Apache Shiro: middleweight Security Framework

Authentication and authorization privileges on shiro may refer to small series of another article: SpringBoot Shiro integration to achieve dynamic load permissions

https://blog.csdn.net/qq_38225558/article/details/101616759

Two, SpringBoot integrated experience Getting Started with Spring Security

Basic environment: springboot 2.1.8

1, rely on the introduction Spring Security

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

2, a new test access controller

@RestController
public class IndexController {
    @GetMapping("/index")
    public String index() {
        return "Hello World ~";
    }
}

3, run the project visit http://127.0.0.1:8080/index

Warm Tips : Without any configuration, the default user name given by Spring Security userpassword is the project up and running when a string of randomly generated string that will be printed in the console, as shown below:
Here Insert Picture Description
When we visit index home page, the system will jump to the default login authentication login page

Here Insert Picture Description
After successful authentication will jump to our index page
Here Insert Picture Description

Three, Spring Security user password configuration

In addition to the above Spring Security user without any default configuration given userpassword with the start of the project to generate a random string, we may also be configured in the following manner

1, springboot configuration file is

spring:
  security:
    user:
      name: admin  # 用户名
      password: 123456  # 密码

2, java code is arranged in memory

New Security core configuration class inheritanceWebSecurityConfigurerAdapter

@Configuration
@EnableWebSecurity // 启用Spring Security的Web安全支持
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 将用户设置在内存中
     * @param auth
     * @throws Exception
     */
    @Autowired
    public void config(AuthenticationManagerBuilder auth) throws Exception {
        // 在内存中配置用户,配置多个用户调用`and()`方法
        auth.inMemoryAuthentication()
                .passwordEncoder(passwordEncoder()) // 指定加密方式
                .withUser("admin").password(passwordEncoder().encode("123456")).roles("ADMIN")
                .and()
                .withUser("test").password(passwordEncoder().encode("123456")).roles("USER");
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        // BCryptPasswordEncoder:Spring Security 提供的加密工具,可快速实现加密加盐
        return new BCryptPasswordEncoder();
    }

}

3, to obtain user account and password information from the database

This way is the way we normally used in the project, leaving behind this article say

Four, Spring Security to intercept the login process and ignored

I believe there are comments relevant code is easy to understand

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 登录处理
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 开启登录配置
        http.authorizeRequests()
                // 标识访问 `/index` 这个接口,需要具备`ADMIN`角色
                .antMatchers("/index").hasRole("ADMIN")
                // 允许匿名的url - 可理解为放行接口 - 多个接口使用,分割
                .antMatchers("/", "/home").permitAll()
                // 其余所有请求都需要认证
                .anyRequest().authenticated()
                .and()
                // 设置登录认证页面
                .formLogin().loginPage("/login")
                // 登录成功后的处理接口 - 方式①
                .loginProcessingUrl("/home")
                // 自定义登陆用户名和密码属性名,默认为 username和password
                .usernameParameter("username")
                .passwordParameter("password")
                // 登录成功后的处理器  - 方式②
//                .successHandler((req, resp, authentication) -> {
//                    resp.setContentType("application/json;charset=utf-8");
//                    PrintWriter out = resp.getWriter();
//                    out.write("登录成功...");
//                    out.flush();
//                })
                // 配置登录失败的回调
                .failureHandler((req, resp, exception) -> {
                    resp.setContentType("application/json;charset=utf-8");
                    PrintWriter out = resp.getWriter();
                    out.write("登录失败...");
                    out.flush();
                })
                .permitAll()//和表单登录相关的接口统统都直接通过
                .and()
                .logout().logoutUrl("/logout")
                // 配置注销成功的回调
                .logoutSuccessHandler((req, resp, authentication) -> {
                    resp.setContentType("application/json;charset=utf-8");
                    PrintWriter out = resp.getWriter();
                    out.write("注销成功...");
                    out.flush();
                })
                .permitAll()
                .and()
                .httpBasic()
                .and()
                // 关闭CSRF跨域
                .csrf().disable();

    }

    /**
     * 忽略拦截
     * @param web
     * @throws Exception
     */
    @Override
    public void configure(WebSecurity web) throws Exception {
        // 设置拦截忽略url - 会直接过滤该url - 将不会经过Spring Security过滤器链
        web.ignoring().antMatchers("/getUserInfo");
        // 设置拦截忽略文件夹,可以对静态资源放行
        web.ignoring().antMatchers("/css/**", "/js/**");
    }

}

V. Summary

  1. Spring Security project introduced dependence
  2. Custom Security core configuration class inheritanceWebSecurityConfigurerAdapter
  3. Configuring account password
  4. Login processing
  5. Ignore interception
Case demo source code

https://gitee.com/zhengqingya/java-workspace

Guess you like

Origin www.cnblogs.com/zhengqing/p/11612654.html