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

The solution to the problem of single sign-on SSO after upgrading Spring Boot from 1.x to 2.x

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

Share

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

This article mainly introduces "the solution to the problem of single sign-on SSO after upgrading Spring Boot from 1.x to 2.x". In daily operation, it is believed that many people have doubts about the solution to the problem of single sign-on SSO after upgrading Spring Boot from 1.x to 2.x. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to solve the problem of single sign-on SSO after upgrading Spring Boot from 1.x to 2.x! Next, please follow the editor to study!

Solve the problem of single sign-on (SSO) after upgrading Spring Boot from 1.x to 2.x

> when learning Spring Cloud,    always has little knowledge of oauth related to authorization service, so he decides to first study and sort through the permissions such as Spring Security, Spring Security Oauth3, authentication-related content, principles and design. This series of articles is written to strengthen the impression and understanding in the process of learning. Please let me know if there is any infringement.

> Project environment: >-JDK1.8 >-Spring boot 2.x >-Spring Security 5.x

   has basically written almost the content related to Spring Security in the early stage, so I have been sorting out the content related to Spring Sexurity Oauh3 recently, but when it comes to single sign-on (OSS), there is a problem that has been bothering me for a long time, because there is little information on how to solve the problems related to single sign-on after upgrading from Spring Boot 1.x to Spring Boot 2.x. Here is a special article to describe some of the problems encountered in the upgrade process, the performance of the problems and how I solved these problems.

Question 1: except for @ EnableOAuth3Sso in spring boot 2?

First of all,    makes it clear to you that there is no! But why did you introduce spring-security-oauth3 maven to rely on the IDEA prompt @ EnableOAuth3Sso to find it? First of all, we find the official Spring Boot 2.x upgrade document, and we will find an introduction to Oauth3:

> OAuth 2.0 Support Functionality from the Spring Security OAuth project is being migrated to core Spring Security. OAuth 2.0 client support has already been added and additional features will be migrated in due course.

