Spring Security OAuth2 authorization callback processing mechanism

1. Preface The previous post focused on how to initialize the OAuth2AuthorizationRequest authorization request object when a user initiates a third-party authorization request and how to forward it through the filter to the third party. Today we will follow this process down to see what the server does when it receives an authorization request. 2. OAuth2 Login Authentication When the third party receives an OAuth2 authorization request, it will pass the authorization acknowledgement to us via a callback request redirect_uri provided by us.

How Spring Security OAuth2 authorization requests are constructed and executed

1. Preface In the previous article we found the filter OAuth2AuthorizationRequestRedirectFilter that intercepts the OAuth2 authorization request entry /oauth2/authorization and found the method that actually initiates the OAuth2 authorization request sendRedirectForAuthorization. But this method is not described in detail, so I’ll continue today. 2. sendRedirectForAuthorization This sendRedirectForAuthorization method is not much code, its main purpose is to redirect access to third-party platforms for authorization. All its logic is related to

Spring Security Client OAuth2 authorization request entry

Entry http://localhost:8082/oauth2/authorization/gitee Suppose the request URL above is the starting point for the client to perform third-party authentication, the default format is {baseUrl}/oauth2/authorization/{clientRegistrationId}, where clientRegistrationId represents a third-party identifier, which can be WeChat, Alipay and other open platforms. Alipay and other open platforms, in this case gitee. After the user clicks on the request, the authorization journey begins. Spring Security must have intercepted the /oauth2/authorization before enabling the OAuth2 related

Spring Boot integration lightweight logging framework tinylog

