inBloomApiLibrary.OAuth.CallAuthorization C# (CSharp) Method

CallAuthorization() public method

This function is used to check authentication of the user and gives access to api's.
public CallAuthorization ( string accessToken, string code ) : OAuthResponse
accessToken string
code string
return OAuthResponse
        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;
        }

Usage Example

Exemplo n.º 1
0
        public ActionResult Index(string code)
        {
            try
            {
                // Check for a token in the session already, and if found, no action is required
                if (!string.IsNullOrEmpty(SessionInfo.Current.AccessToken))
                    return RedirectToAction("Index", "Home");

                // Init oAuth
                var oAuth = new OAuth();

                // We get a code back from the first leg of OAuth process.  If we don't have one, let's get it.
                if (string.IsNullOrEmpty(code))
                {
                    string authorizationUrl = oAuth.GetAuthorizationUrl();
                    return Redirect(authorizationUrl);
                }

                // Otherwise, we have a code, we can run the second leg of OAuth process.
                var authorization = oAuth.CallAuthorization(null, code);

                // OAuth successful so get values, store in session and continue
                if (authorization.Success)
                {
                    // Authorization successful; set session variables
                    SessionInfo.Current.AccessToken = authorization.AccessToken;
                    SessionInfo.Current.FullName = authorization.UserFullName;
                    SessionInfo.Current.Roles = authorization.UserSLIRoles;
                    SessionInfo.Current.UserId = authorization.UserId;

                    // Redirect to post login URL if one exists
                    if (!string.IsNullOrEmpty(SessionInfo.Current.PostLoginRedirectUrl))
                    {
                        var returnUrl = SessionInfo.Current.PostLoginRedirectUrl;
                        SessionInfo.Current.PostLoginRedirectUrl = null;
                        return Redirect(returnUrl);
                    }

                    // Otherwise, just go to home
                    return RedirectToAction("Index", "Home", SessionInfo.Current.SPContextRouteValues);
                }

                return Content("Unknown Error authorizing");
            }
            catch (Exception ex)
            {
                return Content("Error authorizing: " + ex.Message);
            }
        }