//
        // The Client ID is used by the application to uniquely identify itself to Azure AD.
        // The App Key is a credential used to authenticate the application to Azure AD.  Azure AD supports password and certificate credentials.
        // The Metadata Address is used by the application to retrieve the signing keys used by Azure AD.
        // The AAD Instance is the instance of Azure, for example public Azure or Azure China.
        // The Authority is the sign-in URL of the tenant.
        // The Post Logout Redirect Uri is the URL where the user will be redirected after they sign out.
        //


        // This is the resource ID of the AAD Graph API.  We'll need this to request a token to call the Graph API.

        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());
            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
            {
                ClientId              = MediaLibraryWebApp.Configuration.ClientId,
                Authority             = MediaLibraryWebApp.Configuration.Authority,
                PostLogoutRedirectUri = MediaLibraryWebApp.Configuration.PostLogoutRedirectUri,
                Notifications         = new OpenIdConnectAuthenticationNotifications()
                {
                    //
                    // If there is a code in the OpenID Connect response, redeem it for an access token and refresh token, and store those away.
                    //
                    AuthorizationCodeReceived = (context) =>
                    {
                        var code = context.Code;
                        System.IdentityModel.Tokens.JwtSecurityToken jwtToken = context.JwtSecurityToken;
                        string userObjectID = context.AuthenticationTicket.Identity.FindFirst(MediaLibraryWebApp.Configuration.ClaimsObjectidentifier).Value;

                        Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential credential = new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential(MediaLibraryWebApp.Configuration.ClientId, MediaLibraryWebApp.Configuration.AppKey);
                        NaiveSessionCache cache           = new NaiveSessionCache(userObjectID);
                        AuthenticationContext authContext = new AuthenticationContext(MediaLibraryWebApp.Configuration.Authority, cache);
                        //Getting a token to connect with GraphApi later on userProfile page
                        AuthenticationResult graphAPiresult = authContext.AcquireTokenByAuthorizationCode(code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, MediaLibraryWebApp.Configuration.GraphResourceId);

                        //Getting a access token which can be used to configure auth restrictions for multiple tentants since audience will be same for each web app requesting this token
                        AuthenticationResult kdAPiresult = authContext.AcquireTokenByAuthorizationCode(code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, MediaLibraryWebApp.Configuration.KdResourceId);
                        string kdAccessToken             = kdAPiresult.AccessToken;

                        //Initializing  MediaServicesCredentials in order to obtain access token to be used to connect
                        var amsCredentials = new MediaServicesCredentials(MediaLibraryWebApp.Configuration.MediaAccount, MediaLibraryWebApp.Configuration.MediaKey);
                        //Forces to get access token
                        amsCredentials.RefreshToken();

                        //Adding token to a claim so it can be accessible within controller
                        context.AuthenticationTicket.Identity.AddClaim(new Claim(MediaLibraryWebApp.Configuration.ClaimsSignInJwtToken, jwtToken.RawData));

                        //Adding media services access token as claim so it can be accessible within controller
                        context.AuthenticationTicket.Identity.AddClaim(new Claim(MediaLibraryWebApp.Configuration.ClaimsAmsAcessToken, amsCredentials.AccessToken));

                        return(Task.FromResult(0));
                    }
                }
            });
        }
Пример #2
0
        protected void Page_Load(object sender, EventArgs e)
        {
            //Redirect uri must match the redirect_uri used when requesting Authorization code.
            string redirectUri = Properties.Settings.Default.RedirectUrl;
            string authorityUri = "https://login.windows.net/common/oauth2/authorize/";
           
            // Get the auth code
            string code = Request.Params.GetValues(0)[0];
            
            // Get auth token from auth code       
            TokenCache TC = new TokenCache();

            AuthenticationContext AC = new AuthenticationContext(authorityUri, TC);

            ClientCredential cc = new ClientCredential
                (Properties.Settings.Default.ClientID,
                Properties.Settings.Default.ClientSecretKey);

            AuthenticationResult AR = AC.AcquireTokenByAuthorizationCode(code, new Uri(redirectUri), cc);

            //Set Session "authResult" index string to the AuthenticationResult
            Session["authResult"] = AR;

            //Redirect back to Default.aspx
            Response.Redirect("/Default.aspx");
        }
    public ActionResult Index(string code) {

      CustomAuthenticationManager.CacheAuthenticationCode(code);
      
      ClientCredential credential = 
        new ClientCredential(DemoConstants.ClientId, DemoConstants.ClientSecret);

      string resource = DemoConstants.TargetResource;
      Uri uriReplyUrl = new Uri(DemoConstants.ClientReplyUrl);

      AuthenticationContext authenticationContext = new AuthenticationContext(DemoConstants.urlAuthorizationEndpoint);

      AuthenticationResult authenticationResult =
        authenticationContext.AcquireTokenByAuthorizationCode(
                      code,
                      uriReplyUrl,
                      credential, 
                      resource);

      CustomAuthenticationManager.CacheAuthenticationResult(authenticationResult);

      ViewBag.AuthenticationCode = code;

      return View(authenticationResult);

    }
        public ActionResult Token(string code)
        {
            var authenticationContext = new AuthenticationContext(authority);
            var tokenResult = authenticationContext.AcquireTokenByAuthorizationCode(code, new Uri(redirectUrl), new ClientCredential(clientId, clientSecret), resource);

            var accessToken = tokenResult.AccessToken;

            using (ClientContext ctx = new ClientContext(resource))
            {
                ctx.ExecutingWebRequest += (object sender, WebRequestEventArgs e) =>
                {
                    e.WebRequestExecutor.RequestHeaders.Add("Authorization", "Bearer " + accessToken);
                };

                var web = ctx.Web;
                ctx.Load(web, a => a.Title, a=>a.CurrentUser);
                ctx.ExecuteQuery();

                var title = web.Title;

                ViewBag.SiteTitle = title;
                ViewBag.LoggedUser = web.CurrentUser.Title;
                ViewBag.LoggedUserEmail = web.CurrentUser.Email;
            }

            return View("Index");
        }
 /// <summary>
 /// Acquires an IUserIdentity from Azure Active Directory using the argument authorizationCode.
 /// </summary>
 /// <param name="authorizationCode">An authorization code provided by Azure Active Directory used to retrieve an IUserIdentity</param>
 /// <returns>Returns an IUserIdentity representing a successfully authenticated Azure Active Directory user who has privileges for this configured application</returns>
 public static IUserIdentity GetAuthenticatedUserIDentity(string authorizationCode)
 {
     var authenticationContext = new AuthenticationContext(string.Format("https://login.windows.net/{0}", AAD.TENANT_ID));
     var clientCredential      = new ClientCredential(AAD.CLIENT_ID, AAD.CLIENT_KEY);
     var authenticationResult  = authenticationContext.AcquireTokenByAuthorizationCode(authorizationCode, new Uri(AAD.REPLY_URL), clientCredential);
     return new UserIdentity(authenticationResult.UserInfo);
 }
