Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize HTTP Authentication in Spring Boot

2025-03-04 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article will explain in detail how to achieve HTTP authentication in Spring Boot, the content of the article is of high quality, so the editor shares it for you to do a reference. I hope you will have a certain understanding of the relevant knowledge after reading this article.

HttpBasic authentication has some limitations and security risks, so it is not often used in practical projects, but sometimes it is much more convenient to open HttpBasic authentication for testing convenience.

Today, let's have a brief talk with you about HttpBasic certification in Spring Security.

1. What is HttpBasic?

Http Basic authentication is a way of authentication between Web server and client, which is originally defined in HTTP1.0 specification (RFC 1945). Subsequent security information can be found in HTTP 1945 specification (RFC 2616) and HTTP authentication specification (RFC 2617).

The biggest advantage of HttpBasic is that it is very easy to use, there is no complex page interaction, it only needs to carry the corresponding information in the request header to authenticate successfully, and it is a kind of stateless login, that is, the user's login information will not be recorded in session.

The biggest problem with HttpBasic is security, because the username / password is simply encoded by Base64 and then transmitted, which can be easily sniffed by tools and expose user information.

Spring Security supports both basic HttpBasic authentication and Http digest authentication. Http digest authentication improves information security management on the basis of HttpBasic authentication, but the code complexity also increases a lot, so Http digest authentication is not widely used.

Here, I would like to share these two authentication methods in Spring Security.

2.HttpBasic certification

Let's first look at the implementation, and then analyze its authentication process.

First create a Spring Boot project and introduce Web and Spring Security dependencies, as follows:

Next, create a test interface:

@ RestController

Public class HelloController {

@ GetMapping ("/ hello")

Public String hello () {

Return "hello"

}

}

Turn on HttpBasic authentication again:

@ Configuration

Public class SecurityConfig extends WebSecurityConfigurerAdapter {

@ Override

Protected void configure (HttpSecurity http) throws Exception {

Http.authorizeRequests ()

.anyRequest () .authenticated ()

.and ()

.httpBasic ()

}

}

Finally, configure the basic user information in application.properties, as follows:

Spring.security.user.password=123

Spring.security.user.name=javaboy

After the configuration is completed, start the project and visit the / hello interface, and there will be a pop-up box in the browser. Let's enter the user name / password information:

At this point, we look at the request response header, as follows:

You can see that the browser responds to 401 with a WWW-Authenticate response header, which is used to describe the authentication form. If we are using HttpBasic authentication, the default response header format is shown in the figure.

Next, we enter the user name and password, click Sign In to log in, and after the login is successful, we can successfully access the / hello interface.

Let's review the second request, as follows:

You can see that in the request header, there is an extra Authorization field whose value is Basic amF2YWJveToxMjM=

AmF2YWJveToxMjM= is a string encoded by Base64. After decoding the string, we find that the result is as follows:

String x = new String (Base64.getDecoder () .decode ("amF2YWJveToxMjM="), "UTF-8")

The decoding results are as follows:

As you can see, this is our username password information. The username / password is passed only after a simple Base64 encoding, so this kind of authentication is dangerous.

Let's summarize the process of HttpBasic certification a little bit:

The browser makes a request to access the / hello interface.

The server returns 401, indicating that it is not authenticated. At the same time, the WWW-Authenticate field is carried in the response header to describe the authentication form.

After the browser receives the 401 response, a pop-up dialog box asks the user to enter the user name / password. After the user enters the user name / password, the browser will encode it with Base64, and then send it to the server.

The server decodes the information from the browser, verifies it, and responds to the client when there is no problem.

This is the general process.

3.Http Digest Certification

Http digest authentication is basically compatible with HttpBasic authentication, but it is much more complex, which is reflected not only in the code, but also in the request process.

The most important improvement of Http digest authentication is that it does not send plaintext passwords on the network. Its entire authentication process is as follows:

The browser makes a request to access the / hello interface.

The server returns 401, indicating that it is not authenticated, and the WWW-Authenticate field is carried in the response header to describe the authentication form. The difference is that this time, the server calculates a random string and returns the front end together to prevent replay attacks (the so-called replay attack means that someone sniffs your summary information and sends the summary as a password to the server over and over again. Add a random string that will change, and the generated summary information will change, so as to prevent replay attacks):

At the same time, the field returned by the server also has a qop that indicates the protection level, auth indicates that only authentication is performed, and auth-int indicates that the content needs to be verified.

Nonce is a random string generated by the server, which is a string encoded by Base64. After decoding, we find that it is composed of expiration time and key. In future requests, the nonce will be sent back to the server intact.

The client selects an algorithm and calculates a summary of the password and other data based on the algorithm, as follows:

As you can see, the client sends a lot of data to the server.

Nonce is a random string sent by the server.

Response is the generated summary information.

Nc indicates that replay attacks can be prevented at this time of the request.

