【Spring Boot】Spring Security开发笔记

Spring Security是一个功能强大且高度可定制的身份验证和访问控制框架。本文将记录Spring Security相关开发笔记及简单的Spring Security应用

首先导入相关依赖

        <!--Spring Security依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

         <!--thymeleaf Spring Security依赖-->
       <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity5</artifactId>
            <version>3.0.4.RELEASE</version>
        </dependency>

配置继承自WebSecurityConfigurerAdapter的配置类,并重写

  protected void configure(HttpSecurity http):                             用于授权

  protected void configure(AuthenticationManagerBuilder auth):用于认证

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        //配置授权的页面请求
        //.antMatchers("/page1/**")配置所需授权的访问请求
        //.hasRole()来配置访问请求所需的角色,如vip1

        http.authorizeRequests().antMatchers("/*").permitAll()
                .antMatchers("/page1/**").hasRole("vip1")
                .antMatchers("/page2/**").hasRole("vip2")
                .antMatchers("/page3/**").hasRole("vip3");

        //配置被阻止访问后,跳转到登录界面,和登陆界面自定义的请求
        http.formLogin().loginProcessingUrl("/login");

        //开启记住密码功能
        http.rememberMe();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //配置认证,这里从内存读取
        auth.inMemoryAuthentication()

                //设置密码加密方式
                .passwordEncoder(new BCryptPasswordEncoder())

                //添加用户
                .withUser("root")
                .password(new BCryptPasswordEncoder().encode("123456"))
                .roles("vip1","vip2","vip3")

                //多个用户使用.and()连接
                .and()
                .withUser("admin")
                .password(new BCryptPasswordEncoder().encode("123456"))
                .roles("vip1");
    }
}

 下面大致的看一下源码

	/**
	 * Override this method to configure the {@link HttpSecurity}. Typically subclasses
	 * should not invoke this method by calling super as it may override their
	 * configuration. The default configuration is:
	 *
	 *
	 * http.authorizeRequests().anyRequest().authenticated().and().formLogin().and().httpBasic();
	 * 
	 *
	 * Any endpoint that requires defense against common vulnerabilities can be specified
	 * here, including public ones. See {@link HttpSecurity#authorizeRequests} and the
	 * `permitAll()` authorization rule for more details on public endpoints.
	 * @param http the {@link HttpSecurity} to modify
	 * @throws Exception if an error occurs
	 */
	protected void configure(HttpSecurity http) throws Exception {
		this.logger.debug("Using default configure(HttpSecurity). "
				+ "If subclassed this will potentially override subclass configure(HttpSecurity).");
		http.authorizeRequests((requests) -> requests.anyRequest().authenticated());
		http.formLogin();
		http.httpBasic();
	}

从  protected void configure(HttpSecurity http)源码注释中可以看出,如下为默认配置

 http.authorizeRequests().anyRequest().authenticated().and().formLogin().and().httpBasic();

进入.authorizeRequests()源码,spring已经将模板写在了注释中,按照其提示编写即可

 需要注意的是antMatchers是有顺序的

在antMatchers的注释中也提到了antMatchers的编写格式, 使用/**或**作为通用匹配用于匹配任何请求,像/aaa/**的格式会匹配/aaa、/aaa/和任何子目录,例如/aaa/bbb/ccc

 通过http.formLogin()实现拦截后跳转到登录界面,loginProcessingUrl("/login")实现跳转到自定义登陆界面的请求。同样错误页面也可自定义,请求为/login?error

如使用Thymeleaf模板引擎开发,可添加以下命名空间,引入thymeleaf-extras-springsecurity4

xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4"

可在Thymeleaf中通过sec调用相关函数

sec:authorize="isAuthenticated()"

猜你喜欢

转载自blog.csdn.net/yscjhghngh/article/details/122640612