Currently, we are using OAuth2.0 authorization code flow into MVC web application, and its working fine as per our requirements, now same things we also need to implement it into our VB.net desktop application:
Below are steps use into MVC web application:
- App Register into Azure :
Register the app and set a redirect url to collect the authorized code:
Web:- https://localhost:44337/Oauth/callback
- Code to get Authorized code, access token, and refresh token:
var redirectUrl = "https://login.microsoftonline.com/3c150d40-f8a6-4418-b062-26ad5b6608dd/oauth2/v2.0/authorize?" +
"client_id=fe97ed3f-091b-4b86-88d8-dcce141571e1" +
"&response_type=code" +
"&redirect_uri=https://localhost:44337/Oauth/callback" + // need to put correct value in it. (redirect URL during app registration)
"&response_mode=query" +
"&scope= User.Read offline_access" +
"&state=12345";
return Redirect(redirectUrl);
- Collect auth code into redirect url:
public ActionResult callback(string code, string state, string error)
{
if (!string.IsNullOrWhiteSpace(code))
{
RestClient restClient = new RestClient("https://login.microsoftonline.com/3c150d40-f8a6-4418-b062-26ad5b6608dd/oauth2/v2.0/token?");
RestRequest restRequest = new RestRequest();
restRequest.AddParameter("client_id", "fe97ed3f-091b-4b86-88d8-dcce141571e1");
restRequest.AddParameter("scope", "User.Read offline_access");
restRequest.AddParameter("grant_type", "authorization_code");
restRequest.AddParameter("code", code);
restRequest.AddParameter("redirect_uri", "https://localhost:44337/Oauth/callback");
restRequest.AddParameter("client_secret", "E4K8Q~60nN~Bgpm31a5d3UeOGzfet93THIembcZP");
var response = restClient.Post(restRequest);
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
var customerDto = JsonConvert.DeserializeObject<Token>(response.Content);
}
}
}