Пример #6
0
    public void ConfigureAuth(IAppBuilder app) {
      app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
      app.UseCookieAuthentication(new CookieAuthenticationOptions());

      app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions {
        ClientId = SettingsHelper.ClientId,
        Authority = SettingsHelper.AzureADAuthority,
        Notifications = new OpenIdConnectAuthenticationNotifications() {
          AuthorizationCodeReceived = (context) => {
            string code = context.Code;

            ClientCredential creds = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret);
            string userObjectId = context.AuthenticationTicket.Identity.FindFirst(System.IdentityModel.Claims.ClaimTypes.NameIdentifier).Value;

            EFADALTokenCache cache = new EFADALTokenCache(userObjectId);
            AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.AzureADAuthority, cache);

            Uri redirectUri = new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path));
            AuthenticationResult authResult = authContext.AcquireTokenByAuthorizationCode(code, redirectUri, creds, SettingsHelper.AzureAdGraphResourceId);

            return Task.FromResult(0);
          },
          AuthenticationFailed = (context) => {
            context.HandleResponse();
            return Task.FromResult(0);
          }
        },
        TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters {
          ValidateIssuer = false
        }
      });
    }
        public void ConfigureAuth(IAppBuilder app)
        {
            ApplicationDbContext db = new ApplicationDbContext();

            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
                {
                    ClientId = clientId,
                    Authority = Authority,
                    PostLogoutRedirectUri = postLogoutRedirectUri,

                    Notifications = new OpenIdConnectAuthenticationNotifications()
                    {
                        // If there is a code in the OpenID Connect response, redeem it for an access token and refresh token, and store those away.
                        AuthorizationCodeReceived = (context) =>
                        {
                            var code = context.Code;
                            ClientCredential credential = new ClientCredential(clientId, appKey);
                            string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
                            AuthenticationContext authContext = new AuthenticationContext(Authority, new ADALTokenCache(signedInUserID));
                            AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(
                            code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, graphResourceId);

                            return Task.FromResult(0);
                        }
                    }
                });
        }
        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            //Configure OpenIDConnect, register callbacks for OpenIDConnect Notifications
            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
                {
                    ClientId = ConfigHelper.ClientId,
                    Authority = ConfigHelper.Authority,
                    PostLogoutRedirectUri = ConfigHelper.PostLogoutRedirectUri,
                    Notifications = new OpenIdConnectAuthenticationNotifications
                    {
                        AuthorizationCodeReceived = context =>
                        {
                            ClientCredential credential = new ClientCredential(ConfigHelper.ClientId, ConfigHelper.AppKey);
                            string userObjectId = context.AuthenticationTicket.Identity.FindFirst(Globals.ObjectIdClaimType).Value;
                            AuthenticationContext authContext = new AuthenticationContext(ConfigHelper.Authority, new TokenDbCache(userObjectId));
                            AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(
                                context.Code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, ConfigHelper.GraphResourceId);

                            return Task.FromResult(0);
                        },

                        AuthenticationFailed = context =>
                        {
                            context.HandleResponse();
                            context.Response.Redirect("/Error/ShowError?signIn=true&errorMessage=" + context.Exception.Message);
                            return Task.FromResult(0);
                        }
                    }
                });
        }
        public AssociationStatusEnum Associate(string state, string code, Uri requestUri)
        {
            ClientCredential clientCredential = new ClientCredential(Constants.ClientId, Constants.ClientKey);
            AuthenticationContext context = new AuthenticationContext("https://login.windows.net/common/");
            AuthenticationResult result = context.AcquireTokenByAuthorizationCode(code, requestUri, clientCredential);

            return ConvertTemporaryTenantToPermanentTenant(state, result.TenantId);
        }
Пример #10
0
        public void ConfigureAuth(IAppBuilder app)
        {
            
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());
            //app.UseCookieAuthentication(new CookieAuthenticationOptions {
            //    CookieManager = new Components.SystemWebCookieManager()
            //});

            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
                {
                    ClientId = MSGraphAPISettings.ClientId,
                    Authority = MSGraphAPISettings.AADInstance + "common",
                    TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
                    {
                        // instead of using the default validation (validating against a single issuer value, as we do in line of business apps), 
                        // we inject our own multitenant validation logic
                        ValidateIssuer = false,
                    },
                    Notifications = new OpenIdConnectAuthenticationNotifications()
                    {
                        SecurityTokenValidated = (context) => 
                        {
                            return Task.FromResult(0);
                        },
                        AuthorizationCodeReceived = (context) =>
                        {
                            var code = context.Code;

                            ClientCredential credential = new ClientCredential(
                                MSGraphAPISettings.ClientId,
                                MSGraphAPISettings.ClientSecret);
                            string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(
                                ClaimTypes.NameIdentifier).Value;
                            string tenantId = context.AuthenticationTicket.Identity.FindFirst(
                                "http://schemas.microsoft.com/identity/claims/tenantid").Value;

                            AuthenticationContext authContext = new AuthenticationContext(
                                MSGraphAPISettings.AADInstance + tenantId,
                                new SessionADALCache(signedInUserID));
                            AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(
                                code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)),
                                credential, MSGraphAPISettings.MicrosoftGraphResourceId);

                            return Task.FromResult(0);
                        },
                        AuthenticationFailed = (context) =>
                        {
                            context.OwinContext.Response.Redirect("/Home/Error?message=" + context.Exception.Message);
                            context.HandleResponse(); // Suppress the exception
                            return Task.FromResult(0);
                        }
                    }
                });

        }
		// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
		public void ConfigureAuth(IAppBuilder app)
		{
			//app.UseWindowsAzureActiveDirectoryBearerAuthentication(
			//	new WindowsAzureActiveDirectoryBearerAuthenticationOptions
			//	{
			//		Audience = ConfigurationManager.AppSettings["ida:Audience"],
			//		Tenant = ConfigurationManager.AppSettings["ida:Tenant"],

			//	});

			

			app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

			app.UseCookieAuthentication(new CookieAuthenticationOptions());

			app.UseOpenIdConnectAuthentication(
				new OpenIdConnectAuthenticationOptions
				{
					ClientId = clientId,
					Authority = Authority,
					//PostLogoutRedirectUri = postLogoutRedirectUri,
					Notifications = new OpenIdConnectAuthenticationNotifications()
					{
						//
						// If there is a code in the OpenID Connect response, redeem it for an access token and refresh token, and store those away.
						//
						AuthorizationCodeReceived = (context) =>
						{
							var code = context.Code;

							ClientCredential credential = new ClientCredential(clientId, appKey);
							string userObjectID = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
							AuthenticationContext authContext = new AuthenticationContext(Authority, new NaiveSessionCache(userObjectID));
							//AuthenticationContext authContext = new AuthenticationContext(Authority);
							//AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, graphResourceId);
							//AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential);

							//string todoListBaseAddress = ConfigurationManager.AppSettings["todo:TodoListBaseAddress"];
							
							AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, serviceResourceId);


							return Task.FromResult(0);
						},

						AuthenticationFailed = context =>
						{
							context.HandleResponse();
							context.Response.Redirect("/Home/Error?message=" + context.Exception.Message);
							return Task.FromResult(0);
						}

					}

				});
		}
        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                //Implement our own cookie manager to work around the infinite
                //redirect loop issue
                CookieManager = new SystemWebCookieManager()
            });

            string clientID = ConfigurationManager.AppSettings["ida:ClientID"];
            string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
            string tenant = ConfigurationManager.AppSettings["ida:Tenant"];
            string clientSecret = ConfigurationManager.AppSettings["ida:AppKey"];
            string graphResourceID = ConfigurationManager.AppSettings["ida:GraphResourceID"];

            string authority = string.Format(CultureInfo.InvariantCulture, aadInstance, tenant);

            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
                {
                    ClientId = clientID,
                    Authority = authority,

                    Notifications = new OpenIdConnectAuthenticationNotifications()
                    {
                        // when an auth code is received...
                        AuthorizationCodeReceived = (context) =>
                        {
                            // get the OpenID Connect code passed from Azure AD on successful auth
                            string code = context.Code;

                            // create the app credentials & get reference to the user
                            ClientCredential creds = new ClientCredential(clientID, clientSecret);
                            string signInUserId = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;

                            // use the OpenID Connect code to obtain access token & refresh token...
                            //  save those in a persistent store...
                            AuthenticationContext authContext = new AuthenticationContext(authority, new ADALTokenCache(signInUserId));

                            // obtain access token for the AzureAD graph
                            Uri redirectUri = new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path));
                            AuthenticationResult authResult = authContext.AcquireTokenByAuthorizationCode(code, redirectUri, creds, graphResourceID);

                            // successful auth
                            return Task.FromResult(0);
                        },
                        AuthenticationFailed = (context) =>
                        {
                            context.HandleResponse();
                            return Task.FromResult(0);
                        }
                    }

                });
        }
