第一步,准备工作。获取client id和client secret
1、自行登陆github官网,点击setting,如下图:
2、继续,点击developer settings,如下图:
3、继续,点击oauth apps,如下图:
4、继续,点击new oauth app,如下图:
5、继续,填写完毕后,点击register application,如下图:
6、至此,我们已经成功拿到client id和client secret。另外,此页面还可以更改步骤5填写的相关信息,如下图:
第二步,代码部分。实现github第三方登录
1、login.aspx 代码
<%@ page language="c#" autoeventwireup="true" codebehind="login.aspx.cs" inherits="githublogin.login" %> <!doctype html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="content-type" content="text/html; charset=utf-8"/> <title></title> </head> <body> <form id="form1" runat="server"> <div> <a href="https://github.com/login/oauth/authorize?client_id=xxxxxxxxxxxxxxxxxxxxxx&state=state&redirect_uri=http://www.kudsu.xyz/">github登录</a> </div> </form> </body> </html>
2、login.aspx.cs 代码
using newtonsoft.json; using newtonsoft.json.linq; using system; using system.collections.generic; using system.io; using system.linq; using system.net; using system.net.http; using system.text; using system.threading.tasks; using system.web; using system.web.ui; using system.web.ui.webcontrols; namespace githublogin { public partial class login : system.web.ui.page { protected void page_load(object sender, eventargs e) { if (!ispostback) { string code = request.querystring["code"] == null || request.querystring["code"].tostring() == "" ? "" : request.querystring["code"].tostring(); if (code != "") { //第二步,获取token string tokenjson = loadurlstring("https://github.com/login/oauth/access_token?client_id=xxxxxxxxxxxxxxx&client_secret=xxxxxxxxxxxxxxx&code=" + code + "&redirect_uri=http://www.kudsu.xyz/", "post"); jobject jo = (jobject)jsonconvert.deserializeobject(tokenjson); tokenjson = jo["access_token"].tostring(); //第三步,获取github用户信息 string userjson = loadurlstring("https://api.github.com/user?access_token=" + tokenjson, "get"); //把github用户信息输出到页面上 response.write(userjson); } } } /// <summary> /// 请求url /// </summary> /// <param name="url">地址</param> /// <param name="getpost">post、get</param> /// <returns></returns> private string loadurlstring(string url, string getpost) { system.net.servicepointmanager.securityprotocol = securityprotocoltype.tls12; httpwebrequest request1 = (httpwebrequest)webrequest.create(url); request1.method = getpost; request1.contenttype = "application/json"; request1.accept = "application/json"; request1.headers.add("accept-language", "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3"); request1.useragent = "mozilla/5.0 (windows nt 5.2; rv:12.0) gecko/20100101 firefox/12.0"; return new streamreader(((httpwebresponse)request1.getresponse()).getresponsestream(), encoding.utf8).readtoend(); } } }
3、项目地址:https://github.com/kudsu/githublogin
亲,如果可以,给个星星~
黄山市民网:https://www.huangshanshimin.com/