public async Task <IActionResult> GetAll() { var administrators = await GraphApiConnector.UpdateAdministrators(); if (!administrators.Contains(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } var users = await _userService.GetAll(); return(Ok(users)); }
public async Task <IActionResult> CreateUser([FromBody, BindRequired] UserDTO userDTO) { var administrators = await GraphApiConnector.UpdateAdministrators(); if (!administrators.Contains(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } var user = await _userService.CreateUser(userDTO); return(Ok(user)); }
internal async Task FindPathAsync() { try { var solution = await GraphApiConnector.PostGraphAsync(Mapper.ToGraphDto(_canvas)); UpdateSolution(solution); } catch (Exception ex) { _canvas.Message = ex.Message; } }
public async Task OnPost() { var form = Request.Form; if (form.TryGetValue("userDeleteId", out var value)) { await GraphApiConnector.DeleteUser(value); } else { Microsoft.Graph.User user; var list = new List <ObjectIdentity>(); if (users.Where(a => a.Username.Equals(form["userId"])).Any()) { list = GraphApiConnector.users.Where(a => a.Id.Equals(form["userId"])).First().Identities.ToList(); list.Where(identity => identity.SignInType.Equals("emailAddress")).First().IssuerAssignedId = form["EmailAddress"]; user = new Microsoft.Graph.User { Id = form["userId"], AccountEnabled = true, DisplayName = form["DisplayName"], CreationType = "LocalAccount", Identities = list }; await GraphApiConnector.UpdateUser(user); } else { list.Add(new ObjectIdentity { SignInType = "emailAddress", Issuer = "emsfiiot.onmicrosoft.com", IssuerAssignedId = form["EmailAddress"] }); user = new Microsoft.Graph.User { Id = form["userId"], AccountEnabled = true, DisplayName = form["DisplayName"], CreationType = "LocalAccount", PasswordProfile = new PasswordProfile { ForceChangePasswordNextSignInWithMfa = true, Password = "******"
public async Task OnGet() { var graphUsers = await GraphApiConnector.UpdateUsers(); administrators = await GraphApiConnector.UpdateAdministrators(); users.Clear(); graphUsers.ToList().ForEach(user => { users.Add(new AppUser { Username = user.Id, DisplayName = user.DisplayName, EmailAddress = user.Identities.First(identity => identity.SignInType.Equals("emailAddress")).IssuerAssignedId.ToString() }); }); ViewData["users"] = JsonSerializer.Serialize(users.ToList()).Replace("\"", "\\\""); ViewData["administrators"] = JsonSerializer.Serialize(administrators.ToList()).Replace("\"", "\\\""); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { new EMSfIIoTApiConnector(Configuration.GetSection("AzureAdB2C")); new BoschIoTSuiteApiConnector(Configuration.GetSection("BoschIoTSuite")); new GraphApiConnector(Configuration.GetSection("AzureAdB2C")); IdentityModelEventSource.ShowPII = true; services.TryAddSingleton <CommonLocalizationService>(); services.TryAddSingleton <IHttpContextAccessor, HttpContextAccessor>(); services.AddAuthentication(AzureADB2CDefaults.AuthenticationScheme) .AddAzureADB2C(options => { options.Instance = Configuration["AzureAdB2C:Instance"]; options.ClientId = Configuration["AzureAdB2C:ClientId"]; options.CallbackPath = Configuration["AzureAdB2C:CallbackPath"]; options.Domain = Configuration["AzureAdB2C:Domain"]; options.SignUpSignInPolicyId = Configuration["AzureAdB2C:SignUpSignInPolicyId"]; options.ResetPasswordPolicyId = Configuration["AzureAdB2C:ResetPasswordPolicyId"]; options.EditProfilePolicyId = Configuration["AzureAdB2C:EditProfilePolicyId"]; }) .AddCookie(); services.Configure <OpenIdConnectOptions>(AzureADB2CDefaults.OpenIdScheme, options => { string authority = Configuration["AzureAdB2C:Instance"] + "tfp/" + Configuration["AzureAdB2C:Domain"] + "/" + Configuration["AzureAdB2C:SignUpSignInPolicyId"] + "/v2.0"; options.ClientId = Configuration["AzureAdB2C:ClientId"]; options.Authority = authority; options.UseTokenLifetime = true; options.SaveTokens = true; options.CallbackPath = new PathString("/auth"); options.GetClaimsFromUserInfoEndpoint = true; options.ResponseMode = OpenIdConnectResponseMode.FormPost; options.TokenValidationParameters = new TokenValidationParameters() { NameClaimType = "name", }; options.Events = new OpenIdConnectEvents { OnAuthorizationCodeReceived = async ctx => { // Use MSAL to swap the code for an access token // Extract the code from the response notification var code = ctx.ProtocolMessage.Code; await GraphApiConnector.UpdateAdministrators(); string signedInUserID = ctx.Principal.FindFirst(ClaimTypes.NameIdentifier).Value; IConfidentialClientApplication cca = ConfidentialClientApplicationBuilder.Create(Configuration["AzureAdB2C:ClientId"]) .WithB2CAuthority(authority) .WithClientSecret(Configuration["AzureAdB2C:ClientSecret"]) .Build(); var cache = new MSALStaticCache(signedInUserID, ctx.HttpContext).EnablePersistence(cca.UserTokenCache); try { AuthenticationResult result = await cca.AcquireTokenByAuthorizationCode(options.Scope, code).ExecuteAsync(); if (result.AccessToken != null) { ctx.HttpContext.Response.Cookies.Append("ADB2CToken", result.AccessToken, new CookieOptions { Expires = result.ExpiresOn }); } ctx.HandleCodeRedemption(result.AccessToken, result.IdToken); } catch (Exception ex) { throw; } }, OnRedirectToIdentityProvider = ctx => { var defaultPolicy = Configuration["AzureAdB2C:SignUpSignInPolicyId"]; if (ctx.Properties.Items.TryGetValue("Policy", out var policy) && !policy.Equals(defaultPolicy)) { ctx.ProtocolMessage.Scope = OpenIdConnectScope.OpenIdProfile; ctx.ProtocolMessage.ResponseType = OpenIdConnectResponseType.IdToken; ctx.ProtocolMessage.IssuerAddress = ctx.ProtocolMessage.IssuerAddress.ToLower().Replace(defaultPolicy.ToLower(), policy.ToLower()); ctx.Properties.Items.Remove(Configuration["AzureAdB2C:SignUpSignInPolicyId"]); } else if (!string.IsNullOrEmpty(Configuration["AzureAdB2C:Url"])) { ctx.ProtocolMessage.Scope += $" offline_access {Configuration["AzureAdB2C:Scopes"]}"; ctx.ProtocolMessage.ResponseType = OpenIdConnectResponseType.CodeIdToken; } ctx.ProtocolMessage.UiLocales = ctx.HttpContext.Request.Query["culture"].ToString(); return(Task.FromResult(0)); }, OnRemoteFailure = ctx => { ctx.HandleResponse(); // Handle the error code that Azure AD B2C throws when trying to reset a password from the login page // because password reset is not supported by a "sign-up or sign-in policy" if (ctx.Failure is OpenIdConnectProtocolException && ctx.Failure.Message.Contains("AADB2C90118")) { // If the user clicked the reset password link, redirect to the reset password route ctx.Response.Redirect("/Account/ResetPassword"); } else if (ctx.Failure is OpenIdConnectProtocolException && ctx.Failure.Message.Contains("access_denied")) { ctx.Response.Redirect("/"); } else { ctx.Response.Redirect("/Error?message=" + Uri.EscapeDataString(ctx.Failure.Message)); } return(Task.FromResult(0)); }, OnRemoteSignOut = ctx => { ctx.HttpContext.Response.Cookies.Delete("ADB2CToken"); return(Task.FromResult(0)); } }; });
public async Task OnGet() { await GraphApiConnector.UpdateUsers(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { new GraphApiConnector(Configuration.GetSection("AzureAdB2C")); new BoschIoTSuiteApiConnector(Configuration.GetSection("BoschIoTSuite")); new SendGridAPIConnector(Configuration.GetSection("SendGrid")); new TelegramAPIConnector(Configuration.GetSection("Telegram")); services.AddAuthentication(options => { options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer("bearerAuth", jwtOptions => { jwtOptions.Authority = Configuration["AzureAdB2C:Authority"]; jwtOptions.Audience = Configuration["AzureAdB2C:ClientId"]; jwtOptions.TokenValidationParameters = new TokenValidationParameters { NameClaimType = "name" }; jwtOptions.Events = new JwtBearerEvents { OnTokenValidated = async ctx => { await GraphApiConnector.UpdateUsers(); } }; }) .AddScheme <AuthenticationSchemeOptions, BasicAuthenticationHandler>("basicAuth", null); services.AddAuthorization(c => { c.AddPolicy("read", p => p.RequireClaim("http://schemas.microsoft.com/identity/claims/scope", new List <string> { "read", "read write", "write read" })); c.AddPolicy("write", p => p.RequireClaim("http://schemas.microsoft.com/identity/claims/scope", new List <string> { "write", "read write", "write read" })); }); services.AddScoped <IUserService, UserService>(); services.AddDbContext <ApiDbContext>(options => { options.UseSqlServer( Configuration.GetConnectionString("database"), providerOptions => providerOptions.EnableRetryOnFailure() ); }); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "EMSfIIoT API", Version = "v1.0.0", Description = "Energy Management Solution for Industrial IoT" }); c.EnableAnnotations(); c.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, "EMSfIIoT_API.xml")); c.AddSecurityDefinition("bearerAuth", new OpenApiSecurityScheme { Type = SecuritySchemeType.OAuth2, Scheme = JwtBearerDefaults.AuthenticationScheme, Flows = new OpenApiOAuthFlows { Implicit = new OpenApiOAuthFlow { AuthorizationUrl = new Uri(Configuration["AzureAdB2C:AuthorizationUrl"], UriKind.Absolute), Scopes = new Dictionary <string, string> { { "https://emsfiiot.onmicrosoft.com/EMSfIIoT_API/read", "Read permissions" }, { "https://emsfiiot.onmicrosoft.com/EMSfIIoT_API/write", "Write permissions" } } } } }); c.AddSecurityDefinition("basicAuth", new OpenApiSecurityScheme { Type = SecuritySchemeType.Http, Description = "Please enter your username and password", Scheme = "basic", In = ParameterLocation.Header }); c.OperationFilter <AuthenticationRequirementOperationsFilter>(); c.OperationFilter <DefaultResponseOperationsFilter>(); }); services.AddControllers(options => { options.RespectBrowserAcceptHeader = true; }) .AddJsonOptions(options => options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter())); services.AddHostedService <NotificationTask>(); services.AddHostedService <TelegramTask>(); services.AddSignalR(); services.AddCors(options => { options.AddPolicy(name: "EMSfIIoT", builder => { builder.WithOrigins( "https://localhost:5001", "https://emsfiiot.azurewebsites.net" ); builder.AllowAnyHeader(); builder.AllowAnyMethod(); builder.AllowCredentials(); }); }); }
private static async void Bot_OnMessage(object sender, MessageEventArgs e) { if (e.Message.Text != null) { await GraphApiConnector.UpdateUsers(); BotCommand[] commands = await botClient.GetMyCommandsAsync(); await botClient.SendChatActionAsync(e.Message.Chat.Id, ChatAction.Typing); string response = null; if (e.Message.ReplyToMessage != null) { var subscription = subscriptions.Where(subscription => subscription.MessageId.Equals(e.Message.ReplyToMessage.MessageId)).FirstOrDefault(); if (subscription != null) { if (subscription.WaitingEmail) { if (e.Message.Text.Trim().Equals(subscription.Token)) { subscriptions.Remove(subscription); await GraphApiConnector.AddTelegramSubscription(subscription.User, e.Message.Chat.Id.ToString()); response = "This chat is now associated with account with email address " + subscription.User.Identities.Where(identity => identity.SignInType.Equals("emailAddress")).First().IssuerAssignedId; } else { response = "Wrong code"; } } else { var user = GraphApiConnector.users .Where(user => user.Identities .Where(identity => identity.SignInType.Equals("emailAddress")).First() .IssuerAssignedId.Equals(e.Message.Text.ToString().Trim().ToLower())) .FirstOrDefault(); if (user != null) { if (!user.AdditionalData.TryGetValue("extension_257f2369f5054b62a0f21c2c82ad96fc_TelegramChatId", out _)) { Random r = new Random(); string randNum = r.Next(1000000).ToString("D6"); subscription.User = user; subscription.Token = randNum; subscription.WaitingEmail = true; await SendGridAPIConnector.SendEmail(new EmailAddress() { Email = user.Identities.Where(identity => identity.SignInType.Equals("emailAddress")).First().IssuerAssignedId, Name = user.DisplayName }, "EMSfIIoT TelgramBot", randNum, randNum); response = "Please insert the code you received in your email address"; var message = await botClient.SendTextMessageAsync( chatId : e.Message.Chat, text : response, replyMarkup : new ForceReplyMarkup() ); subscription.MessageId = message.MessageId; subscription.MessageDate = DateTime.Now; return; } else { response = "This account is already associated with another chat"; } } else { response = "User with email address " + e.Message.Text.ToString().Trim().ToLower() + " not found"; } } } else { response = "Invalid request. Please try again."; } await botClient.SendTextMessageAsync( chatId : e.Message.Chat, text : response ); return; } switch (e.Message.Text) { case "/start": response = "Hello " + e.Message.From.FirstName + " " + e.Message.From.LastName + "\n"; response += "Welcome to the EMSfIIoT Telegram Bot!\n"; commands.ToList().ForEach(command => { response += "\n/" + command.Command + " - " + command.Description; }); break; case "/help": commands.ToList().ForEach(command => { response += "/" + command.Command + " - " + command.Description + "\n"; }); break; case "/subscribe": foreach (var user in GraphApiConnector.users) { if (user.AdditionalData.TryGetValue("extension_257f2369f5054b62a0f21c2c82ad96fc_TelegramChatId", out var value)) { if (Convert.ToInt64(value).Equals(e.Message.Chat.Id)) { response = "This chat is already associated with an account"; } } } if (response != null) { break; } response = "Please insert your EMSfIIoT account email address"; var message = await botClient.SendTextMessageAsync( chatId : e.Message.Chat, text : response, replyMarkup : new ForceReplyMarkup() ); subscriptions.Add(new TelgramSubscription() { MessageId = message.MessageId, MessageDate = DateTime.Now, WaitingEmail = false }); return; case "/unsubscribe": foreach (var user in GraphApiConnector.users) { if (user.AdditionalData.TryGetValue("extension_257f2369f5054b62a0f21c2c82ad96fc_TelegramChatId", out var value)) { if (Convert.ToInt64(value).Equals(e.Message.Chat.Id)) { response = user.Identities.Where(identity => identity.SignInType.Equals("emailAddress")).First().IssuerAssignedId; await GraphApiConnector.RemoveTelegramSubscription(user); } } } if (response != null) { response = "Your subscription associated with account with email address " + response + " was removed"; } else { response = "This chat isn't associated with any account"; } break; case "/status": foreach (var user in GraphApiConnector.users) { if (user.AdditionalData.TryGetValue("extension_257f2369f5054b62a0f21c2c82ad96fc_TelegramChatId", out var value)) { if (Convert.ToInt64(value).Equals(e.Message.Chat.Id)) { response = user.Identities.Where(identity => identity.SignInType.Equals("emailAddress")).First().IssuerAssignedId; } } } if (response != null) { response = "This chat is associated with account with email address " + response; } else { response = "This chat isn't associated with any account"; } break; default: response = "Command not recognized! Type /help for a list of commands."; break; } if (response != null) { await botClient.SendTextMessageAsync( chatId : e.Message.Chat, text : response ); } } }