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 single sign-on Cross-domain by separating the Front and back end of vue+springboot

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly introduces the "vue+springboot front and rear separation how to achieve single sign-on cross-domain", in the daily operation, I believe that many people in the vue+springboot front and back separation how to achieve single sign-on cross-domain problems have doubts, editor consulted all kinds of information, sorted out simple and easy to use operation methods, hope to answer the "vue+springboot front and back end separation how to achieve single sign-on cross-domain" doubt helpful! Next, please follow the editor to study!

The code is as follows:

@ Configurationpublic class CorsConfiguration {@ Bean public WebMvcConfigurer corsConfigurer () {return new WebMvcConfigurerAdapter () {@ Override public void addCorsMappings (CorsRegistry registry) {registry.addMapping ("/ *") .allowedHeaders ("*") .allowedHeaders ("*") .allowedOrigins ("*");}};}}

This configuration allows all mapping, all request headers, all request methods, all sources. After changing the configuration, I decisively restarted the project and looked at the effect. I found that it was impossible to redirect to the single sign-on page. I saw that the error reported by the browser was caused by cross-domain. I first went to the code of my login interceptor.

Public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {/ / user has logged in to if (request.getSession (). GetAttribute ("user")! = null) {return true;} / / after returning from single sign-on, the system is not yet in the login state / / get access_token according to code value, then obtain user information according to access_token, and store user information in session String state = request.getParameter ("state") String uri = getUri (request); if (isLoginFromSSO (state)) {String code = request.getParameter ("code"); Object cacheUrl = request.getSession (). GetAttribute (state); if (cacheUrl = = null) {response.sendRedirect (uri); return false;} HttpUtil client = new HttpUtil (); StringBuffer sb = new StringBuffer () Sb.append ("code=") .append (code) .append ("& grant_type="). Append ("authorization_code") .append ("& client_id=") .append ("& client_secret=") .append (SSOAuth.ClientSecret) .append ("& redirect_uri=") .append (URLEncoder.encode ((String) cacheUrl)); String resp = client.post (SSOAuth.AccessTokenUrl, sb.toString ()) Map map = new Gson (). FromJson (resp, Map.class); / / obtain user information according to access_token String accessToken = map.get ("access_token"); HttpUtil http = new HttpUtil (); http.addHeader ("Authorization", "Bearer" + accessToken); String encrypt = http.get (SSOAuth.UserUrl); String userinfo = decryptUserInfo (encrypt); / / encapsulated into user object User user = new Gson (). FromJson (userinfo, User.class) Request.getSession () .setAttribute ("user", user); return true;} / / Jump to single sign-on interface state = Const._SSO_LOGIN + Const.UNDERLINE + RandomUtil.getUUID (); request.getSession () .setAttribute (state, uri); String redirectUrl = buildAuthCodeUrl (uri, state); response.sendRedirect (redirectUrl); return false;}

Later, the login interface of the front-end vue request background is directly used.

_ window.location.href=this.$api.config.baseUrl+ "/ system/user/login"

After that, the front end accesses the system and can jump directly to the single sign-on page. But when I entered my account and password and clicked on to log in, I jumped back to the system and found that all the request data interfaces could not be accessed properly. Debug found that all requests had no user information and were identified as not logged in by the interceptor, and all requests could not be passed.

Why am I clearly logged in, and the interceptor also sets the user information to session? why is cookies gone? After initiating the request again, I found that the JsessionId of each request was different. After looking up a lot of information, I found that it was necessary to add a configuration with authentication information at the front end.

Axios.defaults.withCredentials=true

The background also needs to make a corresponding configuration allowCredentials (true)

@ Beanpublic WebMvcConfigurer corsConfigurer () {return new WebMvcConfigurerAdapter () {@ Override public void addCorsMappings (CorsRegistry registry) {registry.addMapping ("/ *") .allowedHeaders ("*") .allowedMethods ("*") .allowedOrigins ("*") .allowCredentials (true);}};}

After adding this configuration, execute the operation process again, and find that after logging in, you can jump to the system normally, and the page data is displayed normally.

Just when I thought it was done, I suddenly clicked to a page and could not display the data normally. I wondered, I hastened to F12, and found a request method that I had never seen before, the OPTIONS request. The original request method was clearly POST, how did it become OPTIONS? So I had several other POST requests and found that they all turned into OPTIONS requests. Looking confused, I quickly checked the information of the OPTIONS request. The Internet says that the OPTIONS request is called a "pre-check request", that is, before your formal request is executed, the browser will first issue a pre-check request, and the pre-check request will be passed before the formal request can be executed. After reading it, I suddenly realized that the OPTIONS had been intercepted, so I could no longer execute my POST request, so I just let the pre-check request pass. Just add this judgment to the interceptor.

/ / option pre-check, directly by requesting if ("OPTIONS" .equals (request.getMethod () {return true;}

In this way, the interceptor finds that the request is a pre-check request and passes directly, and then the next POST request can be executed.

At this point, on the "vue+springboot front and back end separation how to achieve single sign-on cross-domain" study is over, I hope to be able to solve everyone's 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

Development

Wechat

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

12
Report