看完這篇,SpringSecurity就算入門了

看完這篇,SpringSecurity就算入門了

1.SpringSecurity是什麼?能幹嘛?

Spring Security 是一個安全框架,能夠爲 Spring企業應用系統提供聲明式的安全訪問控制。 主要用來做訪問權限管理

Spring Security 基於 Servlet 過濾器、 IoC和AOP , 爲 Web 請求和方法調用提供身份確認和授權處理,避免了代碼耦合,減少了大量重複代碼工作

它的兩大功能? 認證和授權

  • 認證:識別並構建用戶對象,如:根據請求中的username,獲取登錄用戶的詳細信息,判斷用戶狀態,緩存用戶對象到請求上下文等。(主要是登錄註冊部分)
  • 授權:判斷用戶能否訪問當前請求,如:識別請求url,根據用戶、權限和資源(url)的對應關係,判斷用戶能否訪問當前請求url。(主要是權限管理)

知道了它是什麼了,那麼接下來我們就看看怎麼用?

2.代碼解讀

首先我們這個是解耦的,基於javaConfig的開發模式,所以可以直接建一個Config類

2.1 SecurityConfig 初體驗

大致隨便看一個模板,拿來體驗體驗,不要求看懂,後面我們來細講

//AOP切面編程,加個config就可以實現功能,不用改變代碼
//WebSecurityConfigurerAdapter 自定義Security策略
//EnableWebSecurity   開啓WebSecurity模式,@Enablexxxxx開啓某個功能
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    //鏈式編程
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //首頁所有人可以訪問,功能頁只有對應有權限的人才能訪問
        //請求授權的規則
        http.authorizeRequests().antMatchers("/").permitAll()
                                .antMatchers("/level1/**").hasRole("vip1")
                                .antMatchers("/level2/**").hasRole("vip2")
                                .antMatchers("/level3/**").hasRole("vip3");

        //沒有權限默認會到登錄頁,需要開啓登錄頁面,定製登錄頁
        //可以直接把表單的提交地址改爲Controller裏面去主頁的路徑
        //loginProcessingUrl對應表單請求的路徑,但是要求默認傳值的name爲username,password
        //可以利用.usernameParameter("user").passwordParameter("pwd")改默認的參數name值
        http.formLogin().loginPage("/toLogin").loginProcessingUrl("/login");

        //開啓註銷功能
        //logoutUrl 你要去哪裏註銷
//        http.logout().logoutSuccessUrl("/");

        //防止網站工具,post ,登陸失敗可能的原因,但是我沒降級用的 Springsecurity5 沒問題
        http.csrf().disable();
        http.logout().logoutSuccessUrl("/");

        //開啓記住我的功能 cookie默認2周,自定義接收前端記住我的參數
        http.rememberMe().rememberMeParameter("remember");
    }
    //認證,springboot.2.1.x,可以使用
    //密碼編碼:passwordEncoder
    //在Spring Security 5.0+ 新增了加密方法
    //AuthenticationManagerBuilder  自定義認證策略
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //這些數據正常應該從數據庫裏讀
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("admin").password(new BCryptPasswordEncoder().encode("123"))
                .roles("vip2","vip3").and().withUser("root").password(new BCryptPasswordEncoder().encode("123"))
                .roles("vip1","vip2","vip3").and()
                .withUser("youke").password(new BCryptPasswordEncoder().encode("123")).roles("vip1")
        ;
    }
}

2.2 起步依賴

首先我們想要使用就必要引入的依賴

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

當然如果是整合前端模板Themeleaf的話,還要引入兩個依賴

        <!--thymeleaf模板-->
        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf-spring5</artifactId>
        </dependency>
               <!--SpringSecurity+thymeleaf-->
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity5</artifactId>
            <version>3.0.4.RELEASE</version>
        </dependency>

2.3 兩大方法之授權

帶有http的參數是授權方法

@EnableWebSecurity    //開啓Security支持
public class SpringConfig extends WebSecurityConfigurerAdapter {

    @Override     //必須重寫的方法,一個配置參數的方法
    protected void configure(HttpSecurity http) throws Exception{

    }
}
//這個是寫在上面configure方法裏面的
//首頁所有人可以訪問,功能頁只有對應有權限的人才能訪問
//請求授權的規則
http.authorizeRequests().antMatchers("/").permitAll()       //允許所有人可以訪問/路勁
                        .antMatchers("/level1/**").hasRole("vip1")   //要擁有vip1權限的人才能訪問/level1/**的路徑,下面照着解讀
                        .antMatchers("/level2/**").hasRole("vip2")
                        .antMatchers("/level3/**").hasRole("vip3");

沒有權限默認會到登錄頁,需要開啓登錄頁面,定製登錄頁

http.formLogin() 加了這個就會讓沒有認證的人去登錄頁面

//loginPage  去哪個頁面登錄  
//loginProcessingUrl對應登錄表單請求的路徑,但是要求前臺默認傳值的name爲username,password
//如果不想寫loginProcessingUrl,那麼去哪個頁面登錄的那個表單action地址就要和這個loginPage路勁一樣
//可以利用.usernameParameter("user").passwordParameter("pwd")改默認的參數username和password值
http.formLogin().loginPage("/toLogin").loginProcessingUrl("/login");
http.logout();  //開啓註銷

http.logout() 開啓註銷 ,他會自動刪除cookie那些

值得注意的是登錄登出,你開啓的他的基本方法如果沒有配置,就會走他自帶的登錄登出頁面