tinylog (https://tinylog.org/v2/), like various other things that start with tiny, is a lightweight open source logging solution. It itself contains only two JAR files (one for the API and the other for the implementation) and does not have any external dependencies. The total size of the two JAR files is only 178KB. Although it is a lightweight level solution , but we commonly used the basic log management features are very complete , it has a similar API design with other popular logging framework , a variety of configurable log output options , performance is also very impressive (this is the official Benchmark (https://tinylog.

How Spring Security filter chains match to specific requests

You know from previous post that SecurityFilterChain determines which requests go through the filter chain, so how does SecurityFilterChain match to a specific request? How to intercept specific requests Only requests that satisfy the match method of a SecurityFilterChain can be processed by that SecurityFilterChain, so how do you configure a SecurityFilterChain to process a specific path? RequestMatcher HttpSecurity has a built-in RequestMatcher property to handle path matching. The RequestMatcher

Writing Spring tests with Kotlin

Preface Usually we write Spring projects using Java language for business development and Java for unit testing. But Java is not very efficient in writing test code due to its lengthy code, and we usually consider multiple scenarios when writing the test code, so the amount of code expands dramatically, which brings a lot of time wastage. The biggest headache is the MockMvc mock request test, Java does not support multi-line strings until 15, which leads to the need to splice line by line, which is very unintuitive to read and does not make good use of the Intellij IDEA injection language.

Tracking the SpringMVC request process

Overall flow All requests are intercepted to DispatcherServlet , which is also a Servlet , executing doService . Snapshot all the parameters in the request and set some objects in the framework to the request object. Call the doDispatch(request,response) method. Call the getHandler method to get the corresponding Handler. Call getHandlerAdapter to get the corresponding HandlerAdapter. Apply the interceptor’s PreHandler, or return it directly if the interceptor’s PreHandeler returns false.

Understanding HttpMessageConverter in Spring

Http Message Converter Introduction Http Message Converter is responsible for serializing Java Object to JSON/XML data representation and deserializing JSON/XML data representation to Java Object. When we configure: <mvc:annotation-driven /> in based XML or @EnableWebMvc in based Java (both are equivalent), AnnotationDrivenBeanDefinitionParser will register a series of conversion service, validators, and message-converters. If there is no custom <message-converters> tag in <mvc:annotation-driven />, Spring will register the following set of message-converters

Spring Security version 5.4 brings new ways to play

1. Preface In previous Spring Security tutorials we customize configuration by declaring a configuration class WebSecurityConfigurerAdapter and then overriding (@Override) the corresponding methods. However, all this has changed since Spring Security 5.4, since Spring Security 5.4 we don’t need to inherit from WebSecurityConfigurerAdapter in order to configure HttpSecurity. The original description reads. Remove need for WebSecurityConfigurerAdapter #8805 Configure HTTP Security without extending WebSecurityConfigurerAdapter #8804 issues/8804) 2. The new configuration method

Optimize Spring Boot application Docker images to improve CI/CD efficiency

More and more projects are containerized and Docker has become an important tool in software development. We can usually package the fat jar of a Spring Boot application as a docker image with the following Dockerfile. 1 2 3 4 5 FROM adoptopenjdk:8-jre-hotspot ARG JAR_FILE=target/*.jar COPY ${JAR_FILE} app.jar EXPOSE 8080 ENTRYPOINT ["java","-jar","/app.jar"] It looks good, but you will find that if we change the business code, the image will be

Spring Security Dynamic Permission Control could be a little simpler

Previously in the tutorial on dynamic permission control, we implemented dynamic permission control by customizing FilterInvocationSecurityMetadataSource and AccessDecisionManager two interfaces. There are more things we need to do here, and there is a certain learning cost. Today to introduce a more simple and easy to understand approach to implement dynamic permission control. Expression-based access control 1 2 3 httpSecurity.authorizeRequests() .anyRequest() .access("hasRole('admin')") Needless to say, after we configure the expression hasRole('admin'),

Spring Security filter chain system

While learning Spring Security did you have any of the following two questions. How is login configured in Spring Security? What is the access control mechanism for Spring Security? SpringBootWebSecurityConfiguration The answers to the above two questions are in the configuration class SpringBootWebSecurityConfiguration. You can follow this mind map to understand it. This auto-configuration: SpringBootWebSecurityConfiguration provides a default set of Spring Security configurations for Spring Boot applications. 1 2 3

How to elegantly read and write HttpServletRequest and HttpServletResponse request bodies

Recently, many interactions have to deal with the native HttpServletRequest and HttpServletResponse. Read body data from HttpServletRequest and encapsulate it into some kind of data structure; write data to HttpServletResponse and respond. The traditional way of writing is very inelegant, so today we introduce you to a more elegant way. HttpMessageConverter HttpMessageConverter is a message converter model provided by the Spring Framework, a policy interface for converting between HTTP requests

Spring Security's new JWT implementation

I have used the official spring-security-jwt provided by Spring as an implementation of JWT. This toolkit is no longer maintained. And it is not particularly compatible with the latest Spring Security OAuth2 Client and Spring Authorization Server. So I took two days to re-implement JWT with these two new dependencies. Nimbus Library The JOSE library nimbus-jose-jwt from Nimbus is used by default in the latest Spring Security. This library is currently one of the most used JOSE class libraries and most of the transformation work has been done around this library.

Spring Boot Rapid Integration with Swagger3

Interface documentation is always annoying, and I have tried using Postman to write and share project documentation, and it felt fine. But lately projects are tight and I don’t have extra time to spend on it, which led to my plan to try YApi (another kind of documentation) to go down the drain. Well, there is no faster and more foolproof tool than Swagger, although it has serious code pollution.

Verify the imported Excel data using jsr303

Recently in doing Excel import function, the product requires the imported data to be verified first and then into the library. So a simple package of tools, we think it’s not bad. Today, we will share the ideas. easyexcel library We all know that POI is the base library for Java manipulation of Excel. It is not customized for generality and has some limitations. After some research it was decided

The difference between WebSecurity and HttpSecurity in Spring Security

The Nature of HttpSecurity Spring Security 5.4 has a new way of configuring HttpSecurity. 1 2 3 4 5 6 7 8 9 @Bean SecurityFilterChain filterChain(HttpSecurity http) throws Exception { return http .antMatcher("/**") .authorizeRequests(authorize -> authorize .anyRequest().authenticated() ) .build(); } In fact, you can know that HttpSecurity is used to build a filter SecurityFilterChain that contains a series of filter chains, and normally our configuration is based around building SecurityFilterChain.

Spring Security Unit Testing

Spring Security Test Environment To use Spring Security in your unit tests, you need to add spring-security-test to your Spring Boot project. 1 2 3 4 5 <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-test</artifactId> <scope>test</scope> </dependency> This way the contextual configuration of the tests can be combined with Spring Security, and the next few tricks will teach you. Spring Security Testing All tests are done under Spring Boot Test, which is supported by the @SpringBootTest annotation.

Various ways of handling exceptions in Spring

Usually the unified exception handling we set up in Spring Boot can only handle exceptions thrown by the Controller. Some requests have exceptions before they reach the Controller, and these exceptions cannot be caught by unified exceptions, such as some exceptions in the Servlet container. Today I encountered one in my project development, which irritated me because it returned an error message format that could not be handled uniformly, and

Spring Boot Containerization via Docker

Recently the company’s application ready to containerize, because dozens of applications from testing to release is too much trouble, and also because of environmental factors lead to a variety of problems in the deployment. In order to maintain a consistent environment in development, testing, production, the introduction of container technology, first take the edge of the project to try, to gain experience. Today a brief summary of several common Docker