Пример #13
0
 private Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification notification)
 {
     ClientCredential credential = new ClientCredential(ConfigHelper.ClientId, ConfigHelper.AppKey);
     string userObjectId = notification.AuthenticationTicket.Identity.FindFirst(Globals.ObjectIdClaimType).Value;
     string tenantId = notification.AuthenticationTicket.Identity.FindFirst(Globals.TenantIdClaimType).Value;
     AuthenticationContext authContext = new AuthenticationContext(String.Format(CultureInfo.InvariantCulture, ConfigHelper.AadInstance, tenantId), new TokenDbCache(userObjectId));
     AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(
         notification.Code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority)), credential, ConfigHelper.GraphResourceId);
     return Task.FromResult(0);
 }
Пример #14
0
        public void ConfigureAuth(IAppBuilder app)
        {
            ApplicationDbContext db = new ApplicationDbContext();

            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
                {
                    ClientId = clientId,
                    Authority = Authority,
                    PostLogoutRedirectUri = postLogoutRedirectUri,

                    Notifications = new OpenIdConnectAuthenticationNotifications()
                    {
                        // If there is a code in the OpenID Connect response, redeem it for an access token and refresh token, and store those away.
                       AuthorizationCodeReceived = (context) =>
                       {
                           var code = context.Code;
                           ClientCredential credential = new ClientCredential(clientId, appKey);
                           string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
                           AuthenticationContext authContext = new AuthenticationContext(Authority, new ADALTokenCache(signedInUserID));
                           AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(
                               code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, graphResourceId);

                           // added by [email protected] to the original template
                           // Getting KeyDelivery Access Token
                           AuthenticationResult kdAPiresult = authContext.AcquireTokenByAuthorizationCode(
                               code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, kdResourceId);
                           string kdAccessToken = kdAPiresult.AccessToken;
                           System.IdentityModel.Tokens.JwtSecurityToken kdAccessJwtToken = new System.IdentityModel.Tokens.JwtSecurityToken(kdAccessToken);

                           //context.AuthenticationTicket.Identity.AddClaim(
                           //    new System.Security.Claims.Claim("KdAccessJwtSecurityTokenClaim", kdAccessJwtToken.RawData));
                           // added by [email protected] to the original template

                           return Task.FromResult(0);
                       }
                    }
                });
        }
Пример #15
0
        //
        // The Client ID is used by the application to uniquely identify itself to Azure AD.
        // The App Key is a credential used to authenticate the application to Azure AD.  Azure AD supports password and certificate credentials.
        // The Metadata Address is used by the application to retrieve the signing keys used by Azure AD.
        // The AAD Instance is the instance of Azure, for example public Azure or Azure China.
        // The Authority is the sign-in URL of the tenant.
        // The Post Logout Redirect Uri is the URL where the user will be redirected after they sign out.
        //
        // This is the resource ID of the AAD Graph API.  We'll need this to request a token to call the Graph API.
        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());
            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
                {
                    ClientId = MediaLibraryWebApp.Configuration.ClientId,
                    Authority = MediaLibraryWebApp.Configuration.Authority,
                    PostLogoutRedirectUri = MediaLibraryWebApp.Configuration.PostLogoutRedirectUri,

                    Notifications = new OpenIdConnectAuthenticationNotifications()
                    {
                        //
                        // If there is a code in the OpenID Connect response, redeem it for an access token and refresh token, and store those away.
                        //
                        AuthorizationCodeReceived = (context) =>
                        {
                            var code = context.Code;
                            System.IdentityModel.Tokens.JwtSecurityToken jwtToken = context.JwtSecurityToken;

                            string userObjectID = context.AuthenticationTicket.Identity.FindFirst(MediaLibraryWebApp.Configuration.ClaimsObjectidentifier).Value;

                            Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential credential = new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential(MediaLibraryWebApp.Configuration.ClientId, MediaLibraryWebApp.Configuration.AppKey);

                            NaiveSessionCache cache = new NaiveSessionCache(userObjectID);
                            AuthenticationContext authContext = new AuthenticationContext(MediaLibraryWebApp.Configuration.Authority, cache);

                            //Getting a token to connect with GraphApi later on userProfile page
                            AuthenticationResult graphAPiresult = authContext.AcquireTokenByAuthorizationCode(code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, MediaLibraryWebApp.Configuration.GraphResourceId);

                            //Getting a access token which can be used to configure auth restrictions for multiple tentants since audience will be same for each web app requesting this token
                            //AuthenticationResult kdAPiresult = authContext.AcquireTokenByAuthorizationCode(code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, MediaLibraryWebApp.Configuration.KdResourceId);

                            //string kdAccessToken = kdAPiresult.AccessToken;

                            //Initializing  MediaServicesCredentials in order to obtain access token to be used to connect
                            var amsCredentials = new MediaServicesCredentials(MediaLibraryWebApp.Configuration.MediaAccount, MediaLibraryWebApp.Configuration.MediaKey);
                            //Forces to get access token
                            amsCredentials.RefreshToken();

                            //Adding token to a claim so it can be accessible within controller
                            context.AuthenticationTicket.Identity.AddClaim(new Claim(MediaLibraryWebApp.Configuration.ClaimsSignInJwtToken, jwtToken.RawData));

                            //Adding media services access token as claim so it can be accessible within controller
                            context.AuthenticationTicket.Identity.AddClaim(new Claim(MediaLibraryWebApp.Configuration.ClaimsAmsAcessToken, amsCredentials.AccessToken));

                            return Task.FromResult(0);
                        }

                    }

                });
        }
