SpringBoot集成Spring Security入門體驗

1、前言

Spring SecurityApache Shiro 都是安全框架,爲Java應用程序提供身份認證和受權。css

兩者區別
  1. Spring Security:量級安全框架
  2. Apache Shiro:量級安全框架

關於shiro的權限認證與受權可參考小編的另一篇文章 : SpringBoot集成Shiro 實現動態加載權限java

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

2、SpringBoot集成Spring Security入門體驗

基本環境 : springboot 2.1.8

一、引入Spring Security依賴

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

二、新建一個controller測試訪問

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

三、運行項目訪問 http://127.0.0.1:8080/index

舒適小提示:在不進行任何配置的狀況下,Spring Security 給出的默認用戶名爲user 密碼則是項目在啓動運行時隨機生成的一串字符串,會打印在控制檯,以下圖:
在這裏插入圖片描述
當咱們訪問index首頁的時候,系統會默認跳轉到login頁面進行登陸認證web

在這裏插入圖片描述
認證成功以後纔會跳轉到咱們的index頁面
在這裏插入圖片描述spring

3、Spring Security用戶密碼配置

除了上面Spring Security在不進行任何配置下默認給出的用戶user 密碼隨項目啓動生成隨機字符串,咱們還能夠經過如下方式配置數據庫

一、springboot配置文件中配置

spring:
  security:
    user:
      name: admin  # 用戶名
      password: 123456  # 密碼

二、java代碼在內存中配置

新建Security 核心配置類繼承WebSecurityConfigurerAdapter json

@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();
    }

}

三、從數據庫中獲取用戶帳號、密碼信息

這種方式也就是咱們項目中一般使用的方式,這個留到後面的文章再說跨域

4、Spring Security 登陸處理 與 忽略攔截

相關代碼都有註釋相信很容易理解安全

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

}

5、總結

  1. 項目引入Spring Security依賴
  2. 自定義Security核心配置類繼承WebSecurityConfigurerAdapter
  3. 帳號密碼配置
  4. 登陸處理
  5. 忽略攔截
案例demo源碼

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

相關文章
相關標籤/搜索