我想在Ajax上使用webservices.使用ajax调用webservice时,安全性的最佳方法是什么?我想防止远程调用应用程序.
我有以下web服务,例如:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class Users : System.Web.Services.WebService
{
[WebMethod]
public List<User> GetUsers()
{
List<User> listUsers = new List<User>();
User user = new User();
user.Id = 1;
user.Name = "John";
User user2 = new User();
user2.Id = 2;
user2.Name = "Martin";
listUsers.Add(user);
listUsers.Add(user2);
return listUsers;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我用jquery ajax调用webservice:
<script type="text/javascript">
$(function () {
getUsers();
function getUsers() {
$.ajax({
type: "POST",
url: "Webservices/Users.asmx/GetUsers",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json", …Run Code Online (Sandbox Code Playgroud) 我有两张桌子Client和ClientSecret。这些表具有以下结构:
public class Client
{
public int Id { get; set; }
public string ClientId { get; set; }
public string ClientName { get; set; }
public List<ClientSecret> ClientSecrets { get; set; }
}
public class ClientSecret
{
public int Id { get; set; }
public string Description { get; set; }
public string Value { get; set; }
public DateTime? Expiration { get; set; }
public Client Client { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我需要全部创建一个新Client …
我尝试将 Windows 身份验证和 JWT 与 .NET Core 2.1 一起使用。
我有以下身份验证的启动设置:
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = IISDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "Test",
ValidAudience = "Test",
IssuerSigningKey = JwtSecurityKey.Create("677efa87-aa4d-42d6-adc8-9f866e5f75f7")
};
options.Events = new JwtBearerEvents()
{
OnAuthenticationFailed = OnAuthenticationFailed
};
});
Run Code Online (Sandbox Code Playgroud)
IIS 设置:
"iisSettings": {
"windowsAuthentication": true,
"anonymousAuthentication": true,
..
}
Run Code Online (Sandbox Code Playgroud)
我尝试使用以下代码片段来创建带有 Windows 身份验证的 JWT 令牌:
[Route("api/[controller]")]
[ApiController]
[Authorize(AuthenticationSchemes = …Run Code Online (Sandbox Code Playgroud) 我想将ASP.NET MVC 5用于我的Web应用程序.我需要使用windows authentication.
如果我使用windows authenticationwhere是读取用户信息(用户ID和角色)的最佳位置并将其存储到Session?
我有从数据库中通过用户名获取用户信息的方法,如下所示:
public class CurrentUser
{
public int UserId { get; set; }
public string UserName { get; set; }
public Roles Roles { get; set; }
}
public enum Roles
{
Administrator,
Editor,
Reader
}
public class AuthService
{
public CurrentUser GetUserInfo(string userName)
{
var currentUser = new CurrentUser();
//load from DB
return currentUser;
}
}
Run Code Online (Sandbox Code Playgroud) 我想创建一个自定义授权属性来检查角色和网址路径.
我已经找到了使用基于策略的授权在Asp.Net Core中执行此操作的方法,但我已经尝试实现它,但是我无法使用inclming url获取HttpContext.
AuthorizationHandlerContext 无法访问HttpContext可能.
如何通过url路径获取当前的HttpContext?是可以这样做还是用其他方式?
我已尝试使用此代码创建自定义策略:
public class RoleUrlValidationHandler : AuthorizationHandler<RoleUrlValidationRequirement>
{
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, RoleUrlValidationRequirement requirement)
{
var path = //Here I need get current url path for example - /api/posts/4545411
var pathPart = path.Split('/');
var clientId = pathPart[3];
if (context.User.IsInRole(clientId))
{
context.Succeed(requirement);
}
return Task.CompletedTask;
}
}
Run Code Online (Sandbox Code Playgroud)
我想创建以下内容:
[Authorize(Policy="RoleUrlValidation")] //Get ClientId from Url and check User's roles
public class PostsController : Controller
{
public ActionResult Get()
{
}
}
Run Code Online (Sandbox Code Playgroud) ResourceApi我在我的东西中创建了一个IndetityServer4这样的东西:
我定义了一个名为 的 ApiResourceAPI 1并直接指定声明 -name, sub对于此 api 资源,我扩展了此资源并指定了两个名为Api1.Read和 的范围Api1.Write,并为每个范围指定了 API 特定部分所需的特定声明,但我不这样做了解 ApiResource 和 Scopes 中使用的 Claims 有什么不同?
Claims直接连接在ApiResource和 中使用的声明是什么意思Scope?
我已尝试仅限制 ApiResource 中的 UserClaims,sub and name但如果我想Api1.Write声明role它是在访问令牌中发送的,但 Api1仅在定义中指定name and sub- 为什么 UserClaims 在 ApiResource 中定义?
var apiResource = new ApiResource
{
Name = "Api1",
UserClaims = new List<string> { "name", "sub" },
Scopes = new List<Scope> …Run Code Online (Sandbox Code Playgroud) 我创建了一个 Asp.Net Core MVC 应用程序。我想处理两种类型的错误。
我创建了两个例外:UserFriendlyException和UserFriendlyViewException.
我试图创建ExceptionFilter我需要根据这些规则处理这两个异常的:
如果UserFriendlyViewException调用异常,那么我想返回带有原始 ViewName 的 ViewResultAddModelError并返回原始模型。
如果异常UserFriendlyException被调用,那么我想重定向到Error查看。
这是我的ExceptionFilterAttribute:
public class ControllerExceptionFilterAttribute : ExceptionFilterAttribute
{
private readonly ITempDataDictionaryFactory _tempDataDictionaryFactory;
private readonly IModelMetadataProvider _modelMetadataProvider;
public ControllerExceptionFilterAttribute(ITempDataDictionaryFactory tempDataDictionaryFactory,
IModelMetadataProvider modelMetadataProvider)
{
_tempDataDictionaryFactory = tempDataDictionaryFactory;
_modelMetadataProvider = modelMetadataProvider;
}
public override void OnException(ExceptionContext context)
{
if (!(context.Exception is UserFriendlyException) && !(context.Exception is UserFriendlyViewException)) return;
var tempData = _tempDataDictionaryFactory.GetTempData(context.HttpContext);
//CreateNotification(NotificationHelpers.AlertType.Error, tempData, context.Exception.Message);
if (!tempData.ContainsKey(NotificationHelpers.NotificationKey)) …Run Code Online (Sandbox Code Playgroud) 我尝试在以下项目结构中使用 Asp.Net Core 创建 Razor 类库:
我在我的网络应用程序中使用了这些设置来进行Startup课堂本地化:
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
.AddViewLocalization(
LanguageViewLocationExpanderFormat.Suffix,
opts => { opts.ResourcesPath = "Resources"; })
.AddDataAnnotationsLocalization();
services.Configure<RequestLocalizationOptions>(
opts =>
{
var supportedCultures = new[]
{
new CultureInfo("en-US"),
new CultureInfo("en")
};
opts.DefaultRequestCulture = new RequestCulture("en");
opts.SupportedCultures = supportedCultures;
opts.SupportedUICultures = supportedCultures;
});
....
var options = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
app.UseRequestLocalization(options.Value);
Run Code Online (Sandbox Code Playgroud)
在Index.cshtml:
@using Microsoft.AspNetCore.Mvc.Localization
@inject IViewLocalizer Localizer
<h1>@Localizer["Title"]</h1>
Run Code Online (Sandbox Code Playgroud)
不幸的是,结果只是字符串“Title”。我无法从 Razor 类库加载这些 resx 文件。
如何像上面那样使用 Razor 类库中的本地化?
更新:这是非常相似的用例 - https://github.com/aspnet/Localization/issues/328 - 提供了一些示例。
我想创建将包含以下扩展方法的 .Net Core 类库:
public static class MyServiceExtensions
{
public static IServiceCollection AddMyService<TUserDto, TUserDtoKey, TUser, TUserKey>(this IServiceCollection services)
where TUserDto : UserDto<TUserDtoKey>
where TUser : User<TUserKey>
{
services.AddAutoMapper(config =>
{
config.AddProfile<UserMappingProfile<TUserDto, TUserDtoKey, TUser, TUserKey>>();
});
return services;
}
}
Run Code Online (Sandbox Code Playgroud)
我有以下 Automapper 配置文件:
public class UserMappingProfile<TUserDto, TUserDtoKey, TUser, TUserKey> : Profile
where TUserDto : UserDto<TUserDtoKey>
where TUser : User<TUserKey>
{
public UserMappingProfile()
{
CreateMap<TUserDto, TUser>(MemberList.Destination)
.ForMember(x => x.Id, opts => opts.MapFrom(x => x.UserId));
CreateMap<TUser, TUserDto > (MemberList.Source)
.ForMember(x => x.UserId, opts …Run Code Online (Sandbox Code Playgroud) 我目前正在使用这种方法来加载实体及其相关实体AsNoTracking:
await DbContext.Clients
.Include(x => x.AllowedGrantTypes)
.Include(x => x.RedirectUris)
.Include(x => x.PostLogoutRedirectUris)
.Include(x => x.AllowedScopes)
.Include(x => x.ClientSecrets)
.Include(x => x.Claims)
.Include(x => x.IdentityProviderRestrictions)
.Include(x => x.AllowedCorsOrigins)
.Include(x => x.Properties)
.Where(x => x.Id == clientId)
.AsNoTracking()
.SingleOrDefaultAsync();
Run Code Online (Sandbox Code Playgroud)
Github 上的代码详细信息:链接
这可行,但迁移到 EF Core 3.0 后该查询非常慢。
我发现可以通过显式加载相关实体来解决此性能问题,如下所示:
IQueryable<Entities.Client> baseQuery = Context.Clients
.Where(x => x.Id == clientId)
.Take(1);
var client = await baseQuery.FirstOrDefaultAsync();
if (client == null) return null;
await baseQuery.Include(x => x.AllowedCorsOrigins).SelectMany(c => c.AllowedCorsOrigins).LoadAsync();
await baseQuery.Include(x => x.AllowedGrantTypes).SelectMany(c => …Run Code Online (Sandbox Code Playgroud) asp.net-core ×7
c# ×3
.net-core ×2
asp.net ×2
ajax ×1
automapper ×1
claims ×1
ef-core-3.0 ×1
jquery ×1
jwt ×1
razor ×1
scope ×1
session ×1
web-services ×1