Пример #16
0
        protected void Page_Load(object sender, EventArgs e)
        {
            String code = Request["code"];
            String error = Request["error"];
            String error_description = Request["error_description"];
            String resource = Request["resource"];
            String state = Request["state"];

            // Is this a response to a request we generated? Let's see if the state is carrying an ID we previously saved
            // ---if we don't, return an error            
            if (db.Tenants.FirstOrDefault(a => a.IssValue == state) == null)
            {
                failedOnBoarding.Visible = true;
                errorMessage.Text = error_description;
                errorDescription.Text = error_description;
            }
            else
            {
                successedOnBoarding.Visible = true;

                // ---if the response is indeed from a request we generated
                // ------get a token for the Graph, that will provide us with information abut the caller
                ClientCredential credential = new ClientCredential(AuthenticationHelper.ClientId, AuthenticationHelper.SharedSecret);

                AuthenticationContext authContext = new AuthenticationContext(AuthenticationHelper.AuthorityMultitenant);
                AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(
                    code, new Uri(Request.Url.GetLeftPart(UriPartial.Path)), credential);

                var myTenant = db.Tenants.FirstOrDefault(a => a.IssValue == state);
                // if this was an admin consent, save the tenant
                if (myTenant.AdminConsented)
                {
                    // ------read the tenantID out of the Graph token and use it to create the issuer string
                    string issuer = String.Format("https://sts.windows.net/{0}/", result.TenantId);
                    myTenant.IssValue = issuer;
                }
                else
                //otherwise, remove the temporary entry and save just the user
                {
                    if (db.Users.FirstOrDefault(a => (a.UPN == result.UserInfo.DisplayableId) && (a.TenantID == result.TenantId)) == null)
                    {
                        db.Users.Add(new User { UPN = result.UserInfo.DisplayableId, TenantID = result.TenantId });
                    }
                    db.Tenants.Remove(myTenant);
                }

                // remove older, unclaimed entries
                DateTime tenMinsAgo = DateTime.Now.Subtract(new TimeSpan(0, 10, 0)); // workaround for Linq to entities
                var garbage = db.Tenants.Where(a => (!a.IssValue.StartsWith("https") && (a.Created < tenMinsAgo)));
                foreach (Tenant t in garbage)
                    db.Tenants.Remove(t);

                db.SaveChanges();
            }
        }
        public ActionResult CatchCode(string code)
        {
            AuthenticationContext ac = new AuthenticationContext(string.Format("https://login.windows.net/{0}",
                                          ClaimsPrincipal.Current.FindFirst(TenantIdClaimType).Value));

            ClientCredential clcred = new ClientCredential(AppPrincipalId, AppKey);

            var ar = ac.AcquireTokenByAuthorizationCode(code,
                           new Uri("https://localhost:44306/Home/CatchCode"), clcred);
            return View();
        }
        /// <summary>
        /// Configures OpenIDConnect Authentication & Adds Custom Application Authorization Logic on User Login.
        /// </summary>
        /// <param name="app">The application represented by a <see cref="IAppBuilder"/> object.</param>
        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            //Configure OpenIDConnect, register callbacks for OpenIDConnect Notifications
            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
                {
                    ClientId = ConfigHelper.ClientId,
                    //Authority = String.Format(CultureInfo.InvariantCulture, ConfigHelper.AadInstance, ConfigHelper.Tenant), // For Single-Tenant
                    Authority = ConfigHelper.CommonAuthority, // For Multi-Tenant
                    PostLogoutRedirectUri = ConfigHelper.PostLogoutRedirectUri,

                    // Here, we've disabled issuer validation for the multi-tenant sample.  This enables users
                    // from ANY tenant to sign into the application (solely for the purposes of allowing the sample
                    // to be run out-of-the-box.  For a real multi-tenant app, reference the issuer validation in 
                    // WebApp-MultiTenant-OpenIDConnect-DotNet.  If you're running this sample as a single-tenant
                    // app, you can delete the ValidateIssuer property below.
                    TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
                    {
                        ValidateIssuer = false, // For Multi-Tenant Only
                        RoleClaimType = "roles",
                    },

                    Notifications = new OpenIdConnectAuthenticationNotifications
                    {
                        AuthorizationCodeReceived = context =>
                        {
                            // Get Access Token for User's Directory
                            string userObjectId = context.AuthenticationTicket.Identity.FindFirst(Globals.ObjectIdClaimType).Value;
                            string tenantId = context.AuthenticationTicket.Identity.FindFirst(Globals.TenantIdClaimType).Value;
                            ClientCredential credential = new ClientCredential(ConfigHelper.ClientId, ConfigHelper.AppKey);
                            AuthenticationContext authContext = new AuthenticationContext(
                                String.Format(CultureInfo.InvariantCulture, ConfigHelper.AadInstance, tenantId),
                                new TokenDbCache(userObjectId));
                            AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(
                                context.Code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)),
                                credential, ConfigHelper.GraphResourceId);

                            return Task.FromResult(0);
                        },

                        AuthenticationFailed = context =>
                        {
                            context.HandleResponse();
                            context.Response.Redirect("/Error/ShowError?signIn=true&errorMessage=" + context.Exception.Message);
                            return Task.FromResult(0);
                        }
                    }
                });
        }
Пример #19
0
        private AuthenticationResult GetAccessTokenFromCode(string code)
        {
            Config c = new Config();

            Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext context =
                new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(c.GetValue("authority"));
            AuthenticationResult result = context.AcquireTokenByAuthorizationCode(code,
                                                                                  new Uri(c.GetValue("redirectUri")),
                                                                                  new ClientCredential(c.GetValue("clientId"), c.GetValue("clientSecret")),
                                                                                  c.GetValue("resource"));

            return(result);
        }
