How to implement HTTP authentication in spring boot?

implement http authentication spring boot


HttpBasic Certification has certain limitations and security risks , So it's not used much in real projects , however , Sometimes for the convenience of testing , Turn on HttpBasic Certification can be a lot easier .

So I'd like to have a brief talk with you today Spring Security Medium HttpBasic authentication .

This article is about Spring Security The first series 29 piece , Reading the previous article will help you understand this article better :

  1. Dig a big hole ,Spring Security Open up !
  2. Brother song takes you to the door Spring Security, Don't ask me how to decrypt the password
  3. How to customize Spring Security Form login in
  4. Spring Security Separation of front and rear ends , Let's not do the page Jump ! All JSON Interaction
  5. Spring Security The authorization operation in is so simple
  6. Spring Security How to store user data in database ?
  7. Spring Security+Spring Data Jpa Combining the , Security management is only simpler !
  8. Spring Boot + Spring Security Achieve automatic login function
  9. Spring Boot automatic logon , How to control the security risk ?
  10. In the micro service project ,Spring Security Than Shiro Where is the strength ?
  11. SpringSecurity Two ways to customize authentication logic ( Advanced play )
  12. Spring Security How to quickly view login users in IP Address and other information ?
  13. Spring Security Automatically kick out the previous login user , One configuration is done !
  14. Spring Boot + Vue Front and rear end separation project , How to kick out the logged in user ?
  15. Spring Security Built in firewall ! You don't even know how secure your system is !
  16. What is a session fixation attack ?Spring Boot How to defend against session fixation attacks ?
  17. Cluster deployment ,Spring Security What to do with session share ?
  18. SongGe teaches you how to do it by hand SpringBoot In defense CSRF attack !so easy!
  19. Learn thoroughly if you want to learn !Spring Security in CSRF Defense source code parsing
  20. Spring Boot Two positions of password encryption in !
  21. Spring Security How to learn ? Why do we have to learn systematically ?
  22. Spring Security Two resource release strategies , Don't use it wrong !
  23. SongGe teaches you how to get started Spring Boot + CAS Single sign on
  24. Spring Boot The third solution to implement single sign on !
  25. Spring Boot+CAS Single sign on , How to connect database ?
  26. Spring Boot+CAS The default login page is ugly , What do I do ?
  27. use Swagger Test interface , How to carry in the request header Token?
  28. Spring Boot Summary of three cross domain scenarios in

1. What is? HttpBasic

Http Basic Certification is Web A way of authentication between the server and the client , Originally in HTTP1.0 standard (RFC 1945) In the definition of , Follow up information on security can be found in HTTP 1.1 standard (RFC 2616) and HTTP Certification specifications (RFC 2617) Find .

HttpBasic The biggest advantage is that it's very simple to use , No complex page interaction , Only need to carry the corresponding information in the request header to authenticate successfully , And it's a stateless login , That is to say session The user's login information is not recorded in .

HttpBasic The biggest problem is security , Because of the user name / The password is simply passed through Base64 After coding, the transmission begins , It's easy to be sniffed by tools , And then expose user information .

Spring Security China supports basic HttpBasic authentication , Also support Http Abstract authentication ,Http Authentication is in HttpBasic On the basis of certification , Improved information security management , But the code complexity has also increased a lot , therefore Http Authentication is not widely used .

here , SongGe will share with you Spring Security These two authentication methods in .

2.HttpBasic authentication

Let's first look at the implementation of , Then analyze its authentication process .

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

Next, create a test interface :

@RestController
public class HelloController {

@GetMapping("/hello")
public String hello() {

return "hello";
}
}

And open HttpBasic authentication :

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {

http.authorizeRequests()
.anyRequest().authenticated()
.and()
.httpBasic();
}
}

At last application.properties Configure basic user information in , as follows :

spring.security.user.password=123
spring.security.user.name=javaboy

When the configuration is complete , Start project , visit /hello Interface , 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 , The browser responded to 401, At the same time, he also carried a WWW-Authenticate Response head , This is used to describe the form of authentication , If we use HttpBasic authentication , The default response header format is shown in the figure .

