public OAuthResponse CallAuthorization(string accessToken, string code)
{
// We already have an access token in session
if (!string.IsNullOrEmpty(accessToken))
return new OAuthResponse { Success = false, Message = "Access Token is missing"};
// We get a code back from the first leg of OAuth process. If we don't have one, let's get it.
// Here the user will log into the SLC. This page will be called back with the code to do second leg of OAuth.
if (string.IsNullOrEmpty(code))
return new OAuthResponse {Success = false, Message = "Code is missing; Authorization required", AuthorizationUrl = GetAuthorizationUrl()};
try
{
// Construct API call to validate code
string sessionUrl = string.Format(_apiHelper.ApiUrl + "/oauth/token?client_id={0}&client_secret={1}&grant_type=authorization_code&redirect_uri={2}&code={3}", _clientId, _clientSecret, _redirectUrl, code);
// Initialise REST Client
var restClient = new WebClient();
restClient.Headers.Add("Content-Type", "application/vnd.slc+json");
restClient.Headers.Add("Accept", "application/vnd.slc+json");
// Call authorization endpoint
string result = restClient.DownloadString(sessionUrl);
// Convert response into a JSON object
var response = JObject.Parse(result);
var accessToken1 = (string)response["access_token"];
var oAuthResponse = new OAuthResponse { Success = true, Message = "Authorization Successful", AccessToken = accessToken1};
// If we have a valid token, it'll be 38 chars long. Let's add it to session if so.
if (accessToken1.Length == 38)
{
var endpoint = _apiHelper.ApiUrl + "/rest/system/session/check";
var request = ApiClient.Request(endpoint, oAuthResponse.AccessToken);
if (request.ResponseObject != null)
{
JArray userInfo = request.ResponseObject;
if (userInfo.Count == 1)
{
var u = userInfo[0];
oAuthResponse.UserFullName = u["full_name"].ToString();
oAuthResponse.UserSLIRoles = from x in u["sliRoles"]
select x.Value<string>();
}
}
// Now get the User ID
oAuthResponse.UserId = GetUserId(oAuthResponse.AccessToken);
// Redirect to app main page.
return oAuthResponse;
}
}
catch (Exception ex)
{
_logger.ErrorException("Error doing OAuth login: " + ex.Message, ex);
throw;
}
return null;
}