天天看點

SpringSecurity(安全架構)使用者認證和授權

以下為源碼部分,通過源碼學習

@EnableWebSecurity 
     public class FormLoginSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
     protected void configure(HttpSecurity http) throws Exception {
           http.authorizeRequests().antMatchers("/**").hasRole("USER").and().formLogin()
     *              .usernameParameter("username") // default is username
     *              .passwordParameter("password") // default is password
     *              .loginPage("/authentication/login") // default is /login with an HTTP get
     *              .failureUrl("/authentication/login?failed") // default is /login?error
     *              .loginProcessingUrl("/authentication/login/process"); // default is /login
     *                                                                      // with an HTTP
     *                                                                      // post
        }

     @Override
      protected void configure(AuthenticationManagerBuilder auth) throws Exception {
          auth.inMemoryAuthentication().withUser("user").password("password").roles("USER");
    }
}      

1.權限(為某些檔案設定權限)

//鍊式程式設計
    //授權
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 首頁所有人都可以通路,功能也隻有對應有權限的人才能通路到
        // 請求授權的規則
        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");

        // 沒有被權限默允許的使用者會跳到登入頁面
        // /login頁面
        http.formLogin()
                .usernameParameter("username")
                .passwordParameter("password")
                .loginPage("/toLogin")
                .loginProcessingUrl("/login");

        //登出,開啟了登出功能,跳到首頁
        http.logout().logoutSuccessUrl("/");

        // 防止網站工具:get,post
        http.csrf().disable();//關閉csrf功能,登入失敗肯定存在的原因

        //開啟記住我功能: cookie,預設儲存兩周,自定義接收前端的參數
        http.rememberMe().rememberMeParameter("remember");


    }      

所設定頁面均不可通路,需要通過使用者認證并且登入後即可通路

2.認證(認證的使用者才有資格登入系統)

// 認證,springboot 2.1.x 可以直接使用,使用者認證,認證後的使用者可以登入系統
    // 密碼編碼: PasswordEncoder    加密     new BCryptPasswordEncoder()即為設定加密
    // 在spring Secutiry 5.0+ 新增了很多加密方法
    //    and()作為連接配接使用
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        //這些資料正常應該中資料庫中讀
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("whx").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3")
                .and()
                .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
                .and()
                .withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
    }      

通過使用者認證确定什麼使用者可以通路什麼頁面

首先讓配置檔案繼承 WebSecurityConfigurerAdapter,然後通過@@EnableWebSecurity 開啟WebSecurity模式。然後通過自動構造方法找到所需方法。

完整配置檔案如下:

package nuc.ss.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  // 開啟WebSecurity模式
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");

        // 沒有被權限默允許的使用者會跳到登入頁面
        // /login頁面
        http.formLogin()
                .usernameParameter("username")
                .passwordParameter("password")
                .loginPage("/toLogin")
                .loginProcessingUrl("/login");

        //登出,開啟了登出功能,跳到首頁
        http.logout().logoutSuccessUrl("/");

        // 防止網站工具:get,post
        http.csrf().disable();//關閉csrf功能,登入失敗肯定存在的原因

        //開啟記住我功能: cookie,預設儲存兩周,自定義接收前端的參數
        http.rememberMe().rememberMeParameter("remember");


    }




    // 認證,springboot 2.1.x 可以直接使用,使用者認證,認證後的使用者可以登入系統
    // 密碼編碼: PasswordEncoder    加密     new BCryptPasswordEncoder()即為設定加密
    // 在spring Secutiry 5.0+ 新增了很多加密方法
    //    and()作為連接配接使用
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        //這些資料正常應該中資料庫中讀
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("whx").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3")
                .and()
                .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
                .and()
                .withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
    }


}      

使用者認證如果需要從資料庫中取資料的話則将使用者認證的代碼通過資料庫的方式寫入;