public async Task<ActionResult> Delete(Guid id)
        {
            //check for tenantId and refresh token in session
            if (Session["TenantID"] == null || Session["RefreshToken"] == null)
                return RedirectToAction("Error", "Home", new { error = "Session expired" });
            var tenantId = Session["TenantID"].ToString();
            var refreshToken = Session["RefreshToken"].ToString();

            //use authentication context to get access token to azure graph
            AuthenticationContext context = new AuthenticationContext(string.Format("{0}/{1}", SettingsHelper.AuthorizationUri, tenantId));
            var result = await context.AcquireTokenByRefreshTokenAsync(refreshToken, new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret), SettingsHelper.AADGraphResourceId);

            ////delete the app in Azure
            //HttpClient client = new HttpClient();
            //client.DefaultRequestHeaders.Add("Authorization", "Bearer " + result.AccessToken);
            //client.DefaultRequestHeaders.Add("Accept", "application/json; odata=verbose");
            //using (HttpResponseMessage response = await client.DeleteAsync(new Uri(string.Format("https://graph.windows.net/{0}/applications?$filter=appId eq '{1}'&api-version=1.5", tenantId, id.ToString()), UriKind.Absolute)))
            //{
            //    if (response.IsSuccessStatusCode)
            //    {
            //        //delete the app in the database
            //    }
            //}

            //delete the app in the database
            using (ApplicationEntities entities = new ApplicationEntities())
            {
                var item = entities.Applications.FirstOrDefault(i => i.Id == id);
                entities.Applications.Remove(item);
                entities.SaveChanges();
            }

            return Redirect("/Application");
        }
Exemplo n.º 2
0
 private async Task<AuthenticationResult> GetAccessToken()
 {
     AuthenticationContext context = new AuthenticationContext(SettingsHelper.AzureADAuthority);
     var clientCredential = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret);
     AuthenticationResult result = (AuthenticationResult)this.Session[SettingsHelper.UserTokenCacheKey];
     return await context.AcquireTokenByRefreshTokenAsync(result.RefreshToken, clientCredential, SettingsHelper.UnifiedApiResource);
 }
Exemplo n.º 3
0
        public async Task <string> RefreshToken()
        {
            var audience = ClaimsPrincipal.Current.FindFirst("aud").Value;

            var authority   = GetAuthority(audience);
            var credential  = new Adalv2.ClientCredential(Config.InternalUsersClientId, Config.InternalUsersClientSecret);
            var authContext = new Adalv2.AuthenticationContext(authority);
            var result      = await authContext.AcquireTokenAsync(Config.InternalUsersClientId, credential);

            var res = await authContext.AcquireTokenByRefreshTokenAsync(result.RefreshToken, credential, Config.InternalUsersClientId);

            return(res.AccessToken);
        }