Next, we enter the user name and password , Click on Sign In Log in , After successful login , You can successfully access /hello The interface .

We look at the second request , as follows :

You can see , In the request header , One more. Authorization Field , The value of this field is Basic amF2YWJveToxMjM=,

amF2YWJveToxMjM= It's a process Base64 The encoded string , We decode the string and find , give the result as follows :

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

The decoding results are as follows :

You can see , This is our user name and password information . user name / The password is simply Base64 After coding, it starts to pass , So , This kind of authentication is dangerous ️.

Let's sum up a little bit HttpBasic Certification process :

  1. Request from browser , Said to visit /hello Interface .
  2. Server return 401, Not certified . Also carry... In the response header WWW-Authenticate Field to describe the authentication form .
  3. Browser received 401 After responding , Pop-up dialog box , Ask the user to enter a user name / password , The user enters the user name / After the code , The browser will do it Base64 code , After coding , Send to server .
  4. The server decodes the information from the browser , And check , When it's ok , Respond to the client .

This is the general process .

3.Http Abstract authentication

Http Authentication and HttpBasic Authentication is basically compatible with , But it's a lot more complicated , This complexity is not just in the code , It's also reflected in the request process .

Http The most important improvement of authentication is that it will not send clear text password on the network . Its whole authentication process is like this :

  1. Request from browser , Said to visit /hello Interface .
  2. Server return 401, Not certified , Also carry... In the response header WWW-Authenticate Field to describe the authentication form . The difference is , This time the server-side accountant calculates a random string , Back to the front end together , This prevents replay attacks ( The so-called replay attack is someone sniffing your summary information , Take the digest as a password and send it to the server again and again , Add a random string that changes , The generated summary information will change , You can prevent replay attacks ), as follows :

meanwhile , There is another field returned by the server qop, Indicates the level of protection ,auth Means authentication only ;auth-int It means to check the content .

nonce Is a random string generated by the server , This is a process Base64 Encoded string , After decoding, we found that , It's made up of expiration time and key . In future requests nonce It will be sent back to the server as it is .

  1. The client selects an algorithm , According to this algorithm, we can calculate the digest of password and other data , as follows :

You can see , The client sends more data to the server .

  • nonce It is a random string sent by the server .
  • response Is the generated summary information .
  • nc At this time , Can prevent replay attacks .
  • cnonce Represents a random string sent by the client to the server .
  1. According to the user name sent by the client , You can find out the user password , Then according to the user password can calculate the summary information , Then compare the summary information with the summary information sent by the client , You can confirm the user's identity .

This is the whole process .

In a word , The original user password is replaced by the digest information , For the sake of safety , The summary information will change according to the random string returned by the server , The server according to the user password , Also calculate the digest information of the password , And then compare with the summary information from the client , No problem , Even if the user authentication is successful . Of course , On this basis, some expiration restrictions are added 、 Replay attack prevention mechanism, etc .

