In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
Most people do not understand the knowledge points of this "RestTemplate how to pass HTTP Basic Auth authentication" article, so the editor summarizes the following contents, detailed contents, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "RestTemplate how to pass HTTP Basic Auth authentication" article.
I. explanation of the principle of HttpBasic authentication
First, HttpBasic mode requires the transmitted username and password to be encrypted using Base64 mode. If the user name is "admin" and the password is "admin", the string "admin:admin" is encrypted using the Base64 encoding algorithm. The encryption result may be: YWtaW46YWRtaW4=.
Then, in the Http request, authorization is used as a HTTP request header Header name, and "Basic YWtaW46YWRtaW4=" is sent to the server as the value of Header. (note that Basic+ spaces + encrypted strings are used here)
When the server receives such a request, it reaches the BasicAuthenticationFilter filter, extracts the header value of "authorization" and decodes it using the same algorithm used to verify the user's identity, Base64.
The decoding result matches the username and password of the login authentication, and if the match is successful, you can continue the subsequent access of the filter.
Second, HTTP Basic Auth server implementation
If you want to build your own server, how do you add Basic Auth authentication for Spring Boot services? Please refer to my other article: "Http Basic Auth login authentication mode of Spring Security series".
Of course, we don't have to build the server ourselves, and we can introduce a website that provides free online RESTful interface service: httpbin.com. This website provides us with the interface of Basic Auth certification testing service. If we just want to learn RestTemplate, we can just use the services provided by this website.
Browser access address: http://www.httpbin.org/#/Auth/get_basic_auth__user___passwd_
This interface service is implemented through OpenAPI (swagger), so it can be tested online. So you can test it through the page operation first, and then start to learn how to use RestTemplate to access the server interface.
Third, the request header carries authentication information.
The user name and password of Basic Auth authentication are included in the HTTP request header. For more information, please see the code notes below:
@ SpringBootTestclass BasicAuthTests {@ Resource private RestTemplate restTemplate; @ Test void testBasicAuth () {/ / the user name and password on the url is required by the test interface of the httpbin website. / / the real business does not need to reflect the basic auth user name and password on the url String url = "http://www.httpbin.org/basic-auth/admin/adminpwd";" / / carry Basic authentication information in the request header (here is how the actual Basic authentication passes user name and password) HttpHeaders headers = new HttpHeaders (); headers.set ("authorization", "Basic" + Base64.getEncoder () .encodeToString ("admin:adminpwd" .getBytes () / / send request HttpEntity ans = restTemplate .exchange (url, HttpMethod.GET, / / GET request new HttpEntity (null, headers), / / join headers String.class); / / body response data reception type System.out.println (ans);}}
The successful execution of the test case shows that RestTemplate correctly carries the Basic authentication information and gets the normal response result.
IV. The interceptor carries authentication information
Although the code in the third section implements the function, it is not good enough. Because every time we send a HTTP request, we need to assemble the HttpHeaders information, which is not good, resulting in a lot of code redundancy. Is there a way to add Http Basic authentication information to all RestTemplate requests API at once? The answer is: add an interceptor when RestTemplate Bean initialization, and add Basic authentication information uniformly in the way of interceptor.
The following code is read with comments. If you don't understand it, you need to refer to it:
Detailed lecture on RestTemplate part 2-switching of multiple underlying HTTP client class libraries
@ Configurationpublic class ContextConfig {@ Bean ("OKHttp3") public RestTemplate OKHttp3RestTemplate () {RestTemplate restTemplate = new RestTemplate (getClientHttpRequestFactory ()); / / add interceptor restTemplate.getInterceptors () .add (getCustomInterceptor ()); return restTemplate } / / implement an interceptor: use the interceptor to add Basic Auth authentication username password information private ClientHttpRequestInterceptor getCustomInterceptor () {ClientHttpRequestInterceptor interceptor = (httpRequest, bytes, execution)-> {httpRequest.getHeaders () .set ("authorization") to each HTTP request "Basic" + Base64.getEncoder () .encodeToString ("admin:adminpwd" .getBytes ()) Return execution.execute (httpRequest, bytes);}; return interceptor;} / / this code is the content of "Section 3-switching of the underlying HTTP client" private ClientHttpRequestFactory getClientHttpRequestFactory () {int timeout = 1000000; OkHttp3ClientHttpRequestFactory clientHttpRequestFactory = new OkHttp3ClientHttpRequestFactory (); clientHttpRequestFactory.setConnectTimeout (timeout); return clientHttpRequestFactory;}}
After the interceptor is added during RestTemplate Bean initialization, the code in the third section can omit the assembly process of the HttpHeaders Basic Auth request header carrying information. Send the request, and the result is the same as in the third section.
V. further simplification
The interceptor is used in the above approach, but we still encapsulate the HTTP headers request header information ourselves. A further simplification is that Spring RestTemplate has provided us with a packaged Basic Auth interceptor that we can use directly without having to implement the interceptor ourselves.
The following method is to use RestTemplateBuilder when RestTemplate Bean is instantiated, with basicAuthentication. So the interceptor is not needed here (the actual underlying code implementation is still the interceptor, but there is no need to specify the interceptor at the api level).
Send the request, and the result is the same as in the third section.
The above is about the content of this article on "how RestTemplate passes HTTP Basic Auth certification". I believe we all have a certain understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please pay attention to the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.