Пример #20
0
		public void ConfigureAuth(IAppBuilder app)
		{
			app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

			app.UseCookieAuthentication(new CookieAuthenticationOptions());


			app.UseOpenIdConnectAuthentication(
				new OpenIdConnectAuthenticationOptions
				{
					ClientId = SettingsHelper.ClientId,
					Authority = SettingsHelper.Authority,

					Notifications = new OpenIdConnectAuthenticationNotifications()
					{
						// If there is a code in the OpenID Connect response, redeem it for an access token and refresh token, and store those away.
						AuthorizationCodeReceived = (context) =>
						{
							var code = context.Code;
							ClientCredential credential = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.AppKey);
							String signInUserId = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;

							AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.Authority, new ADALTokenCache(signInUserId));
							AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(
																							code, 
																							new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), 
																							credential, SettingsHelper.MSGraphResource);

							return Task.FromResult(0);
						},
						RedirectToIdentityProvider = (context) =>
						{
							// This ensures that the address used for sign in and sign out is picked up dynamically from the request
							// this allows you to deploy your app (to Azure Web Sites, for example)without having to change settings
							// Remember that the base URL of the address used here must be provisioned in Azure AD beforehand.
							string appBaseUrl = context.Request.Scheme + "://" + context.Request.Host + context.Request.PathBase;
							context.ProtocolMessage.RedirectUri = appBaseUrl + "/";
							context.ProtocolMessage.PostLogoutRedirectUri = appBaseUrl;

							return Task.FromResult(0);
						},
						AuthenticationFailed = (context) =>
						{
							// Suppress the exception if you don't want to see the error
							context.HandleResponse();
							return Task.FromResult(0);
						}
					}

				});
		}
         // GET: /TOnboarding/ProcessCode
        public ActionResult ProcessCode(string code, string error, string error_description, string resource, string state)
        {
            // Is this a response to a request we generated? Let's see if the state is carrying an ID we previously saved
            // ---if we don't, return an error            
            if (db.Tenants.FirstOrDefault(a => a.IssValue == state) == null)
            {
                // TODO: prettify
                return View("Error");
            }
            else
            {
                // ---if the response is indeed from a request we generated
                // ------get a token for the Graph, that will provide us with information abut the caller
                ClientCredential credential = new ClientCredential(ConfigurationManager.AppSettings["ida:ClientID"],
                                                                   ConfigurationManager.AppSettings["ida:Password"]);
                string Authority = string.Format("{0}/{1}",
                    ConfigurationManager.AppSettings["SignOnEndpoint"],
                    ConfigurationManager.AppSettings["ida:TenantId"]);
                AuthenticationContext authContext = new AuthenticationContext(Authority);
                AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(
                    code, new Uri(Request.Url.GetLeftPart(UriPartial.Path)), credential);

                var myTenant = db.Tenants.FirstOrDefault(a => a.IssValue == state);
                // if this was an admin consent, save the tenant
                if (myTenant.AdminConsented)
                {
                    // ------read the tenantID out of the Graph token and use it to create the issuer string
                    string issuer = String.Format("{0}/{1}/", ConfigurationManager.AppSettings["SecurityTokenServiceEndpoint"], result.TenantId);
                    myTenant.IssValue = issuer;
                }
                else
                //otherwise, remove the temporary entry and save just the user
                {
                    if (db.Users.FirstOrDefault(a => (a.UPN == result.UserInfo.DisplayableId) && (a.TenantID == result.TenantId)) == null)
                    {
                        db.Users.Add(new User { UPN = result.UserInfo.DisplayableId, TenantID = result.TenantId });
                    }
                    db.Tenants.Remove(myTenant);
                }

                // remove older, unclaimed entries
                DateTime tenMinsAgo = DateTime.Now.Subtract(new TimeSpan(0, 10, 0)); // workaround for Linq to entities
                var garbage = db.Tenants.Where(a => (!a.IssValue.StartsWith("https") && (a.Created < tenMinsAgo)));
                foreach (Tenant t in garbage)
                    db.Tenants.Remove(t);

                db.SaveChanges();
                // ------return a view claiming success, inviting the user to sign in
                return View();
            }
        }
Пример #22
0
        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            //configure the OWIN OpenID Connect options
            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                ClientId      = SettingsHelper.ClientId,
                Authority     = SettingsHelper.AzureADAuthority,
                Notifications = new OpenIdConnectAuthenticationNotifications()
                {
                    // when an auth code is received
                    AuthorizationCodeReceived = (context) =>
                    {
                        // get the openid connect code passed from azure ad on a successful auth
                        string code = context.Code;

                        // create app cred & get the user
                        ClientCredential creds = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret);
                        string userObjectId    =
                            context.AuthenticationTicket.Identity.FindFirst(System.IdentityModel.Claims.ClaimTypes.NameIdentifier)
                            .Value;

                        // get access & refresh token
                        EFADALTokenCache cache            = new EFADALTokenCache(userObjectId);
                        AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.AzureADAuthority,
                                                                                      cache);

                        // obtain access token for the azure ad graph
                        Uri redirectUri = new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path));
                        AuthenticationResult authResult = authContext.AcquireTokenByAuthorizationCode(
                            code, redirectUri, creds, SettingsHelper.AzureAdGraphResourceId);

                        // success auth
                        return(Task.FromResult(0));
                    },
                    AuthenticationFailed = (context) =>
                    {
                        context.HandleResponse();
                        return(Task.FromResult(0));
                    }
                },
                TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateIssuer = false
                }
            });
        }
        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
              app.UseCookieAuthentication(new CookieAuthenticationOptions());

              //configure the OWIN OpenID Connect options
              app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
              {
            ClientId = SettingsHelper.ClientId,
            Authority = SettingsHelper.AzureADAuthority,
            Notifications = new OpenIdConnectAuthenticationNotifications()
            {
              // when an auth code is received
              AuthorizationCodeReceived = (context) =>
              {
            // get the openid connect code passed from azure ad on a successful auth
            string code = context.Code;

            // create app cred & get the user
            ClientCredential creds = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret);
            string userObjectId =
              context.AuthenticationTicket.Identity.FindFirst(System.IdentityModel.Claims.ClaimTypes.NameIdentifier)
                .Value;

            // get access & refresh token
            EFADALTokenCache cache = new EFADALTokenCache(userObjectId);
            AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.AzureADAuthority,
                                                      cache);

            // obtain access token for the azure ad graph
            Uri redirectUri = new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path));
            AuthenticationResult authResult = authContext.AcquireTokenByAuthorizationCode(
              code, redirectUri, creds, SettingsHelper.AzureAdGraphResourceId);

            // success auth
            return Task.FromResult(0);
              },
              AuthenticationFailed = (context) =>
              {
            context.HandleResponse();
            return Task.FromResult(0);
              }
            },
            TokenValidationParameters = new TokenValidationParameters()
            {
              ValidateIssuer = false
            }
              });
        }
