ASP.NET MVC - Regex to allow less than character safely
I have a ASP.NET MVC 5 app where my business users require to enter a <
(less than sign). For their specific business segment the <
is a common used sign. I know about the problem of XSS-Attacks, but I'm trying to find a solution to allow just the <
without opening XSS-Attacks. I DON'T want to allow HTML, so I don't what to set [AllowHtml]
or disable the validation rules. They should be turned on.
I thought about to only allow the <
followed by a space, which isn't a valid html tag and isn't detected by ASP.NET as dangerous request. I assume that the best option would be to setup a regex, but I don't know how the regex should look like.
For example I want to extend this regex (Data annotation): [RegularExpression(@"^[a-zA-Z0-9 ]+$", ErrorMessage = "some message")]
to allow <
followed by a space.
Is there also anything to consider if I would allow <
(followed by space)?
See also questions close to this topic
-
Huge amount of logon attempts when loading a page (without cache)
I notice in the Performance Monitor of Windows Server 2012 that there are spikes in logon attempts per second under Web Service -> Logon Attempts/sec. These spikes go from about 0 to 50.
I've traced this down to a page refresh. Loading a page with no cache that is. An average page load does about 50 requests (images, scripts, etc). Now apparently these 50 requests are shown as logon attempts.
Is this normal?
Note that this page does not require the visitor to be logged in.
-
Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler[3\
When warn: Microsoft.AspNetCore.DataProtection.Repositories.FileSystemXmlRepository[60]
Storing keys in a directory '/root/.aspnet/DataProtection-Keys' that may not be persisted outside of the container. Protected data will be unavailable when container is destroyed.
warn: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[35]
No XML encryptor configured. Key {e43b756a-2818-4898-8730-5e8e0f230be7} may be persisted to storage in unencrypted form.
info: IdentityServer4.Startup[0]
Starting IdentityServer4 version 4.1.1+cebd52f5bc61bdefc262fd20739d4d087c6f961f
info: IdentityServer4.Startup[0]
You are using the in-memory version of the persisted grant store. This will store consent decisions, authorization codes, refresh and reference tokens in memory only. If you are using any of those features in production, you want to switch to a different store implementation.
info: IdentityServer4.Startup[0]
Using the default authentication scheme Identity.Application for IdentityServer
info: Microsoft.Hosting.Lifetime[0]
Now listening on: https://[::]:8081
info: Microsoft.Hosting.Lifetime[0]
Now listening on: http://[::]:8080
info: Microsoft.Hosting.Lifetime[0]
Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
Hosting environment: Production
info: Microsoft.Hosting.Lifetime[0]
Content root path: /app
info: IdentityServer4.Hosting.IdentityServerMiddleware[0]
Invoking IdentityServer endpoint: IdentityServer4.Endpoints.TokenEndpoint for /connect/token
info: IdentityServer4.AspNetIdentity.ResourceOwnerPasswordValidator[0]
Credentials validated for username: muthu
info: IdentityServer4.Validation.TokenRequestValidator[0]
Token request validation success, {
"ClientId": "sdgfsdsgsdg",
"ClientName": "Swagger UI",
"GrantType": "password",
"Scopes": "api",
"AuthorizationCode": "********",
"RefreshToken": "********",
"UserName": "sample",
"Raw": {
"grant_type": "password",
"username": "sample",
"password": "REDACTED"
}
}
fail: Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler[3]
Exception occurred while processing message.
System.InvalidOperationException: IDX20803: Unable to obtain configuration from: 'http://*:8080/.well-known/openid-configuration'.
---> System.IO.IOException: IDX20804: Unable to retrieve document from: 'http://*:8080/.well-known/openid-configuration'.
---> System.UriFormatException: Invalid URI: The hostname could not be parsed.
at System.Uri.CreateThis(String uri, Boolean dontEscape, UriKind uriKind)
at System.Uri..ctor(String uriString, UriKind uriKind)
at Microsoft.IdentityModel.Protocols.HttpDocumentRetriever.GetDocumentAsync(String address, CancellationToken cancel)
--- End of inner exception stack trace ---
at Microsoft.IdentityModel.Protocols.HttpDocumentRetriever.GetDocumentAsync(String address, CancellationToken cancel)
at Microsoft.IdentityModel.Protocols.OpenIdConnect.OpenIdConnectConfigurationRetriever.GetAsync(String address, IDocumentRetriever retriever, CancellationToken cancel)
at Microsoft.IdentityModel.Protocols.ConfigurationManager`1.GetConfigurationAsync(CancellationToken cancel)
--- End of inner exception stack trace ---
at Microsoft.IdentityModel.Protocols.ConfigurationManager`1.GetConfigurationAsync(CancellationToken cancel)
at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync()
fail: IdentityServer4.AccessTokenValidation.IdentityServerAuthenticationHandler[0]
IDX20803: Unable to obtain configuration from: 'http://*:8080/.well-known/openid-configuration'.
System.InvalidOperationException: IDX20803: Unable to obtain configuration from: 'http://*:8080/.well-known/openid-configuration'.
---> System.IO.IOException: IDX20804: Unable to retrieve document from: 'http://*:8080/.well-known/openid-configuration'.
---> System.UriFormatException: Invalid URI: The hostname could not be parsed.
at System.Uri.CreateThis(String uri, Boolean dontEscape, UriKind uriKind)
at System.Uri..ctor(String uriString, UriKind uriKind)
at Microsoft.IdentityModel.Protocols.HttpDocumentRetriever.GetDocumentAsync(String address, CancellationToken cancel)
--- End of inner exception stack trace ---
at Microsoft.IdentityModel.Protocols.HttpDocumentRetriever.GetDocumentAsync(String address, CancellationToken cancel)
at Microsoft.IdentityModel.Protocols.OpenIdConnect.OpenIdConnectConfigurationRetriever.GetAsync(String address, IDocumentRetriever retriever, CancellationToken cancel)
at Microsoft.IdentityModel.Protocols.ConfigurationManager`1.GetConfigurationAsync(CancellationToken cancel)
--- End of inner exception stack trace ---
at Microsoft.IdentityModel.Protocols.ConfigurationManager`1.GetConfigurationAsync(CancellationToken cancel)
at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync()
at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync()
at Microsoft.AspNetCore.Authentication.AuthenticationHandler`1.AuthenticateAsync()
at Microsoft.AspNetCore.Authentication.AuthenticationService.AuthenticateAsync(HttpContext context, String scheme)
at IdentityServer4.AccessTokenValidation.IdentityServerAuthenticationHandler.HandleAuthenticateAsync()
info: IdentityServer4.AccessTokenValidation.IdentityServerAuthenticationHandler[7]
Bearer was not authenticated. Failure message: IDX20803: Unable to obtain configuration from: 'http://*:8080/.well-known/openid-configuration'.
info: IdentityServer4.AccessTokenValidation.IdentityServerAuthenticationHandler[12]
AuthenticationScheme: Bearer was challenged.
-
ASP.NET using return RedirectToAction(" ", " ") how to use this to redirect to a cshtml
I can not find a useable tutorial that explains how to redirect using REdirectToAction. can someone share a link that that explains ALL the steps needed to use this? I think I am having a hard time understanding how the parameters are given can find an HTML file with a model in the parameter? or is it a controller? I am very lost on how they communicate. please someone if you can help.
-
ruby - how to make a letter lowercase unless it comes after a comma or slash with regex
I am trying to clean a set of names from a mysql table using mysql2 gem in ruby code, and then add the cleaned names to the table in a new column. I was able to do the cleaning except for one condition:
Lowercasing all words, unless they come after a slash or after a comma or in parentheses
. Here's a sample piece of code:def cleaning_names(client) q = "SELECT column_of_names FROM original_table;" names = client.query(q) names.map do |name| clean_name = "#{name["column_of_names"]" end end
I used multiple
gsub
's to do the rest of the cleaning, but I can't find out how to use regex (in a gsub maybe) in order to downcase letters, or to leave them alone if they come after a slash or comma.For example, one of the names I want is:
'County Clerk/DeKalb County'
becomes‘DeKalb County clerk’
or"1st circuit judge, Circuit Court"
becomes"1st circuit judge (Circuit Court)"
. My code fixed the order, but doesn't do the proper capitalization.Thanks :-)
-
regex for capture groups
I'm still learning Regex. I am trying to capture the groups in
()
below forstrcapture
. Any help with the regex expression to define the two capture groups in the texts below appreciated!Example 1
1. 4301 TMA_Scan1_Core[1,1,A]_[10844,40623]_component_data.tif - resolution #1
to capture:
1. (4301) TMA_Scan1_Core[1,(1,A)]_[10844,40623]_component_data.tif - resolution #1
Example 2
3. TMA A_Scan1_Core[1,1,A]_[4600,36783]_component_data.tif - resolution #1
to capture:
3. (TMA A)_Scan1_Core[1,(1,A)]_[4600,36783]_component_data.tif - resolution #1
May require two different patterns to distinguish example 1 from example 2?
dput(test) structure(list(Image = c("1. 4301 TMA_Scan1_Core[1,1,A]_[10844,40623]_component_data.tif - resolution #1", "2. 4302 TMA_Scan1_Core[1,6,B]_[12511,47333]_component_data.tif - resolution #1", "3. TMA A_Scan1_Core[1,1,A]_[4600,36783]_component_data.tif - resolution #1", "4. TMA B_Scan1_Core[1,9,E]_[12695,54120]_component_data.tif - resolution #1" )), class = c("spec_tbl_df", "tbl_df", "tbl", "data.frame"), row.names = c(NA, -4L), spec = structure(list(cols = list(Image = structure(list(), class = c("collector_character", "collector"))), default = structure(list(), class = c("collector_guess", "collector")), skip = 1L), class = "col_spec"))
substituting "pattern" below to capture groups 1 and 2 into "File" and "ID"
out <- strcapture("pattern", test$Image, list("File" = "", "ID" = ""))
to get:
out<- as.data.frame("File"= c("4301","4302", "TMA A", "TMA B"), "ID" = c("1A","6B","1A","9E"))
-
Replace line breaks not followed by a date in PHP
I try to parse a string using PHP line by line. Usually each data set consists of 13 values separated by tabs. One of those values contains comments and those might have a line break in it (which I cannot avoid - data is imported). If it does I cannot loop through my lines anymore because one dataset does not consist of 13 values anymore and they are split across two lines.
Each new line usually starts with a date like 30.12.2020
How can I check if there are line brakes within my string which are not followed by a date and delete them?
-
ArgumentNullException: Value cannot be null. (Parameter 'user')
I have problem with my code based on this tutorial. I tried to make list of roles and add or delete user from specific role.
This is my code in controller:
[HttpPost] public async Task<IActionResult> EditUsersInRole(List<UserRoleViewModel> model, string roleId) { ViewBag.roleId = roleId; var role = await roleManager.FindByIdAsync(roleId); if (role == null) { ViewBag.ErrorMessage = $"Role with ID = {roleId} cannot be found."; return View("NotFound"); } for (int i = 0; i < model.Count; i++) { var user = await userManager.FindByIdAsync(model[i].UserId); IdentityResult result = null; if (model[i].IsSelected && !(await userManager.IsInRoleAsync(user, role.Name))) { result = await userManager.AddToRoleAsync(user, role.Name); } else if (!model[i].IsSelected && await userManager.IsInRoleAsync(user, role.Name)) { result = await userManager.RemoveFromRoleAsync(user, role.Name); } else { continue; } if (result.Succeeded) { if (i < (model.Count - 1)) continue; else return RedirectToAction("EditRole", new { Id = roleId }); } } return RedirectToAction("EditRole", new { Id = roleId }); }
EditUsersInRole View code:
@model List<collector_forum.ViewModels.UserRoleViewModel> @{ var roleId = ViewBag.roleId; } <form method="post"> <div class="card"> <div class="card-header"> <h2>Add or remove users from this role</h2> </div> <div class="card-body"> @for (int i = 0; i < Model.Count; i++) { <div class="form-check m-1"> <input asp-for="@Model[i].IsSelected" class="form-check-input" /> <label class="form-check-label" asp-for="@Model[i].IsSelected"> @Model[i].UserName </label> </div> } </div> <div class="card-footer"> <input type="submit" value="Update" class="btn btn-primary" style="width: auto;" /> <a asp-action="EditRole" asp-route-id="@roleId" class="btn btn-primary" style="width: auto;">Cancel</a> </div> </div> </form>
And the ViewModel:
namespace collector_forum.ViewModels { public class UserRoleViewModel { public string UserId { get; set; } public string UserName { get; set; } public bool IsSelected { get; set; } } }
Then I got this error:
ArgumentNullException: Value cannot be null. (Parameter 'user')
Error appears Error
I am helpless right now
Please help me.
//Edit.
Html view before posting - screenshot
Chrome Developer Tools -> Network tab before click on "Update"
And after hit "Update" view
-
Fresh ASP.NET MVC web application doesn't render menu/mobile menu correctly
I created a new project in Visual Studio 2017 and selected ASP.NET web application (.NET framework) then selected MVC as the project template. It created all the files and loaded the solution. Upon running the new project I noticed the menu was not being rendered correctly. The mobile menu is not rendered correctly either. And the Learn More buttons are wrong. I don't understand. I didn't make any changes. Anyone else have this issue? Is something missing or not loading? I don't see any errors or warning in the browser console.
Desktop
Mobile
It should look like this
-
Asp.net Identity: obtain client local time zone when logging in or returning to web application
Is it possible to read in the user's local timezone from the browser when they go to our website? Either logging in or where they are already logged in?
Reason: I would like to read the local time zone when they go to our URL (MVC asp.net web application) and store that in memory while they are in the application so we can convert to their local timezone from our UTC datetimes that are stored in the database.
Thanks.