> If you depend on Spring Security OAuth features that have not yet been migrated you will need to add org.springframework.security.oauth:spring-security-oauth3 and configure things manually. If you only need OAuth 2.0 client support you can use the auto-configuration provided by Spring Boot 2.0. We're also continuing to support Spring Boot 1.5 so older applications can continue to use that until an upgrade path is provided.

   We can roughly understand that official 2.x is migrating the functionality of the Spring Security OAuth project to Spring Security. But what is most noteworthy is that there is a passage that says If you only need OAuth 2.0 client support you can use the auto-configuration provided by Spring Boot 2.0. (you need to use auto-configuration if you want to use Oauth3 client-related features in Spring Boot 2.0 (and above).

   based on this hint, we find the official auto-configuration document and tell us the minimum maven dependency we need to use as soon as we come in:

Org.springframework.boot spring-boot-starter-security org.springframework.security.oauth.boot spring-security-oauth3-autoconfigure 2.1.7.RELEASE

   successfully referenced @ EnableOAuth3Sso in accordance with the official documentation configuration, and the problem has been solved!

Question 2: call back to the client during the single sign-on authorization process but prompt 401 (unauthorized) problem?

# 1. Configuration of SSO client

ClientSecurityConfig configuration @ Configuration@EnableOAuth3Sso / / SSo Auto configuration reference public class ClientSecurityConfig extends WebSecurityConfigurerAdapter {@ Override public void configure (HttpSecurity http) throws Exception {http.authorizeRequests () .antMatching ("/"). PermitAll () .anyRequest (). Authenticated () .and () .csrf () .csrf (). Disable ();}}

This configuration is as recommended in the official auto-configuration documentation.

Application.yml configuration auth-server: http://localhost:9090 # authorization service address security: oauth3: client: user-authorization-uri: ${auth-server} / oauth/authorize # request authentication address access-token-uri: ${auth-server} / oauth/token # request token address resource: jwt: key-uri: ${auth-server} / oauth/token_key # address of the key required to resolve the jwt token When the service starts, the authorization service is called. This API is used to obtain the jwt key. Therefore, it is important to make sure that the authorization service sso: login-path: / login # points to the login page, that is, the OAuth3 authorization server triggers the redirection to the client. The default is / loginspring: profiles: active: client1.

   because we need multi-client single-point testing, we use the multi-environment configuration of Spring boot. The configuration of authorization service is not described here, and an available authorization service is built by default. (if you are not clear about how to build Oauth3 authorization service and resource service, please follow me, and related articles will be published later).

Application-client1.yml configuration server: port: 8091 security: oauth3: client: client-id: client1 client-secret: 123456 Test Interface @ RestController@Slf4jpublic class TestController {@ GetMapping ("/ client/ {clientId}") public String getClient (@ PathVariable String clientId) {return clientId;}}

At this point,    asked us to complete a basic SSO client and start the project.

# 2. Problem description and phenomena access the test interface localhost:8091/client/1 on the    browser, jump to the login interface of the authorized service, and jump back to the client's / login address (that is, our configured spring.security.sso.login-path) after the login is successful. Normally, it will be redirected to localhost:8091/client/1 again (this time it will be accessed after successful authentication). This whole process is the authorization code mode process of Oauth3. But now there is a problem. When the authorization service is called back to the client's / login address, the browser displays HTTP ERROR 401, as shown below:

   from the figure, we can see that the authorization service successfully returned the authorization code, but due to a problem in our client, the whole authorization code mode process was interrupted. In the process of reading the official auto-configuration documents, I inadvertently found

> Also note that since all endpoints are secure by default, this includes any default error handling endpoints, for example, the endpoint "/ error". This means that if there is some problem during Single Sign On that requires the application to redirect to the "/ error" page, then this can cause an infinite redirect between the identity provider and the receiving application. First, think carefully about making an endpoint insecure as you may find that the behavior is simply evidence of a different problem. However, this behavior can be addressed by configuring the application to permit "/ error":

@ Configurationpublic class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {@ Override protected void configure (HttpSecurity http) throws Exception {http .authorizeRequests () .ant Matchers ("/ error"). PermitAll () .anyRequest (). Authenticated ();}}

   roughly means that since all endpoints are secure by default, this includes any default error handling endpoints, such as the endpoint "/ error". This means that if there are some problems during single sign-on and the application needs to be redirected to the "/ error" page, this can result in unlimited redirection between the identity provider and the receiving application.

   according to this prompt, I started DEBUG, and as stated in the document, some problems during single sign-on were redirected to / error, so we configured / error to have no permission to access the test interface, and the error interface prompt is obvious this time:

Now that    clearly prompts Unauthorized, let's take a step-by-step DEBUG to see what the problem is during the single point.

# 3. Problem troubleshooting and solution    from the previous phenomenon description, we can know that there is a problem when the problem point is called to obtain token after the authorization code is returned. According to the source code, the step of obtaining token is inside the OAuth3ClientAuthenticationProcessingFilter filter. The key code is as follows:

@ Override public Authentication attemptAuthentication (HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {OAuth3AccessToken accessToken; try {accessToken = restTemplate.getAccessToken () / / 1 call the authorization service to get token} catch (OAuth3Exception e) {BadCredentialsException bad = new BadCredentialsException ("Could not obtain access token", e); publish (new OAuth3AuthenticationFailureEvent (bad)); throw bad } try {OAuth3Authentication result = tokenServices.loadAuthentication (accessToken.getValue ()); / / parse OAuth3Authentication information if (authenticationDetailsSourcesources null) {request.setAttribute (OAuth3AuthenticationDetails.ACCESS_TOKEN_VALUE, accessToken.getValue ()) from token after success Request.setAttribute (OAuth3AuthenticationDetails.ACCESS_TOKEN_TYPE, accessToken.getTokenType ()); result.setDetails (authenticationDetailsSource.buildDetails (request));} publish (new AuthenticationSuccessEvent (result)); return result } catch (InvalidTokenException e) {BadCredentialsException bad = new BadCredentialsException ("Could not obtain user details from token", e); publish (new OAuth3AuthenticationFailureEvent (bad)); throw bad;}}

   We hit the breakpoint here. Under Debug, as expected, an exception occurred while obtaining token. The exception message is: Possible CSRF detected-state parameter was required but no state could be found. The screenshot of debug is as follows:

   has the following statement when consulting online materials:

> Local developers, auth server and client are both localhost, resulting in the interaction of JSESSIONID. This can be solved by configuring the context-path or session name of client

   according to this description, I tried to change the session name to solve the problem:

Server: servlet: session: cookie: name: OAUTH2CLIENTSESSION # solve the Possible CSRF detected-state parameter was required but no state could be found problem

   restart the project, test SSO, perfect solution!

At this point, the study on "the solution to the problem of single sign-on SSO after Spring Boot upgrade from 1.x to 2.x" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

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