Пример #24
0
        public void ConfigureAuth(IAppBuilder app)
        {
            #region WebAPI
            app.UseWindowsAzureActiveDirectoryBearerAuthentication(
                new WindowsAzureActiveDirectoryBearerAuthenticationOptions
            {
                Tenant = tenant,
                TokenValidationParameters = new TokenValidationParameters
                {
                    ValidAudience      = resourceId,
                    AuthenticationType = "OAuth2Bearer"
                },
            });
            #endregion

            #region Web-based login
            ApplicationDbContext db = new ApplicationDbContext();

            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
            {
                ClientId              = clientId,
                Authority             = Authority,
                PostLogoutRedirectUri = postLogoutRedirectUri,

                Notifications = new OpenIdConnectAuthenticationNotifications()
                {
                    // If there is a code in the OpenID Connect response, redeem it for an access token and refresh token, and store those away.
                    AuthorizationCodeReceived = (context) =>
                    {
                        var code = context.Code;
                        ClientCredential credential = new ClientCredential(clientId, appKey);
                        string signedInUserID       = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
                        Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext authContext =
                            new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(Authority, new ADALTokenCache(signedInUserID));
                        AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(
                            code, new System.Uri(System.Web.HttpContext.Current.Request.Url.GetLeftPart(System.UriPartial.Path)), credential, graphResourceId);

                        return(System.Threading.Tasks.Task.FromResult(0));
                    }
                }
            });
            #endregion
        }
Пример #25
0
        public Tokens GetTokens(Client client, ClientSecret clientSecret, Token token, string redirectUri)
        {
            var tokenCache = new TokenCache();

            var authenticationContext = new AuthenticationContext(AuthorityUri, tokenCache);
            var clientCredential = new ClientCredential(client, clientSecret);

            var result = authenticationContext.AcquireTokenByAuthorizationCode(token, new Uri(redirectUri), clientCredential);
            var tokens = new Tokens
            {
                AccessToken = result.AccessToken,
                RefreshToken = result.RefreshToken,
                ExpiresOn = result.ExpiresOn
            };
            return tokens;
        }
Пример #26
0
        /// <summary>
        /// WEBAPP and WEBAPI are in a different AAD APP
        /// Use this method if this app is protected by ADD-Application: CalcEnterpriseClient
        /// Authenticate by requesting a bearer token for the user and the backend service
        /// CalcEnterpriseAPI app => (IMPERSONATION - Webapi will have Caller Details in Claims not just Service Principal)!
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public ActionResult Index_OtherAAD(string code)
        {
            SessionTalk[] contacts      = null;
            string        _ClientID     = "<CalcEnterpriseClient AAD CLientID>";       // CalcEnterpriseClient - Client ID
            string        _ClientSecret = "<CalcEnterpriseClient AAD App Secret/Key>"; // CalcEnterpriseClient - Client Secret
            string        _Ressource    = "<CalcEnterpriseAPI AAD CLientID>";          // CalcEnterpriseAPI - Client ID to be used if we call from middle tier!

            if (String.IsNullOrEmpty(code))
            {
                string authorizationUrl = string.Format(
                    "https://login.windows.net/{0}/oauth2/authorize?" +
                    "api-version=1.0&" +
                    "response_type=code&" +
                    "client_id={1}&" +
                    "resource={2}&" +
                    "redirect_uri={3}",
                    ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value,
                    _ClientID,
                    _Ressource,
                    Request.Url.ToString()
                    );
                return(new RedirectResult(authorizationUrl));
            }
            else
            {
                Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext ac =
                    new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(string.Format("https://login.windows.net/{0}",
                                                                                                            ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value));

                ClientCredential clcred =
                    new ClientCredential(_ClientID, _ClientSecret);

                var ar = ac.AcquireTokenByAuthorizationCode(code,
                                                            new Uri(Request.Url.ToString().Replace(Request.Url.Query, "")), clcred);

                using (HttpClient client = new HttpClient())
                {
                    client.BaseAddress = new
                                         Uri(C_BASE_SERVICE_URI);
                    client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", C_CALC_API_SUBSCRIPTION_KEY);
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(ar.AccessTokenType, ar.AccessToken);
                    var json = client.GetStringAsync(C_SERVICE_PATH).Result;
                    contacts = JsonConvert.DeserializeObject <SessionTalk[]>(json);
                }
                return(View(contacts));
            }
        }
Пример #27
0
        public void ConfigureAuth(IAppBuilder app)
        {
            ApplicationDbContext db = new ApplicationDbContext();

            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            OpenIdConnectAuthenticationOptions options = new OpenIdConnectAuthenticationOptions();
            options.ClientId = SettingsHelper.ClientId;
            options.Authority = SettingsHelper.AzureADAuthority;
            options.PostLogoutRedirectUri = SettingsHelper.LogoutAuthority;

            OpenIdConnectAuthenticationNotifications notifications = new OpenIdConnectAuthenticationNotifications();
            notifications.AuthorizationCodeReceived = (context) =>
            {
                string code = context.Code;

                AuthenticationHelper authHelper = new AuthenticationHelper();
                
                String signInUserId = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;

                AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.AzureADAuthAuthority);
                AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), authHelper.GetClientAssertionCertificate(), null);

                return Task.FromResult(0);
            };

            notifications.RedirectToIdentityProvider = (context) =>
            {
                string appBaseUrl = context.Request.Scheme + "://" + context.Request.Host + context.Request.PathBase;
                context.ProtocolMessage.RedirectUri = appBaseUrl + "/";
                context.ProtocolMessage.PostLogoutRedirectUri = appBaseUrl;

                return Task.FromResult(0);
            };

            notifications.AuthenticationFailed = (context) =>
            {
                context.HandleResponse();
                return Task.FromResult(0);
            };

            options.Notifications = notifications;

            app.UseOpenIdConnectAuthentication(options);
        }
        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); 
            app.UseCookieAuthentication(new CookieAuthenticationOptions()); 
            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                ClientId = SettingsHelper.ClientId,
                Authority = SettingsHelper.AzureADAuthority,
                Notifications = new OpenIdConnectAuthenticationNotifications()
                {
                    AuthorizationCodeReceived = (context) =>
                    {
                        var code = context.Code;
                        var creds = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret); 
                        var userObjectId = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
                        //var tokenCache = new NaiveSessionCache(userObjectId);
                        var tokenCache = new EFADALTokenCache(userObjectId);

                        var authContext = new AuthenticationContext(SettingsHelper.AzureADAuthority, tokenCache);
                        var redirectUri = new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path));
                        var authResult = authContext.AcquireTokenByAuthorizationCode(
                            code, redirectUri, creds, SettingsHelper.GraphResourceId); 
                        return Task.FromResult(0);
                    },
                    AuthenticationFailed = (context) =>
                    {
                        context.HandleResponse();
                        return Task.FromResult(0);
                    },
                    RedirectToIdentityProvider = (context) =>
                    {
                        // This ensures that the address used for sign in and sign out is picked up dynamically from the request
                        // this allows you to deploy your app (to Azure Web Sites, for example) without having to change settings
                        // Remember that the base URL of the address used here must be provisioned in Azure AD beforehand.
                        string appBaseUrl = context.Request.Scheme + "://" + context.Request.Host + context.Request.PathBase;
                        context.ProtocolMessage.RedirectUri = appBaseUrl + "/";
                        context.ProtocolMessage.PostLogoutRedirectUri = appBaseUrl;

                        return Task.FromResult(0);
                    }
                },
                TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
                {
                    ValidateIssuer = false
                }
            });
        }
