精通Spring Boot——第十六篇:初探Spring Security,使用Http Basic認證

說明

本文以及接下來有關spring security 的文章, 基於Spring Boot 2.1.0 RELEASE , Spring Security 5.1.2RELEASEjava

簡單介紹Spring Security

Spring Security是當今很是流行的,基於Spring提供了一套Web安全性的完整框架。用於對用戶進行認證(Authentication)和受權(Authorization)。在用戶認證方面,Spring Security 支持主流的驗證方式,包括,HttpBasic認證,Http表單認證,Http摘要認證,OpenId以及LDAP(輕量目錄訪問協議:Lightweight Directory Access Protocol)等。在用戶受權方面,Spring Security 提供了基於角色的訪問控制和訪問控制列表(Access Control List,ACL),能夠對應用中的領域對象進行細粒度的控制。 本文將經過介紹如何在Spring Boot項目中使用Spring Security保護應用,咱們先討論如何自定義用戶的認證邏輯,經過Spring Security 提供的UserDetailService,User對象,密碼加密PasswordEncoder來初步認識Spring Security。git

初探:用httpBasic認證

Spring Security 5.X 和Spring Security 4.X 在Http Basic認證有些不一樣,在Spring Security4.X中,咱們想要使用Http Basic認證只須要以下代碼:github

/**
 * @author developlee
 * @since 2018/11/17 22:43
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/index").permitAll()
                .anyRequest().authenticated()
                .and().httpBasic();
        super.configure(http);
    }
}

Spring Security 是默認開啓了 Http Basic認證的,若是想要關閉能夠設置 security.basic.enabled: false (Spring Security5.X中已棄用) 而Spring Security 5.X的實現則有些不一樣,若是按照以上代碼,則訪問連接時,會跳轉至Spring Security 提供的默認登錄頁。接下來看看Spring Security5.X的實現,文檔是這樣描述的: 也就是說,要將BasicAuthenticationFilter添加到Spring Security的filterChain中。let's do it! 咱們先繼承BasicAuthenticationEntryPoint,重寫commence方法。spring

/**
 * @author developlee
 * @since 2018/11/25 11:36
 */
@Component
public class MyBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        response.addHeader("WWW-Authenticate", "Basic realm=" + getRealmName());
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        PrintWriter printWriter = new PrintWriter(response.getOutputStream());
        printWriter.write("Http Status 401: " + authException.getLocalizedMessage());
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        setRealmName("developlee");
        super.afterPropertiesSet();
    }
}

接下來看看如何配置安全

/**
 * @author developlee
 * @since 2018/11/17 22:43
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private MyBasicAuthenticationEntryPoint authenticationEntryPoint;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/login").permitAll()
                .anyRequest().authenticated()
                .and().httpBasic()
                .authenticationEntryPoint(authenticationEntryPoint);
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("lensen").password(passwordEncoder().encode("123456")).authorities("ROLE_USER");
    }

    @Bean
    protected PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

LoginController.java的代碼app

/**
 * @author developlee
 * @since 2018/11/17 22:02
 */
@RestController
public class LoginController {
    @GetMapping("/hello")
    public String hello() {
        return "hello";
    }
}

啓動項目,訪問咱們寫好的連接地址。http://loalhost:8080/hello 框架

至此,Spring Security 5.X使用Http Basic 登錄的實例便已經完成了。 本文的全部代碼我已經放在個人github.com上,感謝您的觀看,若是有什麼錯誤的地方,還請指出,共同探討!ide

相關文章
相關標籤/搜索