Exemplo n.º 4
0
 public static async Task<AuthenticationResult> GetAccessTokenFromRefreshToken(string refreshToken)
 {
     try
     {
         var authContext = new AuthenticationContext("https://login.windows.net/common", new ADALTokenCache(String.Empty));
         var clientCredential = new ClientCredential(DashConfiguration.ClientId, DashConfiguration.AppKey);
         return await authContext.AcquireTokenByRefreshTokenAsync(refreshToken, clientCredential);
     }
     catch (Exception ex)
     {
         DashTrace.TraceWarning("Error attempting to retrieve access token from refresh token. Details: {0}", ex);
     }
     return null;
 }
        internal async Task CheckToken()
        {
            if (PowerBIController.authorization == null)
                PowerBIController.authorization = await ReadTokenFromStorage();

            if (PowerBIController.authorization == null)
                return;

            if (DateTime.UtcNow.CompareTo(PowerBIController.authorization.Expires) >= 0)
            {
                AuthenticationContext AC = new AuthenticationContext("https://login.windows.net/common/oauth2/authorize/");
                ClientCredential cc = new ClientCredential(clientId, clientSecret);
                var ADALResult = await AC.AcquireTokenByRefreshTokenAsync(PowerBIController.authorization.RefreshToken, cc);
                PowerBIController.authorization = new AuthResult { Expires = ADALResult.ExpiresOn.UtcDateTime, AccessToken = ADALResult.AccessToken, RefreshToken = ADALResult.RefreshToken };
                await WriteTokenToStorage(PowerBIController.authorization);
            }
        }
        public override async Task<string> LoginAsync(bool clearCache, string authorityId, string redirectUri, string resourceId, string clientId)
        {
            var context = new AuthenticationContext(authorityId);
            var result = await context.AcquireTokenAsync(resourceId, clientId);

            // Build our token
            var token = JObject.FromObject(new
            {
                access_token = result.AccessToken,
            });

            // Request access to Azure Mobile Services
            await MobileServiceClientProvider.MobileClient.LoginAsync(MobileServiceAuthenticationProvider.WindowsAzureActiveDirectory, token);

            var authContext = new AuthenticationContext(ConfigurationHub.ReadConfigurationValue("AadAuthority"), false);

            // Get the sharepoint token
            var authenticationResult = await authContext.AcquireTokenByRefreshTokenAsync(result.RefreshToken, ConfigurationHub.ReadConfigurationValue("AadClientID"), ConfigurationHub.ReadConfigurationValue("SharePointResource"));
            State.SharePointToken = authenticationResult.AccessToken;

            return result.AccessToken;
        }
        /// <summary>
        /// Acquires an access token from the authority using a previously acquired refresh token.
        /// </summary>
        /// <param name="targetUri">
        /// The uniform resource indicator of the resource access tokens are being requested for.
        /// </param>
        /// <param name="clientId">Identifier of the client requesting the token.</param>
        /// <param name="resource">
        /// Identifier of the target resource that is the recipient of the requested token.
        /// </param>
        /// <param name="refreshToken">The <see cref="Token"/> of type <see cref="TokenType.Refresh"/>
        /// to be used to acquire the access token.</param>
        /// <returns>If successful a <see cref="TokenPair"/>; otherwise <see langword="null"/>.</returns>
        public async Task<TokenPair> AcquireTokenByRefreshTokenAsync(Uri targetUri, string clientId, string resource, Token refreshToken)
        {
            Debug.Assert(targetUri != null && targetUri.IsAbsoluteUri, "The targetUri parameter is null or invalid");
            Debug.Assert(!String.IsNullOrWhiteSpace(clientId), "The clientId parameter is null or empty");
            Debug.Assert(!String.IsNullOrWhiteSpace(resource), "The resource parameter is null or empty");
            Debug.Assert(refreshToken != null, "The refreshToken parameter is null");
            Debug.Assert(refreshToken.Type == TokenType.Refresh, "The value of refreshToken parameter is not a refresh token");
            Debug.Assert(!String.IsNullOrWhiteSpace(refreshToken.Value), "The value of refreshToken parameter is null or empty");

            TokenPair tokens = null;

            try
            {
                string authorityHostUrl = AuthorityHostUrl;

                if (refreshToken.TargetIdentity != Guid.Empty)
                {
                    authorityHostUrl = GetAuthorityUrl(refreshToken.TargetIdentity);

                    Trace.WriteLine("   authority host url set by refresh token.");
                }

                Trace.WriteLine(String.Format("   authority host url = '{0}'.", authorityHostUrl));

                AuthenticationContext authCtx = new AuthenticationContext(authorityHostUrl, _adalTokenCache);
                AuthenticationResult authResult = await authCtx.AcquireTokenByRefreshTokenAsync(refreshToken.Value, clientId, resource);
                tokens = new TokenPair(authResult);

                Trace.WriteLine("   token acquisition succeeded.");
            }
            catch (AdalException)
            {
                Trace.WriteLine("   token acquisition failed.");
            }

            return tokens;
        }
        public static async Task<AuthenticationResultProxy> ExecuteAsync(CommandProxy proxy)
        {
            AuthenticationResultProxy resultProxy = null;
            AuthenticationResult result = null;

            foreach (var command in proxy.Commands)
            {
                var arg = command.Arguments;
                switch (command.CommandType)
                {
                    case CommandType.ClearDefaultTokenCache:
                    {
                        var dummyContext = new AuthenticationContext("https://dummy/dummy", false);
                        dummyContext.TokenCache.Clear();
                        break;
                    }

                    case CommandType.SetEnvironmentVariable:
                    {
                        var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
                        localSettings.Values[arg.EnvironmentVariable] = arg.EnvironmentVariableValue;

                        break;
                    }

                    case CommandType.SetCorrelationId:
                    {
                        context.CorrelationId = arg.CorrelationId;
                        break;
                    }

                    case CommandType.CreateContextA:
                    {
                        context = new AuthenticationContext(arg.Authority);
                        break;
                    }

                    case CommandType.CreateContextAV:
                    {
                        context = new AuthenticationContext(arg.Authority, arg.ValidateAuthority);
                        break;
                    }

                    case CommandType.CreateContextAVT:
                    {
                        TokenCache tokenCache = null;
                        if (arg.TokenCacheType == TokenCacheType.InMemory)
                        {
                            tokenCache = new TokenCache()
                                         {
                                             // The default token cache in ADAL WinRT is persistent. This is how to make it in-memory only cache.
                                             BeforeAccess = delegate { },                                          
                                             AfterAccess = delegate { }                                          
                                         };
                        }

                        context = new AuthenticationContext(arg.Authority, arg.ValidateAuthority, tokenCache);
                        break;
                    }

                    case CommandType.ClearUseCorporateNetwork:
                    {
                        //context.UseCorporateNetwork = false;
                        break;
                    }

                    case CommandType.SetUseCorporateNetwork:
                    {
                        //context.UseCorporateNetwork = true;
                        break;
                    }

                    case CommandType.AquireTokenAsyncRC:
                    {
                        result = await context.AcquireTokenAsync(arg.Resource, arg.ClientId);
                        break;
                    }

                    case CommandType.AquireTokenAsyncRCUPa:
                    {
                        UserCredential credential = new UserCredential(arg.UserName);

                        result = await context.AcquireTokenAsync(arg.Resource, arg.ClientId, credential);
                        break;
                    }

                    case CommandType.AquireTokenAsyncRCRe:
                    {
                        result = await context.AcquireTokenAsync(arg.Resource, arg.ClientId, arg.RedirectUri);
                        break;
                    }

                    case CommandType.AquireTokenAsyncRCRePUX:
                    {
                        result = await context.AcquireTokenAsync(arg.Resource, arg.ClientId, arg.RedirectUri, 
                            (arg.PromptBehavior == PromptBehaviorProxy.Always) ? PromptBehavior.Always :
                            (arg.PromptBehavior == PromptBehaviorProxy.Never) ? PromptBehavior.Never : PromptBehavior.Auto,
                            (arg.UserName != null) ? new UserIdentifier(arg.UserName, UserIdentifierType.OptionalDisplayableId) : UserIdentifier.AnyUser, arg.Extra);
                        break;
                    }

                    case CommandType.AquireTokenAsyncRCReP:
                    {
                        result = await context.AcquireTokenAsync(arg.Resource, arg.ClientId, arg.RedirectUri, 
                            (arg.PromptBehavior == PromptBehaviorProxy.Always) ? PromptBehavior.Always :
                            (arg.PromptBehavior == PromptBehaviorProxy.Never) ? PromptBehavior.Never : PromptBehavior.Auto);
                        break;
                    }

                    case CommandType.AquireTokenAsyncRCRePU:
                    {
                        result = await context.AcquireTokenAsync(arg.Resource, arg.ClientId, arg.RedirectUri,                            
                            (arg.PromptBehavior == PromptBehaviorProxy.Always) ? PromptBehavior.Always :
                            (arg.PromptBehavior == PromptBehaviorProxy.Never) ? PromptBehavior.Never : PromptBehavior.Auto,
                            (arg.UserName != null) ? new UserIdentifier(arg.UserName, UserIdentifierType.OptionalDisplayableId) : UserIdentifier.AnyUser);
                        break;
                    }

                    case CommandType.AquireTokenAsyncRCP:
                    {
                        result = await context.AcquireTokenAsync(arg.Resource, arg.ClientId, 
                            (arg.PromptBehavior == PromptBehaviorProxy.Always) ? PromptBehavior.Always :
                            (arg.PromptBehavior == PromptBehaviorProxy.Never) ? PromptBehavior.Never : PromptBehavior.Auto);
                        break;
                    }

                    case CommandType.AcquireTokenByRefreshTokenAsyncRC:
                    {
                        result = await context.AcquireTokenByRefreshTokenAsync(arg.RefreshToken, arg.ClientId);
                        break;
                    }

                    case CommandType.AcquireTokenByRefreshTokenAsyncRCRe:
                    {
                        result = await context.AcquireTokenByRefreshTokenAsync(arg.RefreshToken, arg.ClientId, arg.Resource);
                        break;
                    }

                    case CommandType.CreateFromResourceUrlAsync:
                    {
                        var parameters = await AuthenticationParameters.CreateFromResourceUrlAsync(new Uri(arg.Extra));
                        resultProxy = new AuthenticationResultProxy
                                 {
                                     AuthenticationParametersAuthority = parameters.Authority,
                                     AuthenticationParametersResource = parameters.Resource
                                 };
                        break;
                    }

                    case CommandType.CreateFromResponseAuthenticateHeader:
                    {
                        var parameters = AuthenticationParameters.CreateFromResponseAuthenticateHeader(arg.Extra);
                        resultProxy = new AuthenticationResultProxy
                        {
                            AuthenticationParametersAuthority = parameters.Authority,
                            AuthenticationParametersResource = parameters.Resource
                        };
                        break;
                    }

                    /*case CommandType.AcquireTokenByRefreshTokenAsyncRCC:
                    {
                        result = await context.AcquireTokenByRefreshTokenAsync(arg.RefreshToken, arg.ClientId,
                            (arg.ClientId != null && arg.ClientSecret != null) ? new ClientCredential(arg.ClientId, arg.ClientSecret) : null);
                        break;
                    }*/

                    default:
                        throw new Exception("Unknown command");
                }
            }

            return resultProxy ?? 
                       new AuthenticationResultProxy
                       {
                           AccessToken = result.AccessToken,
                           AccessTokenType = result.AccessTokenType,
                           ExpiresOn = result.ExpiresOn,
                           IsMultipleResourceRefreshToken =
                               result.IsMultipleResourceRefreshToken,
                           RefreshToken = result.RefreshToken,
                           IdToken = result.IdToken,
                           TenantId = result.TenantId,
                           UserInfo = result.UserInfo,
                           Error = result.Error,
                           ErrorDescription = result.ErrorDescription,
                           Status =
                               (result.Status == AuthenticationStatus.Success)
                                   ? AuthenticationStatusProxy.Success
                                   : ((result.Status == AuthenticationStatus.ClientError) ? AuthenticationStatusProxy.ClientError : AuthenticationStatusProxy.ServiceError)
                       };
        }
