我试图了解MVC 5中单页应用程序模板中新的OWIN Bearer Token身份验证过程.如果我错了请更正我,对于OAuth密码客户端身份验证流程,承载令牌身份验证通过检查http授权请求标头来工作对于承载访问令牌代码,以查看请求是否经过身份验证,它不依赖cookie来检查特定请求是否经过身份验证.
根据这篇文章:
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
using (IdentityManager identityManager = _identityManagerFactory.CreateStoreManager())
{
if (!await identityManager.Passwords.CheckPasswordAsync(context.UserName, context.Password))
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
string userId = await identityManager.Logins.GetUserIdForLocalLoginAsync(context.UserName);
IEnumerable<Claim> claims = await GetClaimsAsync(identityManager, userId);
ClaimsIdentity oAuthIdentity = CreateIdentity(identityManager, claims,
context.Options.AuthenticationType);
ClaimsIdentity cookiesIdentity = CreateIdentity(identityManager, claims,
_cookieOptions.AuthenticationType);
AuthenticationProperties properties = await CreatePropertiesAsync(identityManager, userId);
AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
context.Validated(ticket);
context.Request.Context.Authentication.SignIn(cookiesIdentity);
}
}
Run Code Online (Sandbox Code Playgroud)
GrantReourceOwnerCredentials函数不仅使用以下行构成票证:context.Validated(ticket); 但它也组成了一个cookie标识,并使用以下行将其设置为cookie:context.Request.Context.Authentication.SignIn(cookiesIdentity);
所以我的问题是,这个函数中cookie的确切目的是什么?AuthenticationTicket不应该足够用于身份验证吗?
我在一个大型.net MVC 5 Web解决方案中有一个api特定项目.我正在利用开箱即用的WebApi2模板通过api对用户进行身份验证.使用个人帐户进行身份验证,获取访问令牌所需的请求正文是:
grant_type=password&username={someuser}&password={somepassword}
Run Code Online (Sandbox Code Playgroud)
这按预期工作.
但是,我需要在scaffolded方法"GrantResourceOwnerCredentials"中添加第三维.除了检查用户名/密码之外,我还需要添加一个设备ID,用于限制从用户帐户到特定设备的访问.目前尚不清楚如何将这些额外的请求参数添加到已定义的"OAuthGrantResourceOwnerCredentialsContext"中.此上下文目前为UserName和Password腾出空间,但显然我需要包含更多内容.
我的问题很简单,是否有一种标准方法可以扩展OWIN OAuth2令牌请求的登录要求以包含更多数据?而且,您如何在.NET WebApi2环境中可靠地做到这一点?
有没有办法可以使用新IHttpActionResult界面返回HttpStatusCode.NoContent响应消息?
我目前正在使用return new HttpResponseMessage( HttpStatusCode.NoContent );
并希望将其转换为return NoContent();.
IHttpActionResult已经得到了Ok(),Conflict()并且NotFound()但是我找不到任何的Forbidden()和NoContent()我需要在我的项目中使用.
添加其他结果类型有多容易?
在ASP.NET Web API 2中,以下内容有何区别?
public async Task<IEnumerable<MyItem>> GetMyItems()
{
//... code ..., var myItems = await ...
return myItems;
}
Run Code Online (Sandbox Code Playgroud)
和
public async Task<IQueryable<MyItem>> GetMyItems()
{
//... code ..., var myItems = await ...
return myItems;
}
Run Code Online (Sandbox Code Playgroud)
和
public async Task<IHttpActionResult> GetMyItems()
{
//... code ..., var myItems = await ...
return Ok(myItems);
}
Run Code Online (Sandbox Code Playgroud)
我应该退货IHttpActionResult还是IEnumerable<MyItem>/ IQueryable<MyItem>?
我正在尝试在构建于OWIN中间件(使用Owin.Host.SystemWeb的IIS HOST)之上的ASP.NET Web API 2.1项目中创建统一的错误处理/报告.目前我使用了一个自定义异常记录器,它继承System.Web.Http.ExceptionHandling.ExceptionLogger并使用NLog记录所有异常,如下面的代码所示:
public class NLogExceptionLogger : ExceptionLogger
{
private static readonly Logger Nlog = LogManager.GetCurrentClassLogger();
public override void Log(ExceptionLoggerContext context)
{
//Log using NLog
}
}
Run Code Online (Sandbox Code Playgroud)
我想将所有API异常的响应主体更改为友好的统一响应,该响应使用System.Web.Http.ExceptionHandling.ExceptionHandler以下代码隐藏所有异常详细信息:
public class ContentNegotiatedExceptionHandler : ExceptionHandler
{
public override void Handle(ExceptionHandlerContext context)
{
var errorDataModel = new ErrorDataModel
{
Message = "Internal server error occurred, error has been reported!",
Details = context.Exception.Message,
ErrorReference = context.Exception.Data["ErrorReference"] != null ? context.Exception.Data["ErrorReference"].ToString() : string.Empty,
DateTime = DateTime.UtcNow
};
var response …Run Code Online (Sandbox Code Playgroud) asp.net-web-api owin katana asp.net-web-api2 owin-middleware
我有一个现有的Web API 2服务,需要修改其中一个方法以将自定义对象作为另一个参数,目前该方法有一个参数,它是来自URL的简单字符串.将自定义对象添加为参数后,从.NET Windows应用程序调用服务时,我现在收到415不支持的媒体类型错误.有趣的是,我可以使用javascript和jquery ajax方法成功调用此方法.
Web API 2服务方法如下所示:
<HttpPost>
<HttpGet>
<Route("{view}")>
Public Function GetResultsWithView(view As String, pPaging As Paging) As HttpResponseMessage
Dim resp As New HttpResponseMessage
Dim lstrFetchXml As String = String.Empty
Dim lstrResults As String = String.Empty
Try
'... do some work here to generate xml string for the response
'// write xml results to response
resp.Content = New StringContent(lstrResults)
resp.Content.Headers.ContentType.MediaType = "text/xml"
resp.Headers.Add("Status-Message", "Query executed successfully")
resp.StatusCode = HttpStatusCode.OK
Catch ex As Exception
resp.StatusCode = HttpStatusCode.InternalServerError
resp.Headers.Add("Status-Message", String.Format("Error …Run Code Online (Sandbox Code Playgroud) vb.net json asp.net-web-api http-status-code-415 asp.net-web-api2
我正在做一些研究工作,以便使用Bearer令牌作为身份验证机制(即AngularJS UI,通过Web API [2]项目中的OWIN进行身份验证).
我的登录工作正常,角色信息和一切都很好,但我无法获得登出令牌.
我的启动配置是这样的:
OAuthOptions = new OAuthAuthorizationServerOptions() {
TokenEndpointPath = new PathString("/Token"),
Provider = new ApplicationOAuthProvider(PublicClientId),
AccessTokenExpireTimeSpan = SESSION_TIMEOUT,
AllowInsecureHttp = true
};
Run Code Online (Sandbox Code Playgroud)
我的退出操作就是这样:
public HttpResponseMessage Logout() {
var authentication = HttpContext.Current.GetOwinContext().Authentication;
authentication.SignOut(DefaultAuthenticationTypes.ExternalBearer);
return new HttpResponseMessage(HttpStatusCode.OK);
}
Run Code Online (Sandbox Code Playgroud)
为简洁起见,我已将所有身份验证内容留下,但确认我在设置令牌时使用的是ExternalBearer.
在我的UI中,我将令牌存储在本地存储中(此处不涉及cookie,这是一个深思熟虑的设计决策).所以我的UI上有一个注销按钮,注销了Logout操作,代码运行正常.
但是,如果我随后打了上需要授权的API的行动,请求仍然可以通过(即用户通过身份认证,即使他们去应该已经退出.
要么我错过了一些非常明显的东西(不会是第一次;-)或者还有更基本的东西 - 最后我正在打@leastprivilege因为我知道这是他们的区域.
我们将非常感激地提供任何帮助或见解.
我唯一能想到的是令牌在服务器/ API端是无状态的,因此无法过期或退出.
如果是这种情况,我想我可以:
a)添加一个刷新令牌,创建一个过去到期的新令牌 - 这甚至可以工作吗? - 实际取消它,它会发出一个新的令牌......旧的令牌仍然有效
b)将持有者令牌存储在数据库中并每次检查,在注销时删除令牌(自然盐渍,散列等).然而,这只是让我们回到拥有状态服务器.
c)当有人明确注销时,我可以(并且将会)从本地存储中删除令牌,但是如果baddy可以拦截令牌,则令牌在技术上仍然有效.当然,以上所有都将通过SSL,这应该会抑制坏人/女孩.
d)也许这就是为什么很多人将持有者令牌存储在cookie中(作为存储机制),所以一旦你注销,cookie将在下次刷新时删除.
对不起,以上是一个大脑转储,只是想抢先问任何问题
当WebAPI用户发生意外错误时,会看到整个堆栈跟踪.
我相信显示整个堆栈跟踪是不安全的.
停止向我的用户显示整个跟踪的默认行为是什么?
只是一个友好的信息,就像说Internal Server Error一个人就够了.正确?
有什么想法?
<?xml version="1.0"?>
<Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>The method or operation is not implemented.</ExceptionMessage>
<ExceptionType>System.NotImplementedException</ExceptionType>
<StackTrace> at MyCompany.BLL.RequirementOfService.Employee1.Employee1Service.MakeRequirementOfService(RequirementOfService RequirementOfService) in d:\Projects\MyFolder\Testing\WhiteBox\MyCompany.BAL.RequirementOfService\Employee1\Employee1Service.cs:line 37
at MyCompany.BLL.RequirementOfService.RequirementOfServiceBLL.MakeRequirementOfService(RequirementOfService RequirementOfService) in d:\Projects\MyFolder\Testing\WhiteBox\MyCompany.BAL.RequirementOfService\RequirementOfServiceBLL.cs:line 76
at MyCompany.RequirementOfService.Windsor.RequirementOfServiceProvider.MakeRequirementOfService(RequirementOfService RequirementOfService) in d:\Projects\MyFolder\Testing\WhiteBox\MyCompany.RequirementOfService\Windsor\RequirementOfServiceProvider.cs:line 47
at MyCompany.RequirementOfService.RequirementOfService.Controllers.RequirementOfServiceController.Post(RequirementOfServiceDTO RequirementOfServiceDTO) in d:\Projects\MyFolder\Testing\WhiteBox\MyCompany.RequirementOfService\RequirementOfService\Controllers\RequirementOfServiceController.cs:line 87
at lambda_method(Closure , Object , Object[] )
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.<GetExecutor>b__9(Object instance, Object[] methodParameters)
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)
--- End of stack trace …Run Code Online (Sandbox Code Playgroud) 这可能是非常基本的东西,但我无法弄清楚我哪里出错了.
我试图从POST的主体中获取一个字符串,但"jsonString"只显示为null.我也想避免使用模型,但也许这是不可能的.我用PostMan打的那段代码是这个块:
[Route("Edit/Test")]
[HttpPost]
public void Test(int id, [FromBody] string jsonString)
{
...
}
Run Code Online (Sandbox Code Playgroud)
也许这是我对邮递员做错的事情,但我一直试图在身体的价值部分使用"= test"(如在关于这个主题的其他问题中看到的那样) - x-www-form-urlencoded section with密钥作为jsonString而没有.我也尝试过使用raw-text和raw-text/plain.我得到了身份证,所以我知道网址是正确的.任何有关这方面的帮助将不胜感激.
PostMan目前设置如下:
POST http://localhost:8000/Edit/Test?id=111
key = id value = 111
Body - x-www-form-urlencoded
key = jsonString value = "=test"
Run Code Online (Sandbox Code Playgroud) c# asp.net-web-api asp.net-web-api-routing asp.net-web-api2 postman
我将Microsoft.AspNetCore从2.0.3升级到2.0.5,而我的WebAPI项目虽然在本地成功运行,却无法在生产(IIS)中启动.在升级之前,生产中的一切都很好.日志目录中生成的错误消息如下:
Error:
An assembly specified in the application dependencies manifest (MyProject.WebAPI.deps.json) was not found:
package: 'Microsoft.AspNetCore.Mvc.Abstractions', version: '2.0.2'
path: 'lib/netstandard2.0/Microsoft.AspNetCore.Mvc.Abstractions.dll'
This assembly was expected to be in the local runtime store as the application was published using the following target manifest files:
aspnetcore-store-2.0.5.xml
Run Code Online (Sandbox Code Playgroud)
有人可以向我解释这究竟意味着什么的细节吗?我认为它的版本不匹配,但为什么会发生这种情况?我认为NuGet包的最新稳定版本不应该有这样的问题.
我能够通过将Microsoft.AspNetCore.All从2.0.5降级到2.0.3来解决这个问题,但是我想找到一个更好的解决方案来解决这个问题,这样我就可以使用这个软件包的最新版本了.
upgrade nuget-package asp.net-web-api2 .net-core asp.net-core
asp.net-web-api2 ×10
c# ×4
owin ×3
asp.net ×2
katana ×2
.net ×1
.net-core ×1
asp.net-core ×1
async-await ×1
json ×1
oauth-2.0 ×1
postman ×1
stack-trace ×1
upgrade ×1
vb.net ×1