http.logout() .logouturl("/logout") ; 這裏就定義了去哪個頁面註銷

http.logout() .logoutSuccessUrl("/index"); 這裏是自動註銷瞭然後跳轉去index頁面

開啓記住我

 //開啓記住我的功能 cookie默認2周,自定義接收前端記住我的參數
 http.rememberMe().rememberMeParameter("remember");

2.4 兩大方法之認證

帶有AuthenticationMannagerBuilder的是認證

共同點都是,密碼要加密 Security5.0後都要加密,而且爲了安全最好加密密碼 BCryptPasswordEncoder或者MD5之內的加密方式

2.4.1 認證之固定假值用戶
    //認證,springboot.2.1.x,可以使用
    //密碼編碼:passwordEncoder
    //在Spring Security 5.0+ 新增了加密方法
    //AuthenticationManagerBuilder  自定義認證策略
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //這些數據正常應該從數據庫裏讀
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("admin").password(new BCryptPasswordEncoder().encode("123"))
                .roles("vip2","vip3").and().withUser("root").password(new BCryptPasswordEncoder().encode("123"))
                .roles("vip1","vip2","vip3").and()
                .withUser("youke").password(new BCryptPasswordEncoder().encode("123")).roles("vip1")
        ;
    }

上面withuser就是認證user這些人的信息,並且給予權限roles

2.4.2 認證之數據庫查詢

當然如果是數據庫的話我們就需要再自己建一個類UserDetailService接口重寫loadUserByUsername方法,固定寫法,模板拿來即用

@Component
public class CustomUserDetailsService implements UserDetailsService {
    @Autowired
    private UserInfoService userInfoService;
    
    /**
     * 需新建配置類註冊一個指定的加密方式Bean,或在下一步Security配置類中註冊指定
     */
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 通過用戶名從數據庫獲取用戶信息,這裏就是調用數據庫的接口
        UserInfo userInfo = userInfoService.getUserInfo(username);
        if (userInfo == null) {
            throw new UsernameNotFoundException("用戶不存在");
        }

        // 得到用戶角色
        String role = userInfo.getRole();

        // 角色集合
        List<GrantedAuthority> authorities = new ArrayList<>();
        // 角色必須以`ROLE_`開頭,數據庫中沒有,則在這裏加
        authorities.add(new SimpleGrantedAuthority("ROLE_" + role));

        return new User(
                userInfo.getUsername(),
             // 因爲數據庫是明文,所以這裏需加密密碼
                passwordEncoder.encode(userInfo.getPassword()),
                authorities
        );
    }
}

然後得到了用戶信息之後就可以接軌上面的configure方法了

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private MyUserDatailService userDatailService;   //固定注入這個

    /**
     * 指定加密方式
     */
    @Bean
    public PasswordEncoder passwordEncoder(){
        // 使用BCrypt加密密碼
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth
                 // 從數據庫讀取的用戶進行身份認證
                .userDetailsService(userDatailService)   //用戶信息
                .passwordEncoder(passwordEncoder());     //用戶加密的密碼
    }
}

上面設置完後,重新啓動,在登錄頁面就可以輸入數據庫中的用戶名/密碼了。

隨着登錄的用戶,伴隨的權限管理

3. 前臺細節

thymeleaf爲例

<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">

sec:authorize="!isAuthenticated() 如果還沒有登錄,就顯示登錄按鈕

sec:authorize="isAuthenticated() 如果登錄了顯示用戶名和註銷

sec:authentication=“name” 顯示用戶名

sec:authentication=“principal.authorities” 顯示用戶權限

                <!--未登錄-->
                <div sec:authorize="!isAuthenticated()">
                    <a class="item" th:href="@{/toLogin}">
                        <i class="address card icon"></i> 登錄
                    </a>
                </div>

                <!--已登錄   顯示用戶名和註銷-->
                <div sec:authorize="isAuthenticated()">
                    <a class="item">
                        用戶名:<span sec:authentication="name"></span>
                       角色:<span sec:authentication="principal.authorities"></span>
                    </a>
                    <a class="item" th:href="@{/logout}">
                        <i class="sign- out icon"></i> 註銷
                    </a>
                </div>

那如何實現模塊div之間對應權限的隱藏呢?

sec:authorize=“hasRole(‘vip1’)” 可以根據擁有此權限的用戶才顯示

<!--            菜單根據用戶權限動態實現-->
            <div class="column" sec:authorize="hasRole('vip1')">
                <div class="ui raised segment">
                    <div class="ui">
                        <div class="content">
                            <h5 class="content">Level 1</h5>
                            <hr>
                            <div><a th:href="@{/level1/1}"><i class="bullhorn icon"></i> Level-1-1</a></div>
                            <div><a th:href="@{/level1/2}"><i class="bullhorn icon"></i> Level-1-2</a></div>
                            <div><a th:href="@{/level1/3}"><i class="bullhorn icon"></i> Level-1-3</a></div>
                        </div>
                    </div>
                </div>
            </div>

4.安全小細節

之前說了認證的時候要加密密碼爲了安全,這裏還值得一題的是csrf防腳本攻擊

//防止網站工具,post ,登陸失敗可能的原因,但是我沒降級用的 Springsecurity5 沒問題
http.csrf().disable();

看到了這裏差不多都理解了基本用法,接下來就是做一個小案例了,

提醒一下如果是前後端分離的項目,需要注意跨域問題

一個簡單的跨域,可以之間在授權裏面做

 @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 允許跨域訪問
        http.cors();
    }

在這裏插入圖片描述

這樣就可以實現跨域了

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章