Okay , So this one is in Spring Security How to implement in the code ?

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {

http.authorizeRequests()
.anyRequest().authenticated()
.and()
.csrf()
.disable()
.exceptionHandling()
.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 server-side random string generation , On the other hand, it is the verification of client summary information .

  1. First of all, provide DigestAuthenticationEntryPoint Example , Configure a write parameter for server-side random number generation , for example nonce The period of validity ( How long will it change ),realm Name , And generate nonce What is needed when key.nonce The concrete generating logic of is in DigestAuthenticationEntryPoint#commence In the 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 , First get the expiration time , Then give the expiration time and key Together calculate the message digest , then nonce Together with the message digest value, Work out a Base64 Encoded characters , Then write the coded character back to the front end .

  1. To configure DigestAuthenticationFilter filter , It is mainly used to process front-end requests . The source code of the filter is relatively long , I won't post it here , A core idea is to get the summary information of user request from the front end , The server also calculates a summary based on the information , And then according to the summary information that comes over to carry on the comparison , And then confirm the user's identity .

When the configuration is complete , Restart the server for testing .

The test effect is actually the same as HttpBasic Certification is the same , All the changes , It's just that the implementation behind it has changed , The user experience is the same .

4. Summary

Http Although the effect of authentication is better than HttpBasic Security , But actually you can see , In fact, the security problems solved by the whole process are still very limited . And the code is a lot of trouble , So this kind of authentication method is not widely popular .

Http Certified partners as an understanding can , There are some interesting ideas in it , Can stimulate us to solve other problems , For example, the solution to replay attacks , If we want to defend ourselves against replay attacks , You can refer to the implementation ideas here .

All right. , If you have something to gain , Remember to watch and encourage brother song ~

版权声明
本文为[A kind of A little rain in the south of the Yangtze River]所创,转载请带上原文链接,感谢

  1. [front end -- JavaScript] knowledge point (IV) -- memory leakage in the project (I)
  2. This mechanism in JS
  3. Vue 3.0 source code learning 1 --- rendering process of components
  4. Learning the realization of canvas and simple drawing
  5. gin里获取http请求过来的参数
  6. vue3的新特性
  7. Get the parameters from HTTP request in gin
  8. New features of vue3
  9. vue-cli 引入腾讯地图(最新 api,rocketmq原理面试
  10. Vue 学习笔记(3,免费Java高级工程师学习资源
  11. Vue 学习笔记(2,Java编程视频教程
  12. Vue cli introduces Tencent maps (the latest API, rocketmq)
  13. Vue learning notes (3, free Java senior engineer learning resources)
  14. Vue learning notes (2, Java programming video tutorial)
  15. 【Vue】—props属性
  16. 【Vue】—创建组件
  17. [Vue] - props attribute
  18. [Vue] - create component
  19. 浅谈vue响应式原理及发布订阅模式和观察者模式
  20. On Vue responsive principle, publish subscribe mode and observer mode
  21. 浅谈vue响应式原理及发布订阅模式和观察者模式
  22. On Vue responsive principle, publish subscribe mode and observer mode
  23. Xiaobai can understand it. It only takes 4 steps to solve the problem of Vue keep alive cache component
  24. Publish, subscribe and observer of design patterns
  25. Summary of common content added in ES6 + (II)
  26. No.8 Vue element admin learning (III) vuex learning and login method analysis
  27. Write a mini webpack project construction tool
  28. Shopping cart (front-end static page preparation)
  29. Introduction to the fluent platform
  30. Webpack5 cache
  31. The difference between drop-down box select option and datalist
  32. CSS review (III)
  33. Node.js学习笔记【七】
  34. Node.js learning notes [VII]
  35. Vue Router根据后台数据加载不同的组件(思考->实现->不止于实现)
  36. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  37. 【JQuery框架,Java编程教程视频下载
  38. [jQuery framework, Java programming tutorial video download
  39. Vue Router根据后台数据加载不同的组件(思考->实现->不止于实现)
  40. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  41. 【Vue,阿里P8大佬亲自教你
  42. 【Vue基础知识总结 5,字节跳动算法工程师面试经验
  43. [Vue, Ali P8 teaches you personally
  44. [Vue basic knowledge summary 5. Interview experience of byte beating Algorithm Engineer
  45. 【问题记录】- 谷歌浏览器 Html生成PDF
  46. [problem record] - PDF generated by Google browser HTML
  47. 【问题记录】- 谷歌浏览器 Html生成PDF
  48. [problem record] - PDF generated by Google browser HTML
  49. 【JavaScript】查漏补缺 —数组中reduce()方法
  50. [JavaScript] leak checking and defect filling - reduce() method in array
  51. 【重识 HTML (3),350道Java面试真题分享
  52. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  53. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  54. [re recognize HTML (3) and share 350 real Java interview questions
  55. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  56. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  57. 【重识 HTML ,nginx面试题阿里
  58. 【重识 HTML (4),ELK原来这么简单
  59. [re recognize HTML, nginx interview questions]
  60. [re recognize HTML (4). Elk is so simple