天天看點

RBAC權限---SpringBoot整合Security

引入SpringSecurity子產品

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

複制

加入這個依賴後表示所有的接口都是被保護的狀态,通路的時候被Security攔截。

RBAC權限---SpringBoot整合Security

在浏覽器輸入該請求路徑,會自重定向到Spring Security的登入頁。預設的使用者名是user,密碼請去IDEA的Consolse去找項目每次啟動時随機生成的字元串:

Using generated security password: 5a38aea2-81d0-485d-bf5c-12c73b0aad27

(複制passwor後的内容即可通路)

RBAC權限---SpringBoot整合Security

同時也支援在資料庫配置使用者名和密碼(正式項目一般處理方式)或在配置檔案配置使用者名密碼,本文使用的是yml配置,properties同理,如果不知道如何配置,請自行百度。配置後在Console中便不自動生成password

spring:
  security:
    user:
      name: Ltx
      password: 123456
      # roles可不配置
      roles: admin           

複制

配置HTTP攔截規則

配置接口放行規則

SecurityConfig.class

/**
 * @author Liutx
 * @date 2020/12/13 11:53
 * @Description
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 實際就是為了告訴Spring我的密碼不用加密
     */
    @Bean
    PasswordEncoder passwordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }

    /**
     * configure有三個重寫的方法,本方法是基于記憶體的配置使用者角色
     * 在Spring 5.0後需要對密碼進行加密
     */
    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("root").password("123456").roles("admin")
                .and()
                .withUser("Ltx").password("123456").roles("user");
    }

    /**
     * 配置HTTP請求規則
     * 什麼請求路徑需要什麼權限才能通路,
     * 登入接口,都可通路
     *
     * @param http
     * @throws Exception
     */
    @Override
     protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
                    @Override
                    public <O extends FilterSecurityInterceptor> O postProcess(O object) {
                        object.setAccessDecisionManager(customUrlDecisionManager);
                        object.setSecurityMetadataSource(customFilterInvocationSecurityMetadataSource);
                        return object;
                    }
                })
                .and()
                .logout()
                .logoutSuccessHandler((req, resp, authentication) -> {
                            resp.setContentType("application/json;charset=utf-8");
                            PrintWriter out = resp.getWriter();
                            out.write(new ObjectMapper().writeValueAsString(RespBean.ok("登出成功!")));
                            out.flush();
                            out.close();
                        }
                )
                .permitAll()
                .and()
                .csrf().disable().exceptionHandling()
                //沒有認證時,在這裡處理結果,不要重定向
                .authenticationEntryPoint((req, resp, authException) -> {
                            resp.setContentType("application/json;charset=utf-8");
                            resp.setStatus(401);
                            PrintWriter out = resp.getWriter();
                            RespBean respBean = RespBean.error("通路失敗!");
                            if (authException instanceof InsufficientAuthenticationException) {
                                respBean.setMsg("請求失敗,請聯系管理者!");
                            }
                            out.write(new ObjectMapper().writeValueAsString(respBean));
                            out.flush();
                            out.close();
                        }
                );
        http.addFilterAt(new ConcurrentSessionFilter(sessionRegistry(), event -> {
            HttpServletResponse resp = event.getResponse();
            resp.setContentType("application/json;charset=utf-8");
            resp.setStatus(401);
            PrintWriter out = resp.getWriter();
            out.write(new ObjectMapper().writeValueAsString(RespBean.error("您已在另一台裝置登入,本次登入已下線!")));
            out.flush();
            out.close();
        }), ConcurrentSessionFilter.class);
        http.addFilterAt(loginFilter(), UsernamePasswordAuthenticationFilter.class);
    }
}           

複制

使用postman測試,是以關閉CSRF攻擊,正式環境請開啟 記得要删掉super.configure(http); 不然會報錯IllegalStateException: Can't configure anyRequest after itself ObjectMapper類是Jackson庫的主要類。它提供一些功能将轉換成Java對象比對JSON結構,反之亦然。它使用JsonParser和JsonGenerator的執行個體實作JSON實際的讀/寫。

表單登入測試

RBAC權限---SpringBoot整合Security

使用post請求構造表單登入,SpringSecurity已做密碼脫敏,權限中預設使用"ROLE_?imageView2/2/w/1620"為字首。

表單登出測試

RBAC權限---SpringBoot整合Security

登出配置如上代碼,構造get請求即可。

使用資料庫的方式做登入認證

一、引入資料庫驅動、orm架構(MyBatis-Plus)
<dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

		<!-- 引入阿裡資料庫連接配接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.3</version>
        </dependency>
    
        <!--MyBatis-Plus-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.1</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
            <version>8.0.22</version>
        </dependency>           

複制

因為敲完這個demo,時間不是很充足,是以沒有更新文章,SpringBoot下與資料庫互動使用權限認證請去我的github去尋找源碼,思路根據江南一點雨(松哥)的權限認證思路而來。

項目源碼Git位址

松哥Github位址