Пример #29
0
        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
                {
                    ClientId = clientId,
                    Authority = authority,
                    TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
                    {
                        // instead of using the default validation (validating against a single issuer value, as we do in line of business apps), 
                        // we inject our own multitenant validation logic
                        ValidateIssuer = false,
                    },
                    Notifications = new OpenIdConnectAuthenticationNotifications()
                    {
                        AuthorizationCodeReceived = (context) =>
                        {
                            var code = context.Code;

                            ClientCredential credential = new ClientCredential(clientId, appKey);
                            string tenantID = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
                            string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;

                            AuthenticationContext authContext = new AuthenticationContext(aadInstance + tenantID, new NaiveSessionCache(signedInUserID));
                            AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(
                                code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, asaResourceId);

                            return Task.FromResult(0);
                        },
                        RedirectToIdentityProvider = (context) =>
                        {
                            // This ensures that the address used for sign in and sign out is picked up dynamically from the request
                            // this allows you to deploy your app (to Azure Web Sites, for example)without having to change settings
                            // Remember that the base URL of the address used here must be provisioned in Azure AD beforehand.
                            string appBaseUrl = context.Request.Scheme + "://" + context.Request.Host + context.Request.PathBase;
                            context.ProtocolMessage.RedirectUri = appBaseUrl + "/";
                            context.ProtocolMessage.PostLogoutRedirectUri = appBaseUrl;
                            return Task.FromResult(0);
                        },
                    }
                });
        }
Пример #30
0
        public void ConfigureAuth(IAppBuilder app)
        {
            ApplicationDbContext db = new ApplicationDbContext();

            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
                {
                    ClientId = clientId,
                    Authority = Authority,
                    PostLogoutRedirectUri = postLogoutRedirectUri,
                    TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
                    {
                        // instead of using the default validation (validating against a single issuer value, as we do in line of business apps),  
                        // we inject our own multitenant validation logic 
                        ValidateIssuer = false,
                    },
                    Notifications = new OpenIdConnectAuthenticationNotifications()
                    {
                        // If there is a code in the OpenID Connect response, redeem it for an access token and refresh token, and store those away.
                       AuthorizationCodeReceived = (context) => 
                       {
                           var code = context.Code;
                           ClientCredential credential = new ClientCredential(clientId, appKey);
                           string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
                           AuthenticationContext authContext = new AuthenticationContext(Authority, new ADALTokenCache(signedInUserID));
                           AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(
                           code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, graphResourceId);

                           //cache the token in session state
                           HttpContext.Current.Session[SettingsHelper.UserTokenCacheKey] = result;

                           return Task.FromResult(0);
                       },
                       RedirectToIdentityProvider = (context) =>
                       {
                           FormDataCookie cookie = new FormDataCookie(SettingsHelper.SavedFormDataName);
                           cookie.SaveRequestFormToCookie();
                           return Task.FromResult(0);
                       }
                    }
                });
        }
Пример #31
0
        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
                {
                    ClientId = MSGraphAPIDemoSettings.ClientId,
                    Authority = MSGraphAPIDemoSettings.Authority,
                    PostLogoutRedirectUri = MSGraphAPIDemoSettings.PostLogoutRedirectUri,
                    Notifications = new OpenIdConnectAuthenticationNotifications()
                    {
                        SecurityTokenValidated = (context) =>
                        {
                            return Task.FromResult(0);
                        },
                        AuthorizationCodeReceived = (context) =>
                        {
                            var code = context.Code;

                            ClientCredential credential = new ClientCredential(
                                MSGraphAPIDemoSettings.ClientId, 
                                MSGraphAPIDemoSettings.ClientSecret);
                            string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(
                                ClaimTypes.NameIdentifier).Value;

                            AuthenticationContext authContext = new AuthenticationContext(
                                MSGraphAPIDemoSettings.Authority,
                                new SessionADALCache(signedInUserID));
                            AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(
                                code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), 
                                credential, MSGraphAPIDemoSettings.MicrosoftGraphResourceId);

                            return Task.FromResult(0);
                        },
                        AuthenticationFailed = (context) =>
                        {
                            context.OwinContext.Response.Redirect("/Home/Error");
                            context.HandleResponse(); // Suppress the exception
                            return Task.FromResult(0);
                        }
                    }
                });
        }
        public string CompleteOAuthFlow(AuthorizationParameters parameters) {
            try
            {
                ClientCredential credential = new ClientCredential(AppConstants.OneDriveClientId, AppConstants.OneDriveClientSecret);
                string authority = string.Format(CultureInfo.InvariantCulture, OAuthUrl, "common");
                AuthenticationContext authContext = new AuthenticationContext(authority);
                AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(
                    parameters.Code, new Uri(RedirectUrl.GetLeftPart(UriPartial.Path)), credential);

                // Cache the access token and refresh token
                Storage.OneDrive.RefreshToken = result.RefreshToken;
                return "OAuth succeeded";
            }
            catch (Exception ex)// ActiveDirectoryAuthenticationException ex)
            {
                return "OAuth failed. " + ex.ToString();
            }
        }
        //
        // This method will be invoked as a call-back from an authentication service (e.g., https://login.windows.net/).
        // It is not intended to be called directly, only as a redirect from the authorization request in UserProfileController.
        // On completion, the method will cache the refresh token and access tokens, and redirect to the URL
        //     specified in the state parameter.
        //
        public ActionResult Index(string code, string error, string error_description, string resource, string state)
        {
            string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier").Value;

            // NOTE: In production, OAuth must be done over a secure HTTPS connection.
            if (Request.Url.Scheme != "https" && !Request.Url.IsLoopback)
                return View("Error");

            // Ensure there is a state value on the response.  If there is none, stop OAuth processing and display an error.
            if (state == null) {
                ViewBag.ErrorMessage = "Error Generating State.";
                return View("Error");
            }

            // Handle errors from the OAuth response, if any.  If there are errors, stop OAuth processing and display an error.
            if (error != null)
                return View("Error");

            string redirectUri = ValidateState(state, userObjectID);

            if (redirectUri == null) {
                ViewBag.ErrorMessage = "Error Validating State.";
                return View("Error");
            }

 
            // Redeem the authorization code from the response for an access token and refresh token.
            try
            {
                ClientCredential credential = new ClientCredential(Startup.clientId, Startup.appKey);
                AuthenticationContext authContext = new AuthenticationContext(Startup.Authority, new TokenDbCache(userObjectID));
                AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(
                    code, new Uri(Request.Url.GetLeftPart(UriPartial.Path)), credential, Startup.graphResourceId);

                // Return to the originating page where the user triggered the sign-in
                return Redirect(redirectUri);
            }
            catch (Exception e)
            {
                return Redirect("/UserProfile/Index?authError=token");
            }
        }