Exemplo n.º 9
0
        protected async Task<TokenCacheInfo> GetAuthorizationResultByRefreshToken(CustomTokenCache tokenCache, TokenCacheInfo cacheInfo)
        {
            var azureEnvironment = this.AzureEnvironments;
            var authority = String.Format("{0}/{1}", Constants.AADLoginUrls[(int)azureEnvironment], cacheInfo.TenantId);
            var context = new AuthenticationContext(
                authority: authority,
                validateAuthority: true,
                tokenCache: tokenCache);

            AuthenticationResult result = await context.AcquireTokenByRefreshTokenAsync(
                    refreshToken: cacheInfo.RefreshToken,
                    clientId: Constants.AADClientId,
                    resource: cacheInfo.Resource);

            var ret = new TokenCacheInfo(cacheInfo.Resource, result);
            ret.TenantId = cacheInfo.TenantId;
            ret.DisplayableId = cacheInfo.DisplayableId;
            tokenCache.Add(ret);
            return ret;
        }
        public async Task<ActionResult> Update(Guid id)
        {
            //check for tenantId and refresh token in session
            if (Session["TenantID"] == null || Session["RefreshToken"] == null)
                return RedirectToAction("Error", "Home", new { error = "Session expired" });
            var tenantId = Session["TenantID"].ToString();
            var refreshToken = Session["RefreshToken"].ToString();

            //use authentication context to get access token to azure graph
            AuthenticationContext context = new AuthenticationContext(string.Format("{0}/{1}", SettingsHelper.AuthorizationUri, tenantId));
            var result = await context.AcquireTokenByRefreshTokenAsync(refreshToken, new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret), SettingsHelper.AADGraphResourceId);

            //get the registered app
            using (ApplicationEntities entities = new ApplicationEntities())
            {
                var tenantIdGuid = new Guid(tenantId);
                var dbApp = entities.Applications.FirstOrDefault(i => i.TenantId == tenantIdGuid && i.Id == id);
                var app = new ApplicationModel()
                {
                    CliendId = dbApp.Id,
                    Name = dbApp.Name,
                    AppOriginsFlat = dbApp.Origins,
                };
                app.AppOrigins = app.AppOriginsFlat.Split(';').ToList();

                //get the application from Azure AD to validate settings
                HttpClient client = new HttpClient();
                client.DefaultRequestHeaders.Add("Authorization", "Bearer " + result.AccessToken);
                client.DefaultRequestHeaders.Add("Accept", "application/json; odata=verbose");
                using (HttpResponseMessage response = await client.GetAsync(new Uri(string.Format("https://graph.windows.net/{0}/applications?$filter=appId eq '{1}'&api-version=1.5", tenantId, id.ToString()), UriKind.Absolute)))
                {
                    if (response.IsSuccessStatusCode)
                    {
                        var json = await response.Content.ReadAsStringAsync();
                        JObject oResponse = JObject.Parse(json);
                        var item = oResponse.SelectToken("d.results").ToObject<List<JsonApplication>>().FirstOrDefault();
                        app.SignOnURL = item.homepage;

                        //flatten the actual scopes
                        List<string> scopeIds = new List<string>();
                        foreach (var resource in item.requiredResourceAccess.results)
                        {
                            foreach (var scope in resource.resourceAccess.results)
                                scopeIds.Add(scope.id);
                        }

                        //update scopes based on what is selected
                        app.Permissions = PermissionModel.GetAllPermissions();
                        foreach (var perm in app.Permissions)
                        {
                            perm.Selected = scopeIds.Contains(perm.ScopeId.ToString());
                        }
                    }
                }

                return View(app);
            }
        }
        public async Task<ActionResult> Add(ApplicationModel application)
        {
            //check for tenantId and refresh token in session
            if (Session["TenantID"] == null || Session["RefreshToken"] == null)
                return RedirectToAction("Error", "Home", new { error = "Session expired" });
            var tenantId = Session["TenantID"].ToString();
            var refreshToken = Session["RefreshToken"].ToString();

            //use authentication context to get access token to azure graph
            AuthenticationContext context = new AuthenticationContext(string.Format("{0}/{1}", SettingsHelper.AuthorizationUri, tenantId));
            var result = await context.AcquireTokenByRefreshTokenAsync(refreshToken, new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret), SettingsHelper.AADGraphResourceId);

            //determine which scopes are selected
            List<Scopes> scopes = new List<Scopes>();
            foreach (var scope in AppScopes.ScopeIds.Keys)
            {
                if (Request[AppScopes.ScopeIds[scope]] != null)
                {
                    scopes.Add(scope);
                }
            }

            //get the domain
            var upn = ClaimsPrincipal.Current.FindFirst("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn").Value;
            upn = upn.Substring(upn.IndexOf('@') + 1);
            upn = upn.Substring(0, upn.IndexOf('.'));

            //create the application registration
            var appResult = AppRegistration.CreateWebAppRegistration(result.AccessToken, tenantId, application.Name, Request["hdnSignOnUrlPrefix"] + application.SignOnURL,
                String.Format("https://{0}.onmicrosoft.com/{1}", upn, application.Name.Replace(" ", "")), "https://easyauth.azurewebsites.net/OAuth/AuthCode", true, true, scopes);

            //Add to database
            using (ApplicationEntities entities = new ApplicationEntities())
            {
                Application app = new Application()
                {
                    Id = new Guid(appResult["client_id"]),
                    Secret = appResult["client_secret"],
                    Origins = Request["AppOriginsFlat"],
                    Name = application.Name,
                    TenantId = new Guid(tenantId)
                };
                entities.Applications.Add(app);
                entities.SaveChanges();
            }

            return Redirect("/Application");
        }
Exemplo n.º 12
0
 private async Task<AuthenticationResult> GetAccessToken(string resource, string refresh)
 {
     AuthenticationContext context = new AuthenticationContext(SettingsHelper.AzureADAuthority);
     var clientCredential = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret);
     return await context.AcquireTokenByRefreshTokenAsync(refresh, clientCredential, resource);
 }