javascript
使用基本身份验证来保护Spring Boot REST API
這是我的Spring Boot Blog帖子系列的第三篇文章。 在第一篇文章中,我談到了我使用Spring Boot創(chuàng)建RESTFul Services的經(jīng)驗(yàn)。 然后我將樣本擴(kuò)展到
與Swagger文檔集成 。 在這篇文章中,我將在安全方面擴(kuò)展上述示例。
什么是API安全性
API安全性廣泛,具有許多不同的定義,含義和解決方案。 API安全性中的主要關(guān)鍵術(shù)語(yǔ)是授權(quán),身份驗(yàn)證,加密,聯(lián)合和委派。 但是,在這里我不會(huì)談?wù)撍鼈儭?
什么是認(rèn)證
身份驗(yàn)證用于可靠地確定最終用戶的身份,并根據(jù)正確標(biāo)識(shí)的用戶授予對(duì)資源的訪問(wèn)權(quán)限。
什么是基本身份驗(yàn)證
基本身份驗(yàn)證是對(duì)資源實(shí)施訪問(wèn)控制的最簡(jiǎn)單方法。 在此,HTTP用戶代理在發(fā)出請(qǐng)求時(shí)提供用戶名和密碼。 當(dāng)需要身份驗(yàn)證時(shí),包含用戶名和密碼的字符串由冒號(hào)分隔,并在發(fā)送到后端之前經(jīng)過(guò)Base64編碼。
如何調(diào)用基本身份驗(yàn)證受保護(hù)的API
選項(xiàng)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='選項(xiàng)2:使用網(wǎng)址:
curl -X GET -u username:password? http://localhost:8080/admin/hello/chandana好的,我們討論了一些基本的東西。 因此,讓我們來(lái)看一下如何使用Spring Security保護(hù)REST API。 您可以從我的GitHub存儲(chǔ)庫(kù)下載初始示例代碼(Swagger Spring Boot Project源代碼)
為了使用基本的auth安全性增強(qiáng)我們先前的示例,首先我將在pom文件中添加“ spring-boot-starter-security”和“ spring-boot-starter-tomcat”依賴項(xiàng)。
<!-- --><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批注對(duì)我們的配置類(lèi)進(jìn)行批注,并從WebSecurityConfigurerAdapter擴(kuò)展配置類(lèi)。 EnableWebSecurity批注將啟用Spring-Security Web安全支持。
@Configuration @EnableSwagger2 @EnableWebSecurity public class ApplicationConfig extends WebSecurityConfigurerAdapter {重寫(xiě)的configure(HttpSecurity)方法用于定義哪些URL路徑應(yīng)該受到保護(hù),哪些不應(yīng)該受到保護(hù)。 在我的示例中,不需要“ /”和“ / api”路徑進(jìn)行任何身份驗(yàn)證,并且任何其他路徑(例如:“ admin”)都應(yīng)使用基本身份驗(yàn)證進(jìn)行身份驗(yàn)證。
@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)建了一個(gè)內(nèi)存用戶存儲(chǔ),其中包含一個(gè)名為“ chandana”的用戶。 在那里,我為內(nèi)存中的用戶添加了用戶名,密碼和userole。
@Autowiredpublic void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {auth.inMemoryAuthentication().withUser("chandana").password("chandana").roles("USER");}除此之外,您還可以看到我已將自動(dòng)裝配的BasicAuthenticationPoint添加到我的配置類(lèi)中。 BasicAuthenticationEntryPoint類(lèi)的目的是將“ WWW-Authenticate”標(biāo)頭設(shè)置為響應(yīng)。 因此,Web瀏覽器將顯示一個(gè)對(duì)話框,用于基于基本身份驗(yàn)證機(jī)制(WWW-Authenticate標(biāo)頭)輸入用戶名和密碼
然后,您可以使用“ mvn spring-boot:run”運(yùn)行示例。 當(dāng)您訪問(wèn)“ localhost:8080 / api / hello / chandana”時(shí),調(diào)用api不需要基本身份驗(yàn)證。 但是,如果您嘗試訪問(wèn)“ localhost:8080 / admin / hello / chandana”,則需要提供基本的身份驗(yàn)證憑據(jù)才能訪問(wèn)資源。
AppConfig類(lèi):
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類(lèi):
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存儲(chǔ)庫(kù)下載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的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 环评如何网上备案(环评网上备案怎么办理)
- 下一篇: Spring Webflux – Kot