Пример #34
0
        //
        // The Client ID is used by the application to uniquely identify itself to Azure AD.
        // The App Key is a credential used to authenticate the application to Azure AD.  Azure AD supports password and certificate credentials.
        // The Metadata Address is used by the application to retrieve the signing keys used by Azure AD.
        // The AAD Instance is the instance of Azure, for example public Azure or Azure China.
        // The Authority is the sign-in URL of the tenant.
        // The Post Logout Redirect Uri is the URL where the user will be redirected after they sign out.
        //


        // This is the resource ID of the AAD Graph API.  We'll need this to request a token to call the Graph API.

        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
            {
                ClientId              = MediaLibraryWebApp.Configuration.ClientId,
                Authority             = MediaLibraryWebApp.Configuration.Authority,
                PostLogoutRedirectUri = MediaLibraryWebApp.Configuration.PostLogoutRedirectUri,

                Notifications = new OpenIdConnectAuthenticationNotifications()
                {
                    //
                    // If there is a code in the OpenID Connect response, redeem it for an access token and refresh token, and store those away.
                    //
                    AuthorizationCodeReceived = (context) =>
                    {
                        var code = context.Code;

                        ClientCredential credential = new ClientCredential(MediaLibraryWebApp.Configuration.ClientId, MediaLibraryWebApp.Configuration.AppKey);
                        string userObjectID         = context.AuthenticationTicket.Identity.FindFirst(MediaLibraryWebApp.Configuration.ClaimsObjectidentifier).Value;

                        AuthenticationContext authContext = new AuthenticationContext(MediaLibraryWebApp.Configuration.Authority, new NaiveSessionCache(userObjectID));
                        AuthenticationResult result       = authContext.AcquireTokenByAuthorizationCode(code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, MediaLibraryWebApp.Configuration.GraphResourceId);

                        //Initializing  MediaServicesCredentials in order to obtain access token to be used to connect
                        var amsCredentials = new MediaServicesCredentials(MediaLibraryWebApp.Configuration.MediaAccount, MediaLibraryWebApp.Configuration.MediaKey);
                        //Forces to get access token
                        amsCredentials.RefreshToken();

                        //Adding token to a claim so it can be accessible within controller
                        context.AuthenticationTicket.Identity.AddClaim(new Claim(MediaLibraryWebApp.Configuration.ClaimsJwtToken, result.AccessToken));
                        context.AuthenticationTicket.Identity.AddClaim(new Claim(MediaLibraryWebApp.Configuration.ClaimsAmsAcessToken, amsCredentials.AccessToken));
                        return(Task.FromResult(0));
                    }
                }
            });
        }
Пример #35
0
        public void ConfigureAuth(IAppBuilder app)
        {
            app.UseWindowsAzureActiveDirectoryBearerAuthentication(
                new WindowsAzureActiveDirectoryBearerAuthenticationOptions
            {
                Tenant = ConfigurationManager.AppSettings["ida:Domain"],
                TokenValidationParameters = new TokenValidationParameters
                {
                    ValidAudience = ConfigurationManager.AppSettings["ida:Audience"]
                },
            });

            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
            {
                ClientId              = clientId,
                Authority             = Authority,
                PostLogoutRedirectUri = postLogoutRedirectUri,

                Notifications = new OpenIdConnectAuthenticationNotifications()
                {
                    // If there is a code in the OpenID Connect response, redeem it for an access token and refresh token, and store those away.
                    AuthorizationCodeReceived = (context) =>
                    {
                        var code = context.Code;
                        ClientCredential credential = new ClientCredential(clientId, appKey);
                        string signedInUserID       = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
                        Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext authContext =
                            new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(Authority, new MemoryADALCache(signedInUserID));
                        AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(
                            code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, graphResourceId);

                        return(Task.FromResult(0));
                    }
                }
            });
        }
Пример #36
0
        public ActionResult Index()
        {
            if (AzureAuthenticationHelper.IsAuthenticated())
            {
                return this.RedirectToAction("Transfer");
            }

            var values = this.Request.QueryString["code"];
            if (values != null)
            {
                string code = values;
                AuthenticationContext ac = new AuthenticationContext(PersonalConfigurationManager.AppSettings["AzureAuthorityUri"]);
                ClientCredential cc = new ClientCredential(PersonalConfigurationManager.AppSettings["AzureClientId"], PersonalConfigurationManager.AppSettings["AzureKey"]);
                AuthenticationResult ar = ac.AcquireTokenByAuthorizationCode(code, new Uri(PersonalConfigurationManager.AppSettings["AzureRedirectUrl"]), cc);

                AzureAuthenticationHelper.SetSession(ar);
                return this.RedirectToAction("Transfer");
            }

            return this.View();
        }
Пример #37
0
        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
                {
                    Client_Id = clientId,
                    Authority = authority,
                    Post_Logout_Redirect_Uri = postLogoutRedirectUri,

                    Notifications = new OpenIdConnectAuthenticationNotifications()
                    {
                        //
                        // If there is a code in the OpenID Connect response, redeem it for an access token and refresh token, and store those away.
                        //
                        AccessCodeReceived = (context) =>
                        {
                            var code = context.Code;

                            ClientCredential credential = new ClientCredential(clientId, appKey);
                            AuthenticationContext authContext = new AuthenticationContext(authority);

                            AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(
                                code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, graphResourceId);

                            // Cache the access token and refresh token
                            TokenCacheUtils.SaveAccessTokenInCache(graphResourceId, result.AccessToken, (result.ExpiresOn.AddMinutes(-5)).ToString());
                            TokenCacheUtils.SaveRefreshTokenInCache(result.RefreshToken);

                            return Task.FromResult(0);
                        }

                    }

                });
        }
Пример #38
0
        public void ConfigureAuth(IAppBuilder app)
        {
            ApplicationDbContext db = new ApplicationDbContext();

            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
            {
                ClientId              = clientId,
                Authority             = Authority,
                PostLogoutRedirectUri = postLogoutRedirectUri,

                TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateIssuer = false,
                    RoleClaimType  = "roles"
                },

                Notifications = new OpenIdConnectAuthenticationNotifications()
                {
                    // If there is a code in the OpenID Connect response, redeem it for an access token and refresh token, and store those away.
                    AuthorizationCodeReceived = (context) =>
                    {
                        var code = context.Code;
                        ClientCredential credential = new ClientCredential(clientId, appKey);
                        string signedInUserID       = context.AuthenticationTicket.Identity.FindFirst(System.IdentityModel.Claims.ClaimTypes.NameIdentifier).Value;
                        Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext authContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(Authority, new ADALTokenCache(signedInUserID));
                        AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(
                            code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, graphResourceId);

                        return(Task.FromResult(0));
                    }
                }
            });
        }