pau*_*sim 9 c# asp.net-web-api owin http-token-authentication
我有两个申请
计划身份验证如下
现在,在关闭应用程序的服务器端,我需要确认每个请求的令牌都没有被篡改.
到目前为止,我已经编写了下面的代码来创建一个POC.
========================= OWIN配置========
[assembly: OwinStartup(typeof(WebApi.App_Start.Startup))]
namespace WebApi.App_Start
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
HttpConfiguration config = new HttpConfiguration();
ConfigureOAuth(app);
WebApiConfig.Register(config);
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
app.UseWebApi(config);
}
public void ConfigureOAuth(IAppBuilder app)
{
OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = false,
TokenEndpointPath = new PathString("/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
Provider = new SimpleAuthorizationServerProvider(),
};
// Token Generation
app.UseOAuthAuthorizationServer(OAuthServerOptions);
app.UseOAuthBearerAuthentication(new
OAuthBearerAuthenticationOptions());
}
}
}
==============================oAuth Provided========================
public class SimpleAuthorizationServerProvider: OAuthAuthorizationServerProvider
{
public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
context.Validated();
}
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
using (AuthRepository _repo = new AuthRepository())
{
IdentityUser user = _repo.FindUser(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
}
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
identity.AddClaim(new Claim("sub", context.UserName));
identity.AddClaim(new Claim("role", "user"));
context.Validated(identity);
}
}
Run Code Online (Sandbox Code Playgroud)
请帮忙,
谢谢,
@保罗
请建议我如何验证每个请求中的令牌,因为我不知道 OWIN 用于生成令牌的密钥。
您当前的设置(如果您已将其添加app.UseOAuthBearerAuthentication()到 owin 管道)将通过在每个请求上传递的不记名令牌对用户进行身份验证。然后可以通过 找到当前用户HttpContext.Current.User。
然后使用该Authorize属性来决定哪些用户在某些端点上获得授权。以下是允许具有“user”角色的用户访问的示例
[Authorize(Roles="user")]
public class ValuesController : ApiController
{
}
Run Code Online (Sandbox Code Playgroud)
编写代码来验证客户端应用程序上的令牌是正确的,或者应该在身份验证服务器上。
不,您不会在客户端验证令牌,如果您的用户凭据错误,您根本不会获得令牌。这就是您需要知道的全部。 另外,为什么要在客户端验证令牌?
我计划将所有用户管理代码(例如注册用户、更改密码)转移到身份验证服务器,以便我们可以将其重新用于不同的客户端应用程序 - 这是正确的设计实践吗?
重用令牌提供者很常见。为什么要为每个应用发明轮子?构建一个伟大的,或使用第三方,并在您的应用程序中重用它。