Cnonce represents a random string that the client sends to the server.

According to the user name sent by the client, the server can query the user password, then calculate the summary information according to the user password, and then compare the summary information with the summary information sent by the client to confirm the identity of the user.

That's the whole process.

In a word, the original user password is replaced by the summary information. For the sake of security, the summary information will change according to the random string returned by the server. The server also calculates the summary information of the password according to the user password, and then compares it with the summary information sent from the client. If there is no problem, the user can be considered as successful in authentication. Of course, some expiration restrictions, replay attack prevention mechanism and so on are added on this basis.

Okay, so how do you do this in Spring Security code?

@ Configuration

Public class SecurityConfig extends WebSecurityConfigurerAdapter {

@ Override

Protected void configure (HttpSecurity http) throws Exception {

Http.authorizeRequests ()

.anyRequest () .authenticated ()

.and ()

Csrf ()

.disable ()

.promotionHandling ()

.authenticationEntryPoint (digestAuthenticationEntryPoint ())

.and ()

.addFilter (digestAuthenticationFilter ())

}

@ Bean

DigestAuthenticationEntryPoint digestAuthenticationEntryPoint () {

DigestAuthenticationEntryPoint entryPoint = new DigestAuthenticationEntryPoint ()

EntryPoint.setKey ("javaboy")

EntryPoint.setRealmName ("myrealm")

EntryPoint.setNonceValiditySeconds (1000)

Return entryPoint

}

@ Bean

DigestAuthenticationFilter digestAuthenticationFilter () {

DigestAuthenticationFilter filter = new DigestAuthenticationFilter ()

Filter.setAuthenticationEntryPoint (digestAuthenticationEntryPoint ())

Filter.setUserDetailsService (userDetailsService ())

Return filter

}

@ Override

@ Bean

Protected UserDetailsService userDetailsService () {

InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager ()

Manager.createUser (User.withUsername ("javaboy") .password ("123") .roles (" admin ") .build ()

Return manager

}

@ Bean

PasswordEncoder passwordEncoder () {

Return NoOpPasswordEncoder.getInstance ()

}

}

Configuration is nothing more than two aspects, on the one hand, the generation of random strings on the server side, and on the other hand, the verification of client summary information.

First, provide an example of DigestAuthenticationEntryPoint and configure some parameters generated by random numbers on the server, such as the validity period of nonce (how long it takes to change), the name of realm, and the key needed to generate nonce. The specific generation logic of nonce is in the DigestAuthenticationEntryPoint#commence method:

Public void commence (HttpServletRequest request, HttpServletResponse response

AuthenticationException authException) throws IOException {

HttpServletResponse httpResponse = response

Long expiryTime = System.currentTimeMillis () + (nonceValiditySeconds * 1000)

String signatureValue = DigestAuthUtils.md5Hex (expiryTime + ":" + key)

String nonceValue = expiryTime + ":" + signatureValue

String nonceValueBase64 = new String (Base64.getEncoder () .encode (nonceValue.getBytes ()

String authenticateHeader = "Digest realm=\" + realmName + "\", "

+ "qop=\" auth\ ", nonce=\"+ nonceValueBase64 +"\ ""

If (authException instanceof NonceExpiredException) {

AuthenticateHeader = authenticateHeader + ", stale=\" true\ ""

}

If (logger.isDebugEnabled ()) {

Logger.debug ("WWW-Authenticate header sent to user agent:"

+ authenticateHeader)

}

HttpResponse.addHeader ("WWW-Authenticate", authenticateHeader)

HttpResponse.sendError (HttpStatus.UNAUTHORIZED.value ()

HttpStatus.UNAUTHORIZED.getReasonPhrase ()

}

In this code, we first get the expiration time, then calculate the message digest together with the key, and then use the nonce and the message digest as value to calculate a Base64 encoded character, and then write the encoded character back to the front end.

Configure the DigestAuthenticationFilter filter, which is mainly used to process front-end requests. The source code of the filter is relatively long, so I won't post it here. A core idea is to get the summary information requested by the user from the front end, and the server also calculates a summary according to the information all the time, and then compares it according to the transmitted summary information, and then confirms the identity of the user.

After the configuration is completed, restart the server for testing.

The test effect is actually the same as HttpBasic authentication, all the changes, only behind the implementation has changed, the user experience is the same.

4. Summary

Although the effect of Http summary authentication is safer than HttpBasic, in fact, we can see that the security problems solved by the whole process are actually very limited. And the code is also a lot of trouble, so this kind of authentication is not widely popular.

As an understanding of Http certification friends, there are some interesting ideas that can inspire us to solve other problems, such as solutions to replay attacks. If we want to defend ourselves against replay attacks, we can refer to the implementation ideas here.

On how to achieve HTTP authentication in Spring Boot to share here, I hope that the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

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.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report