javascript
使用基本身份验证来保护Spring Boot REST API
這是我的Spring Boot Blog帖子系列的第三篇文章。 在第一篇文章中,我談到了我使用Spring Boot創(chuàng)建RESTFul Services的經(jīng)驗。 然后我將樣本擴展到
與Swagger文檔集成 。 在這篇文章中,我將在安全方面擴展上述示例。
什么是API安全性
API安全性廣泛,具有許多不同的定義,含義和解決方案。 API安全性中的主要關(guān)鍵術(shù)語是授權(quán),身份驗證,加密,聯(lián)合和委派。 但是,在這里我不會談?wù)撍鼈儭?
什么是認證
身份驗證用于可靠地確定最終用戶的身份,并根據(jù)正確標(biāo)識的用戶授予對資源的訪問權(quán)限。
什么是基本身份驗證
基本身份驗證是對資源實施訪問控制的最簡單方法。 在此,HTTP用戶代理在發(fā)出請求時提供用戶名和密碼。 當(dāng)需要身份驗證時,包含用戶名和密碼的字符串由冒號分隔,并在發(fā)送到后端之前經(jīng)過Base64編碼。
如何調(diào)用基本身份驗證受保護的API
選項1:發(fā)送授權(quán)標(biāo)頭。 該值是base64編碼的username:password Ex:“授權(quán):基本Y2hhbmRhbmE6Y2hhbmRhbmE =”
curl -X GET http://localhost:8080/admin/hello/chandana -H 'authorization: Basic Y2hhbmRhbmE6Y2hhbmRhbmE='選項2:使用網(wǎng)址:
curl -X GET -u username:password? http://localhost:8080/admin/hello/chandana好的,我們討論了一些基本的東西。 因此,讓我們來看一下如何使用Spring Security保護REST API。 您可以從我的GitHub存儲庫下載初始示例代碼(Swagger Spring Boot Project源代碼)
為了使用基本的auth安全性增強我們先前的示例,首先我將在pom文件中添加“ spring-boot-starter-security”和“ spring-boot-starter-tomcat”依賴項。
<!-- --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency><dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>3.1.0</version></dependency>下一步是使用@EnableWebSecurity批注對我們的配置類進行批注,并從WebSecurityConfigurerAdapter擴展配置類。 EnableWebSecurity批注將啟用Spring-Security Web安全支持。
@Configuration @EnableSwagger2 @EnableWebSecurity public class ApplicationConfig extends WebSecurityConfigurerAdapter {重寫的configure(HttpSecurity)方法用于定義哪些URL路徑應(yīng)該受到保護,哪些不應(yīng)該受到保護。 在我的示例中,不需要“ /”和“ / api”路徑進行任何身份驗證,并且任何其他路徑(例如:“ admin”)都應(yīng)使用基本身份驗證進行身份驗證。
@Override protected void configure(HttpSecurity http) throws Exception {http.csrf().disable();http.authorizeRequests().antMatchers("/", "/api/**").permitAll().anyRequest().authenticated();http.httpBasic().authenticationEntryPoint(basicAuthenticationPoint); }在configureGlobal(AuthenticationManagerBuilder)方法中,我創(chuàng)建了一個內(nèi)存用戶存儲,其中包含一個名為“ chandana”的用戶。 在那里,我為內(nèi)存中的用戶添加了用戶名,密碼和userole。
@Autowiredpublic void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {auth.inMemoryAuthentication().withUser("chandana").password("chandana").roles("USER");}除此之外,您還可以看到我已將自動裝配的BasicAuthenticationPoint添加到我的配置類中。 BasicAuthenticationEntryPoint類的目的是將“ WWW-Authenticate”標(biāo)頭設(shè)置為響應(yīng)。 因此,Web瀏覽器將顯示一個對話框,用于基于基本身份驗證機制(WWW-Authenticate標(biāo)頭)輸入用戶名和密碼
然后,您可以使用“ mvn spring-boot:run”運行示例。 當(dāng)您訪問“ localhost:8080 / api / hello / chandana”時,調(diào)用api不需要基本身份驗證。 但是,如果您嘗試訪問“ localhost:8080 / admin / hello / chandana”,則需要提供基本的身份驗證憑據(jù)才能訪問資源。
AppConfig類:
package com.chandana.helloworld.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; 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 springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.service.Contact; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; @Configuration @EnableSwagger2 @EnableWebSecurity public class ApplicationConfig extends WebSecurityConfigurerAdapter { @Autowired private BasicAuthenticationPoint basicAuthenticationPoint; @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(getApiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.chandana.helloworld.controllers")) .paths(PathSelectors.any()) .build(); } @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable(); http.authorizeRequests().antMatchers("/", "/api/**").permitAll() .anyRequest().authenticated(); http.httpBasic().authenticationEntryPoint(basicAuthenticationPoint); } private ApiInfo getApiInfo() { Contact contact = new Contact("Chandana Napagoda", "http://blog.napagoda.com", "cnapagoda@gmail.com"); return new ApiInfoBuilder() .title("Example Api Title") .description("Example Api Definition") .version("1.0.0") .license("Apache 2.0") .licenseUrl("http://www.apache.org/licenses/LICENSE-2.0") .contact(contact) .build(); } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().withUser("chandana").password("chandana").roles("USER"); } }BasicAuthenticationEntryPoint類:
package com.chandana.helloworld.config; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint; import org.springframework.stereotype.Component; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @Component public class BasicAuthenticationPoint extends BasicAuthenticationEntryPoint { @Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authEx) throws IOException, ServletException { response.addHeader("WWW-Authenticate", "Basic realm=" +getRealmName()); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); PrintWriter writer = response.getWriter(); writer.println("HTTP Status 401 - " + authEx.getMessage()); } @Override public void afterPropertiesSet() throws Exception { setRealmName("Chandana"); super.afterPropertiesSet(); } }您也可以從我的GitHub存儲庫下載Spring Boot Basic Auth Project源代碼。
翻譯自: https://www.javacodegeeks.com/2017/10/secure-spring-boot-rest-api-using-basic-authentication.html
總結(jié)
以上是生活随笔為你收集整理的使用基本身份验证来保护Spring Boot REST API的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 环评如何网上备案(环评网上备案怎么办理)
- 下一篇: 微信安卓免费下载百度手机助手(微信安卓免