Chilkat Classic ASP Online Tools

Classic ASP to Get Office365 OAuth2 Access Token for IMAP, SMTP, or POP3

This tool demonstrates how to get a Microsoft Office365 OAuth2 access token using three-legged OAuth2 in a Classic ASP application. This is also known as the "authorization code grant flow". This is when your Classic ASP app acts on the behalf of a third-party user, your app must obtain the user's permission before it can make requests that access and update that third-party's confidential resources. A User access token carries a third-party's authorization to access specific resources, and this type of token is obtained through the authorization code grant flow.

* See this post for instructions on how to Create an Azure App Registration for use with IMAP, POP3, and SMTP

The Classic ASP Source Code for this Page

<%@ Language=VBScript %>
<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Classic ASP Office365 OAuth2 Example</title>
        <link rel="apple-touch-icon" sizes="76x76" href="/apple-touch-icon.png">
        <link rel="icon" type="image/png" href="/favicon-32x32.png" sizes="32x32">
        <link rel="icon" type="image/png" href="/favicon-16x16.png" sizes="16x16">

        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    </head>

    <body>
        <!--#include file="header.shtml" -->
        <div>

<%
    access_token = ""
    state = Request.QueryString("state")

    ' Check to see if this is our redirect containing the access token.
    if state <> "" then

        ' Make sure this is the redirect for our session.
        if state <> Session("oauth2_state") then
            access_token = "invalid_state"
        elseif Request.QueryString("code") <> "" then
        
        
	        ' Exchange authorization code for refresh and access tokens
	        
	        set glob = Server.CreateObject("Chilkat_9_5_0.Global")
	        success = glob.UnlockBundle(Mid("<unlockCode>Anything for 30-day trial....</unlockCode>",13,29))
	        
	        set http = Server.CreateObject("Chilkat_9_5_0.Http")
			
	        set req = Server.CreateObject("Chilkat_9_5_0.HttpRequest")
	        req.AddHeader "Accept","application/json"
	        req.AddParam "client_id","581e2fa2-2929-49d6-8b8d-6439c7be4c6c"
	        req.AddParam "client_secret",Mid("<secret>............CLIENT_SECRET...............</secret>",9,40)
	        req.AddParam "grant_type","authorization_code"
	        req.AddParam "code",Request.QueryString("code")
	        req.AddParam "redirect_uri","https://tools.chilkat.io/office365_oauth2.asp"
	        
	        ' resp is a Chilkat_9_5_0.HttpResponse
	        ' Use your tenant ID instead of "112d7..."
	        Set resp = http.PostUrlEncoded("https://login.microsoftonline.com/112d7ed6-71bf-4eba-a866-738364321bfc/oauth2/v2.0/token",req)
	        If (http.LastMethodSuccess <> 1) Then
	            Response.Write "<pre>" & Server.HTMLEncode( http.LastErrorText) & "</pre>"
	            Response.End
	        End If

	        set json = Server.CreateObject("Chilkat_9_5_0.JsonObject")
	        json.EmitCompact = 0
	        json.Load(resp.BodyStr)
	        Response.Write "<pre>" & Server.HTMLEncode( json.Emit()) & "</pre>"
			
	        access_token = json.StringOf("access_token")
	        
	        ' You save the JSON containing the access/refresh tokens to a cookie to make it available in subsequent requests in the same ASP session...
	        ' The JSON contains something like this:
	        
			' {
			'   "token_type": "Bearer",
			'   "scope": "openid profile User.Read User.ReadWrite Mail.ReadWrite Mail.Send Files.ReadWrite",
			'   "expires_in": 3600,
			'   "ext_expires_in": 3600,
			'   "access_token": "EwCQA8l6...8+CYUC",
			'   "refresh_token": "MCXmlpj...2QDng$$",
			'   "id_token": "eyJ0e...Sic2bg"
			' }	        
			
	        json.EmitCompact = 1
	        Response.Cookies("ms_access_json")=json.Emit()

            
        end if
    end if

    set req = Server.CreateObject("Chilkat_9_5_0.HttpRequest")
    call req.AddParam("client_id", "581e2fa2-2929-49d6-8b8d-6439c7be4c6c")
    ' Redirect to any ASP page desired.  This example will redirect to this same ASP page..
    call req.AddParam("redirect_uri", "https://tools.chilkat.io/office365_oauth2.asp")
    call req.AddParam("response_type", "code")
    call req.AddParam("prompt","login")
    call req.AddParam("scope", "openid profile offline_access https://outlook.office365.com/SMTP.Send https://outlook.office365.com/POP.AccessAsUser.All https://outlook.office365.com/IMAP.AccessAsUser.All")
    ' Replace this with random data..
    stateData = "12345678" 
    call req.AddParam("state", stateData)
    Session("oauth2_state") = stateData

	' Use your tenant ID instead of "112d7..."
    auth_url = "https://login.microsoftonline.com/112d7ed6-71bf-4eba-a866-738364321bfc/oauth2/v2.0/authorize?" + req.GetUrlEncodedParams()

%>

<div class="container">
    <h2>Classic ASP to Get Office365 OAuth2 Access Token for IMAP, SMTP, or POP3</h2>
    <p>
        This tool demonstrates how to get a Microsoft Office365 OAuth2 access token using
        three-legged OAuth2 in a Classic ASP application.  This is also known as the "authorization code grant flow".
        This is when your Classic ASP app acts on the behalf of a third-party user, your app must obtain the user's permission
        before it can make requests that access and update that third-party's confidential resources. A User access token carries
        a third-party's authorization to access specific resources, and this type of token is obtained through the authorization code grant flow.
    </p>
    <h4>* See this post for instructions on how to  <a href="https://cknotes.com/create-azure-app-registration-for-use-with-imap-pop3-and-smtp/">Create an Azure App Registration for use with IMAP, POP3, and SMTP</a></h4>
    <div class="panel panel-default">
        <div class="panel-body">
            <a href="<%=auth_url %>" class="btn btn-primary" role="button">Begin OAuth2</a>
        </div>
    </div>
    <div class="panel panel-default">
          <%
            if access_token <> "" then
                Response.Write("<p><b></b>Microsoft Office365 access token:</b>" & access_token & "</p>")
            end if

        %>
    </div>
    
    <div class="panel panel-default">
        <h2>The Classic ASP Source Code for this Page</h2>
        <pre><%
    		set fac = Server.CreateObject("Chilkat_9_5_0.FileAccess")
            path = Server.MapPath("office365_oauth2.asp")
            src = fac.ReadEntireTextFile(path,"utf-8")
            set sbTemp = Server.CreateObject("Chilkat_9_5_0.StringBuilder")
            success = sbTemp.Append(src)
            n = sbTemp.ReplaceAllBetween("<secret>", "</secret>", "............CLIENT_SECRET...............", 0)
            n = sbTemp.ReplaceAllBetween("<unlockCode>", "</unlockCode>", "Anything for 30-day trial....", 0)
            src = sbTemp.GetAsString()
            Response.Write(Server.HTMLEncode(src))
        %>
        </pre>
    </div>

</div>

        </div>
        <!--#include file="footer.shtml" -->
    </body>
</html>