banner
RustyNail

RustyNail

coder. 【blog】https://rustynail.me 【nostr】wss://ts.relays.world/ wss://relays.world/nostr

將 spring Security 集成到 SpringBoot 專案中

spring security 是一個用於權限驗證和資源權限管理的庫。簡單地記錄一下,spring security 集成到 spring boot

專案中的過程。

WebSecurityConfiguration#

主要是一個WebSecurityConfiguration

@Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
        		.userDetailsService(getUserDetailsService())
                .passwordEncoder(new PasswordEncoder() {
                    @Override
                    public String encode(CharSequence rawPassword) {
                        return rawPassword.toString();
                    }

                    @Override
                    public boolean matches(CharSequence rawPassword, String encodedPassword) {
                        return rawPassword.toString().equals(encodedPassword);
                    }
                });
    }
  • 繼承WebSecurityConfigurerAdapter,然後重寫這個configure方法,

可以設置使用者的來源: userDetailsService(UserDetailsService uds) ,UserDetailsService 決定了使用者怎麼來的。

比如:通過使用者名稱從資料庫查詢

@Bean
    public UserDetailsService getUserDetailsService(){
        return username -> {
            SysUser user = userRepository.getSysUserByUsername(username);
            if (user != null){
                return user;
            }else {
                throw new UsernameNotFoundException("no such user name.");
            }
        };
   }
  • 可以設定密碼的驗證機制
.passwordEncoder(new PasswordEncoder() {
      @Override
    public String encode(CharSequence rawPassword) {
     	return rawPassword.toString();
  	}

    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {
      return rawPassword.toString().equals(encodedPassword);
	}
});

可以設置密碼的加密和匹配方式

對請求進行權限控制#

提供了如 csrf 等功能,

  • csrf
  • antMatchers
  • formLogin
  • logout

等,對這些可以進一步設置

  • disable() 如 csrf
  • permitAll() 不需要權限
  • authenticated() 需要權限

等。

例子:

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf()
                .and()
                .authorizeRequests()
                .antMatchers("/api/*")
                    .authenticated()
                .antMatchers("/")
                    .authenticated()
                .and()
                .formLogin()
                    .loginPage("/login/page")
                    .defaultSuccessUrl("/out")
                    .loginProcessingUrl("/login")
                    .failureUrl("/e")
                    .permitAll()
                .and()
                .logout()
                    .logoutUrl("/logout")
                    .logoutSuccessUrl("/out")
                .permitAll();

        CsrfFilter csrfFilter = new CsrfFilter();
        http.addFilterAfter(csrfFilter,CsrfFilter.class);

    }
載入中......
此文章數據所有權由區塊鏈加密技術和智能合約保障僅歸創作者所有。