In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article focuses on "how to use Java code to achieve third-party authentication login", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let the editor take you to learn "how to use Java code to achieve third-party authentication login"!
First, create application 1 on Code Cloud, register an account on Code Cloud, click on the upper right corner to set up 2, create application 3, and fill in the information.
Many students do not know what is the application callback address webhooks (after a third party logs in successfully, it will return to the address you specified and carry the parameter information to verify whether it is successful)
4. Get clientId and client Secret
The main function of clientId and client Sercret is to get the requested address by splicing and redirect the address to the authorized login page
The preparation process has been completed
2. Implement third-party login in the project 1, import dependent jar package javax.servlet javax.servlet-api 3.1.0 me.zhyd.oauth JustAuth 1.3.2 org.apache.httpcomponents httpclient 4.5.22, Jump authorization page AuthRequest authRequest = new AuthGiteeRequest (AuthConfig.builder () .clientId (CLIENT_ID) / / Client ID .clientSecret (CLIENT_SECRET) / / Client Secret .redirectUri (REDIRECTURI) / / callback address .build ()) String authorizeUrl = authRequest.authorize (AuthStateUtils.createState ()); / / Jump to the authorization page response.sendRedirect (authorizeUrl); 3. Get the code value / / http://localhost:8080/login?actionName=giteeCode&code=e063730161cd40cf&state=25c74eba2ac5f String code = request.getParameter ("code") through the callback address; 4. Send the user authorization code to the CVM.
Add a small hole, code cloud third-party verification needs to add header information, otherwise it will report a 403 error
String url = "https://gitee.com/oauth/token?grant_type=authorization_code&code="+code+"&client_id="+CLIENT_ID+"&redirect_uri="+REDIRECTURI+"&client_secret="+CLIENT_SECRET;Map map = new HashMap (); map.put (" User-Agent "," Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 "); JSONObject s = HttpUtils.post (url,map)
Authorization login failure returns a message error message, identifying login failure
Success:
{"access_token": "e386e20327b7c4", "refresh_token": "057c79c2d1f957a5cb4d", "scope": "user_info", "created_at": 15488, "token_type": "bearer", "expires_in": 86400} 5, obtain password cloud user information
The json data obtained through the authorization code, in which the access_token parameter can access the user data of Code Cloud.
/ / https://gitee.com/api/v5/user?access_token=*******String access_token = s.getString ("access_token"); String url2 = "https://gitee.com/api/v5/user?access_token="+access_token;JSONObject user = HttpUtils.get (url2,map); / / 1. Set the response type output stream response.setContentType (" application/json;charset=UTF-8 "); / / 2, convert json to the string String str = JSON.toJSONString (user) / / 3. Get the character output stream response.getWriter (). Write (str)
Source code:
Here the editor would like to talk about the difference between callback address operation 1 and callback address operation 2.
Operation 1: the editor uses the get,post of the server to send the request, while the plug-in is used to jump to the "authorization page" (giteeLogin method). You can also manually change the get request to the third-party login page. Please refer to the specific get address.
Cloud oauth document
Steps An and B, after modification, you can jump to the authorization page without plug-in code.
Operation 2: completely use the JustAuth plug-in to implement third-party login
Import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.JSONObject;import com.shsxt.utils.HttpUtils;import me.zhyd.oauth.config.AuthConfig;import me.zhyd.oauth.model.AuthCallback;import me.zhyd.oauth.model.AuthResponse;import me.zhyd.oauth.request.AuthGiteeRequest;import me.zhyd.oauth.request.AuthRequest;import me.zhyd.oauth.utils.AuthStateUtils;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.methods.HttpPost;import org.apache.http.client.methods.HttpRequestBase Import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.util.EntityUtils;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;import java.io.UnsupportedEncodingException;import java.util.HashMap;import java.util.Map;@WebServlet ("/ login") public class LoginServlet extends HttpServlet {private static final long serialVersionUID = 1L / / ac85a173bb89ee private final String CLIENT_ID = "Client ID" private final String CLIENT_SECRET= "Client Secret" private final String REDIRECTURI = "callback address" protected void service (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {/ / get user behavior String actionName = request.getParameter ("actionName") / / determine user behavior if ("giteeLogin" .equals (actionName)) {/ / if sending code cloud authorization verification giteeLogin (request,response);} else if ("giteeCode" .equals (actionName)) {/ / giteeCode (request,response); giteeCode2 (request,response);} System.out.println ("clicked") Operation 1 * @ param request * @ param response * / private void giteeCode (HttpServletRequest request, HttpServletResponse response) throws IOException {/ / get code String code = request.getParameter ("code") after calling back the address String url = "https://gitee.com/oauth/token?grant_type=authorization_code&code="+code+"&client_id="+CLIENT_ID+"&redirect_uri="+REDIRECTURI+"&client_secret="+CLIENT_SECRET; Map map = new HashMap (); map.put (" User-Agent "," Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 ") JSONObject s = HttpUtils.post (url,map); System.out.println (s); / / https://gitee.com/api/v5/user?access_token=******* String access_token = s.getString ("access_token"); String url2 = "https://gitee.com/api/v5/user?access_token="+access_token; JSONObject user = HttpUtils.get (url2,map) / / 1. Set the response type output stream response.setContentType ("application/json;charset=UTF-8"); / / 2, convert json to the string String str = JSON.toJSONString (user); / / 3, get the character output stream response.getWriter () .write (str) 2 * @ param request * @ param response * / private void giteeCode2 (HttpServletRequest request, HttpServletResponse response) throws IOException {String code = request.getParameter ("code") AuthRequest authRequest = new AuthGiteeRequest (AuthConfig.builder () .clientId (CLIENT_ID) / / Client ID .clientSecret (CLIENT_SECRET) / / Client Secret .redirectUri (REDIRECTURI) / / callback address .build ()); AuthResponse json = authRequest.login (code); System.out.println (json) } / * Redirect authorization page * @ param request * @ param response * / private void giteeLogin (HttpServletRequest request HttpServletResponse response) throws IOException {/ / Redirect authorization page AuthRequest authRequest = new AuthGiteeRequest (AuthConfig.builder () .clientId (CLIENT_ID) / / Client ID .clientSecret (CLIENT_SECRET) / / Client Secret .redirectUri (REDIRECTURI) / / callback address .build ()) String authorizeUrl = authRequest.authorize (); / / Jump to authorization page response.sendRedirect (authorizeUrl);}}
Server sends get/post request utility class
Package com.shsxt.utils;import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.JSONObject;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.methods.HttpGet;import org.apache.http.client.methods.HttpPost;import org.apache.http.client.methods.HttpRequestBase;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.util.EntityUtils;import java.io.IOException;import java.io.UnsupportedEncodingException Import java.util.Map;import java.util.Set;public class HttpUtils {/ * * send simple post request * / public static JSONObject post (String url) {HttpPost post = new HttpPost (url); return getResult (post);} / * * send post request with Header * / public static JSONObject post (String url, Map map) {HttpPost post = new HttpPost (url) If (! map.isEmpty ()) {Set entrys = map.entrySet (); for (Map.Entry entry: entrys) {post.setHeader (entry.getKey (), entry.getValue ());}} return getResult (post) } / * * send get request with Header * / public static JSONObject get (String url, Map map) {HttpGet get = new HttpGet (url); if (! map.isEmpty ()) {Set entrys = map.entrySet (); for (Map.Entry entry: entrys) {get.setHeader (entry.getKey (), entry.getValue ()) }} return getResult (get);} / * * send a simple get request * / public static JSONObject get (String url) {HttpGet get = new HttpGet (url); return getResult (get) } / * * send the request method. The request response is JSONObject * / private static JSONObject getResult (HttpRequestBase requestBase) {CloseableHttpClient httpClient = HttpClients.createDefault (); String result = null; try {result = EntityUtils.toString (httpClient.execute (requestBase). GetEntity ()); result = new String (result.getBytes ("ISO-8859-1"), "utf-8") HttpClient.close ();} catch (UnsupportedEncodingException E1) {e1.printStackTrace ();} catch (ClientProtocolException E1) {e1.printStackTrace ();} catch (IOException E1) {e1.printStackTrace ();} finally {return new JSONObject (JSON.parseObject (result)) }} / * * when the request response is String, * / public static String getString (String url) {CloseableHttpClient httpClient = HttpClients.createDefault (); HttpGet get = new HttpGet (url); String result = null; try {result = EntityUtils.toString (httpClient.execute (get). GetEntity ()); httpClient.close () } catch (UnsupportedEncodingException E1) {e1.printStackTrace ();} catch (ClientProtocolException E1) {e1.printStackTrace ();} catch (IOException E1) {e1.printStackTrace ();} finally {return result } ```* when the request response is String, * / public static String getString (String url) {CloseableHttpClient httpClient = HttpClients.createDefault (); HttpGet get = new HttpGet (url); String result = null; try {result = EntityUtils.toString (httpClient.execute (get). GetEntity ()); httpClient.close () } catch (UnsupportedEncodingException E1) {e1.printStackTrace ();} catch (ClientProtocolException E1) {e1.printStackTrace ();} catch (IOException E1) {e1.printStackTrace ();} finally {return result At this point, I believe you have a deeper understanding of "how to use Java code to achieve third-party authentication login". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
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: 237
*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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.