public IHttpActionResult PutMuscularStrengthAndEndurance(int id, MuscularStrengthAndEndurance muscularStrengthAndEndurance) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != muscularStrengthAndEndurance.ID) { return(BadRequest()); } db.Entry(muscularStrengthAndEndurance).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!MuscularStrengthAndEnduranceExists(id)) { return(NotFound()); } else { throw; } } return(StatusCode(HttpStatusCode.NoContent)); }
public ActionResult SignUp([Bind(Include = "ID,Name,AdminConsented")] Tenant tenant) { // generate a random value to identify the request string stateMarker = Guid.NewGuid().ToString(); // store it in the temporary entry for the tenant, we'll use it later to assess if the request was originated from us // this is necessary if we want to prevent attackers from provisioning themselves to access our app without having gone through our onboarding process (e.g. payments, etc) tenant.IssValue = stateMarker; tenant.Created = DateTime.Now; db.Tenants.Add(tenant); db.SaveChanges(); //create an OAuth2 request, using the web app as the client. //this will trigger a consent flow that will provision the app in the target tenant string authorizationRequest = String.Format( "https://login.windows.net/common/oauth2/authorize?response_type=code&client_id={0}&resource={1}&redirect_uri={2}&state={3}", Uri.EscapeDataString(ConfigurationManager.AppSettings["ida:ClientID"]), Uri.EscapeDataString("https://graph.windows.net"), Uri.EscapeDataString(this.Request.Url.GetLeftPart(UriPartial.Authority).ToString() + "/Onboarding/ProcessCode"), Uri.EscapeDataString(stateMarker) ); //if the prospect customer wants to provision the app for all users in his/her tenant, the request must be modified accordingly if (tenant.AdminConsented) { authorizationRequest += String.Format("&prompt={0}", Uri.EscapeDataString("admin_consent")); } // send the user to consent return(new RedirectResult(authorizationRequest)); }
public IHttpActionResult PutBodyComposition(int id, BodyComposition bodyComposition) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != bodyComposition.ID) { return(BadRequest()); } db.Entry(bodyComposition).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!BodyCompositionExists(id)) { return(NotFound()); } else { throw; } } return(StatusCode(HttpStatusCode.NoContent)); }
public IHttpActionResult PutFlexibility(int id, Flexibility flexibility) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != flexibility.ID) { return(BadRequest()); } db.Entry(flexibility).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!FlexibilityExists(id)) { return(NotFound()); } else { throw; } } return(StatusCode(HttpStatusCode.NoContent)); }
public IHttpActionResult PutTrunkLiftModel(int id, TrunkLiftModel trunkLiftModel) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != trunkLiftModel.ID) { return(BadRequest()); } db.Entry(trunkLiftModel).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!TrunkLiftModelExists(id)) { return(NotFound()); } else { throw; } } return(StatusCode(HttpStatusCode.NoContent)); }
public IHttpActionResult PutCardiovascularFitness(int id, CardiovascularFitness cardiovascularFitness) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != cardiovascularFitness.ID) { return(BadRequest()); } db.Entry(cardiovascularFitness).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!CardiovascularFitnessExists(id)) { return(NotFound()); } else { throw; } } return(StatusCode(HttpStatusCode.NoContent)); }
// clean up the db public override void Clear() { base.Clear(); foreach (var cacheEntry in _db.PerUserCacheList) { _db.PerUserCacheList.Remove(cacheEntry); } _db.SaveChanges(); }
public ActionResult Create([Bind(Include = "ID,Description")] Todo todo) { if (ModelState.IsValid) { todo.Owner = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value; db.Todoes.Add(todo); db.SaveChanges(); return(RedirectToAction("Index")); } return(View(todo)); }
public ActionResult Create([Bind("ID", "Description")] Todo todo) { if (ModelState.IsValid) { todo.Owner = User.FindFirst(ClaimTypes.NameIdentifier).Value; _db.Todoes.Add(todo); _db.SaveChanges(); return(new RedirectToActionResult("Index", "Todo", null)); } return(View(todo)); }
public ActionResult Create([Bind(Include = "ID,Owner,Height,Weight,BodyFat,Logged")] BodyComposition bodyComposition) { if (ModelState.IsValid) { bodyComposition.Owner = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value; bodyComposition.Logged = DateTime.UtcNow; db.BodyComps.Add(bodyComposition); db.SaveChanges(); return(RedirectToAction("Index")); } return(View(bodyComposition)); }
public ActionResult Create([Bind(Include = "ID,Owner,SitAndReach,ArmAndShoulder,TrunkLift,Logged")] Flexibility flexibility) { if (ModelState.IsValid) { flexibility.Owner = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value; flexibility.Logged = DateTime.UtcNow; db.Flexibilities.Add(flexibility); db.SaveChanges(); return(RedirectToAction("Index")); } return(View(flexibility)); }
public ActionResult Create([Bind(Include = "ID,Owner,CurlUps,RightAnglePushUps,MaxBench,MaxLegPress,PullUps,FlexedArmHang,Logged")] MuscularStrengthAndEndurance muscularStrengthAndEndurance) { if (ModelState.IsValid) { string owner = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value; muscularStrengthAndEndurance.Owner = owner; muscularStrengthAndEndurance.Logged = DateTime.UtcNow; db.MuscularStrengthsAndEndurances.Add(muscularStrengthAndEndurance); db.SaveChanges(); return(RedirectToAction("Index")); } return(View(muscularStrengthAndEndurance)); }
public ActionResult Create([Bind(Include = "ID,Owner,HalfMileTime,Pacer,MileTime,StepTestSteps,StepTestHeartRate,Logged")] CardiovascularFitness cardiovascularFitness) { if (ModelState.IsValid) { string owner = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value; cardiovascularFitness.Owner = owner; cardiovascularFitness.Logged = DateTime.UtcNow; db.Cardios.Add(cardiovascularFitness); db.SaveChanges(); return(RedirectToAction("Index")); } return(View(cardiovascularFitness)); }
// Inject custom logic for validating which users we allow to sign in // Here we check that the user (or their tenant admin) has signed up for the application. private Task OnTokenValidated(TokenValidatedContext context) { // Retrieve the db service TodoListWebAppContext db = (TodoListWebAppContext)context.HttpContext.RequestServices.GetService(typeof(TodoListWebAppContext)); // Retrieve caller data from the incoming principal string issuer = context.Ticket.Principal.FindFirst(AzureADConstants.Issuer).Value; string objectID = context.Ticket.Principal.FindFirst(AzureADConstants.ObjectIdClaimType).Value; string tenantID = context.Ticket.Principal.FindFirst(AzureADConstants.TenantIdClaimType).Value; string upn = context.Ticket.Principal.FindFirst(ClaimTypes.Upn).Value; // Look up existing sign up records from the database Tenant tenant = db.Tenants.FirstOrDefault(a => a.IssValue.Equals(issuer)); AADUserRecord user = db.Users.FirstOrDefault(b => b.ObjectID.Equals(objectID)); // If the user is signing up, add the user or tenant to the database record of sign ups. string adminConsentSignUp = null; if (context.Properties.Items.TryGetValue(Constants.AdminConsentKey, out adminConsentSignUp)) { if (adminConsentSignUp == Constants.True) { if (tenant == null) { tenant = new Tenant { Created = DateTime.Now, IssValue = issuer, Name = context.Properties.Items[Constants.TenantNameKey], AdminConsented = true }; db.Tenants.Add(tenant); } else { tenant.AdminConsented = true; } } else if (user == null) { user = new AADUserRecord { UPN = upn, ObjectID = objectID }; db.Users.Add(user); } db.SaveChanges(); } // Ensure that the caller is recorded in the db of users who went through the individual onboarding // or if the caller comes from an admin-consented, recorded issuer. if ((tenant == null || !tenant.AdminConsented) && (user == null)) { // If not, the caller was neither from a trusted issuer or a registered user - throw to block the authentication flow throw new SecurityTokenValidationException("Did you forget to sign-up?"); } return(Task.FromResult(0)); }
public void Onboard([FromBody] string name) { // here "name" is just a placeholder for the real data your app would require from the caller // if (MyCustomOnboardingDataValidation(name)) string upn = ClaimsPrincipal.Current.FindFirst(ClaimTypes.Name).Value; string tenantID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value; if (db.Users.FirstOrDefault(a => (a.UPN == upn) && (a.TenantID == tenantID)) == null) { // add the caller to the collection of valid users db.Users.Add(new User { UPN = upn, TenantID = tenantID }); } db.SaveChanges(); }
// GET: UserProfile public ActionResult Index() { string clientId = ConfigurationManager.AppSettings["ida:ClientID"]; string appKey = ConfigurationManager.AppSettings["ida:Password"]; string graphResourceID = "https://graph.windows.net"; string signedInUserID = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value; string tenantID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value; string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value; bool validTokenPresent = true; TodoListWebApp.Models.TokenCacheEntry tce = null; //get a token using the cached values var existing = db.TokenCache.FirstOrDefault(a => (a.SignedInUser == signedInUserID) && (a.ResourceID == graphResourceID)); if (existing != null) //we have a token cache entry { tce = existing; //if the access token is expired if (tce.Expiration.DateTime < DateTime.Now) { //use the refresh token to get a fresh set of tokens try { ClientCredential clientcred = new ClientCredential(clientId, appKey); AuthenticationContext authContext = new AuthenticationContext(string.Format("https://login.windows.net/{0}", tenantID)); AuthenticationResult result = authContext.AcquireTokenByRefreshToken(tce.RefreshToken, clientId, clientcred, graphResourceID); TodoListWebApp.Models.TokenCacheEntry tce2 = new TodoListWebApp.Models.TokenCacheEntry { SignedInUser = signedInUserID, TokenRequestorUser = result.UserInfo.UserId, ResourceID = graphResourceID, AccessToken = result.AccessToken, RefreshToken = result.RefreshToken, Expiration = result.ExpiresOn.AddMinutes(-5) }; db.TokenCache.Remove(tce); db.TokenCache.Add(tce2); db.SaveChanges(); tce = tce2; } catch { // the refresh token might be expired tce = null; } } } else // we don't have a cached token { tce = null; // it's already null, but for good measure... } if (tce != null) { // CallContext currentCallContext = new CallContext { AccessToken = tce.AccessToken, ClientRequestId = Guid.NewGuid(), TenantId = tenantID, ApiVersion = "2013-11-08" }; CallContext currentCallContext = new CallContext(tce.AccessToken, Guid.NewGuid(), "2013-11-08"); GraphConnection graphConnection = new GraphConnection(currentCallContext); User user = graphConnection.Get <User>(userObjectID); return(View(user)); } else { ViewBag.ErrorMessage = "AuthorizationRequired"; return(View()); } }
public void ConfigureAuth(IAppBuilder app) { string clientId = ConfigurationManager.AppSettings["ida:ClientID"]; string appKey = ConfigurationManager.AppSettings["ida:Password"]; string graphResourceID = "https://graph.windows.net"; //fixed address for multitenant apps in the public cloud string Authority = "https://login.windows.net/common/"; app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); app.UseCookieAuthentication(new CookieAuthenticationOptions { }); app.UseOpenIdConnectAuthentication( new OpenIdConnectAuthenticationOptions { Client_Id = 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() { AccessCodeReceived = (context) => { var code = context.Code; ClientCredential credential = new ClientCredential(clientId, appKey); string tenantID = context.ClaimsIdentity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value; string signedInUserID = context.ClaimsIdentity.FindFirst(ClaimTypes.NameIdentifier).Value; AuthenticationContext authContext = new AuthenticationContext(string.Format("https://login.windows.net/{0}", tenantID)); AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode( code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, graphResourceID); TokenCacheEntry tce = new TokenCacheEntry { SignedInUser = signedInUserID, TokenRequestorUser = result.UserInfo.UserId, ResourceID = graphResourceID, AccessToken = result.AccessToken, RefreshToken = result.RefreshToken, Expiration = result.ExpiresOn.AddMinutes(-5) }; var existing = db.TokenCache.FirstOrDefault(a => (a.SignedInUser == signedInUserID) && (a.ResourceID == graphResourceID)); if (existing != null) { db.TokenCache.Remove(existing); } db.TokenCache.Add(tce); db.SaveChanges(); 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.Redirect_Uri = appBaseUrl + "/"; context.ProtocolMessage.Post_Logout_Redirect_Uri = appBaseUrl; return(Task.FromResult(0)); }, // we use this notification for injecting our custom logic SecurityTokenValidated = (context) => { // retriever caller data from the incoming principal string issuer = context.AuthenticationTicket.Identity.FindFirst("iss").Value; string UPN = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.Name).Value; string tenantID = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value; if ( // the caller comes from an admin-consented, recorded issuer (db.Tenants.FirstOrDefault(a => ((a.IssValue == issuer) && (a.AdminConsented))) == null) // the caller is recorded in the db of users who went through the individual onboardoing && (db.Users.FirstOrDefault(b => ((b.UPN == UPN) && (b.TenantID == tenantID))) == null) ) { // the caller was neither from a trusted issuer or a registered user - throw to block the authentication flow throw new System.IdentityModel.Tokens.SecurityTokenValidationException(); } return(Task.FromResult(0)); }, AuthenticationFailed = (context) => { context.Redirect("/Home/Error"); return(Task.FromResult(0)); } } }); }