Spring Security(结合源码)----Spring Boot 相关配置与使用

第一步:加入security启动器依赖:

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

第二步:创建security的配置类(重点):

package com.kuang.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

//aop:横切,不需要修改源代码,相同的还有拦截器等
@EnableWebSecurity   //spring托管
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
    
    //链式编程
    @Override
    protected void configure(HttpSecurity http) throws Exception {
    
    
        http.authorizeRequests()
                .antMatchers("/").permitAll()           //所有人可以访问
                .antMatchers("/level1/**").hasRole("vip1")//"vip1"角色才能访问
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");
            //没有权限则默认会到登录页面  为什么会进入login页面  --看源码>约定大于配置
            //loginPage()指定登录界面是哪一个
            //loginProcessingUrl() 指定处理登录请求的,也就是form 提交的地址,这里是"/login"
            //passwordParameter("password") 指定表单中name属性为password的为密码,如果name就是password了我们就不用写了,他源码默认了
             //usernameParameter("username");   指定表单中name属性为username的为密码 ,如果name就是username了我们就不用写了,他源码默认了
        http.formLogin().loginPage("/toLogin").loginProcessingUrl("/login").passwordParameter("password").usernameParameter("username");
        //http.csrf().disable();//关闭csrf功能.登出失败可能的原因
        http.logout().logoutSuccessUrl("/");//logoutSuccessUrl()设置注销成功跳转的页面
        http.rememberMe().rememberMeParameter("rememeber");//开启记住我功能,cookie实现,
        // rememberMeParameter("rememeber")接收前端name为remember的来成为我们的remember功能
    }
    //认证,
    //密码编译,否则会报500,服务器异常错误
    //加入加密编码
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    
    
        auth.inMemoryAuthentication() //内存中认证,数据库认证则为jdbcAuthentication()
          .passwordEncoder(new BCryptPasswordEncoder())
         .withUser("min").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2")  //添加用户权限,用户名为min,密码为123456,身份角色有vip1/2
         .and()
         .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
         .and()
         .withUser("person").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");

    }
}


特别说明:

  1. 继承的WebSecurityConfigurerAdapter不要导错包了,否则会缺失方法
  2. 关于security配置中的方法都是链式编程的思想(简单上手)
  3. 使用到了AOP的知识,不需要修改源代码,相同的还有拦截器等
  4. configure(HttpSecurity http)该重写方法是依靠url地址来识别的
  5. 500服务器异常:在给用户密码的时候记得使用加密编码,否则高一点的Security会报500异常,这也是为了安全着想,否则反编译过来看到源码就危险了!
  6. 403权限不够异常
  7. http.formLogin()中体现了spring的约定大于配置,如,没有角色认证的用户在请求到权限网页时会自动跳转到login页面.看源码,有说明!在这里插入图片描述
  8. 登录与注销的跳转页面应为:/toLogin与/logout,在http.logout()中的源码有说明在这里插入图片描述
	/**
	 * Provides logout support. This is automatically applied when using
	 * {@link WebSecurityConfigurerAdapter}. The default is that accessing the URL
	 * "/logout" will log the user out by invalidating the HTTP Session, cleaning up any
	 * {@link #rememberMe()} authentication that was configured, clearing the
	 * {@link SecurityContextHolder}, and then redirect to "/login?success".
	 *
	 * <h2>Example Custom Configuration</h2>
	 *
	 * The following customization to log out when the URL "/custom-logout" is invoked.
	 * Log out will remove the cookie named "remove", not invalidate the HttpSession,
	 * clear the SecurityContextHolder, and upon completion redirect to "/logout-success".
	 *
	 * <pre>
	 * &#064;Configuration
	 * &#064;EnableWebSecurity
	 * public class LogoutSecurityConfig extends WebSecurityConfigurerAdapter {
	 *
	 * 	&#064;Override
	 * 	protected void configure(HttpSecurity http) throws Exception {
	 * 		http.authorizeRequests().antMatchers(&quot;/**&quot;).hasRole(&quot;USER&quot;).and().formLogin()
	 * 				.and()
	 * 				// sample logout customization
	 * 				.logout().deleteCookies(&quot;remove&quot;).invalidateHttpSession(false)
	 * 				.logoutUrl(&quot;/custom-logout&quot;).logoutSuccessUrl(&quot;/logout-success&quot;);
	 * 	}
	 *
	 * 	&#064;Override
	 * 	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
	 * 		auth.inMemoryAuthentication().withUser(&quot;user&quot;).password(&quot;password&quot;).roles(&quot;USER&quot;);
	 * 	}
	 * }
	 * </pre>
	 * @return the {@link LogoutConfigurer} for further customizations
	 * @throws Exception
	 */
	public LogoutConfigurer<HttpSecurity> logout() throws Exception {
    
    
		return getOrApply(new LogoutConfigurer<>());
	}




重点_怎么让security接管我们的登录页,几个总结出来的知识点!(源码)

      //没有权限则默认会到登录页面  为什么会进入login页面  --看源码>约定大于配置
      //loginPage()指定登录界面是哪一个
      //loginProcessingUrl() 指定处理登录请求的,也就是form 提交的地址,这里是"/login"
  http.formLogin().loginPage("/toLogin").loginProcessingUrl("/login");

重点理解这几个方法的作用!!!
loginPage()只是指定登录界面是哪一个.可以由controller来指定跳转我们自己写的登录页!
loginProcessingUrl(),这个是指定登录请求的,也就是登录页的form提交的地址它接管,识别用户名,密码.
当它接管的表单提交后,若成功登录,他会自己找到templates下的index.html页面,若没有,则会找你的controller的请求地址为"/"的控制器来跳转!

在这里插入图片描述
表单中的nane="username"和name="password"最好命名好为约定的就行密码那个最好不要为:name=“pwd”),不然在security的配置类中需要再使用passwordParameter()和usernameParameter()来接管指定的用户名密码,
在这里插入图片描述
我们默认为上图命名,就不用写这俩个方法啦(passwordParameter()和usernameParameter()).源码奉上
在这里插入图片描述

 http.rememberMe().rememberMeParameter("rememeber");//开启记住我功能,cookie实现,
        // rememberMeParameter("rememeber")接收前端name为remember的来成为我们的remember功能

rememberMeParameter()同理

最后:

 <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity5</artifactId>
            <version>3.0.4.RELEASE</version>
        </dependency>

注销404页面解决!:
SpringBoot+SpringSecurity注销时报错404的两种解决方法
总结结束!

猜你喜欢

转载自blog.csdn.net/CSDN13822805069/article/details/122954256
今日推荐