Alb*_*Gao 9 asp.net oauth-2.0 asp.net-web-api owin
我想要的是:
代码怎么样:
public void Configuration(IAppBuilder app)
{
app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions
{
AuthorizeEndpointPath = "/Authorize",
AllowInsecureHttp = true,
Provider = new OAuthAuthorizationServerProvider
{
OnGrantCustomExtension = GrantCustomExtension,
OnValidateClientRedirectUri = ValidateClientRedirectUri,
OnValidateClientAuthentication = ValidateClientAuthentication,
}
});
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
{
Provider = new OAuthBearerAuthenticationProvider
{
//Handles applying the authentication challenge to the response message.
ApplyChallenge=MyApplyChallenge,
//Handles processing OAuth bearer token.
RequestToken=MyRequestToken,
//Handles validating the identity produced from an OAuth bearer token.
ValidateIdentity = MyValidateIdentity,
}
});
app.UseWebApi(new WebApplication3.Config.MyWebApiConfiguration());
}
Run Code Online (Sandbox Code Playgroud)
问题是什么:
的3个属性OAuthBearerAuthenticationProvider
,
ApplyChallenge
,RequestToken
和ValidateIdentity
.如何实现3方法?
在令牌认证过程中,我想到的是解密访问令牌,验证来自客户端的令牌,如果令牌已经过验证,则将令牌的身份放入HttpContext.Current.User
.
我们OAuthBearerAuthenticationProvider
的责任是完成前面的步骤.我对吗?
如您所知,UseOAuthAuthorizationServer负责对用户进行身份验证。然后,UseOAuthBearerAuthentication的工作是确保只有经过身份验证的用户才能访问您的应用程序。通常,这两个作业分配给不同的Web应用程序。看来您的应用程序同时在做。
当然,在某些情况下,您需要覆盖默认的OAuthBearerAuthenticationProvider。也许您愿意,或者也许您不同意,就我而言,ApplicationCookie并不完全适合这种情况。因此,我将第三方JWT令牌存储在Cookie中,而不是在标头中,并使用它来指示用户已通过Web应用程序认证。我还需要重定向到我自己的登录页面,而不是提供401。
这是同时实现这两个功能的实现:
public class CustomOAuthBearerProvider : IOAuthBearerAuthenticationProvider
{
public Task ApplyChallenge(OAuthChallengeContext context)
{
context.Response.Redirect("/Account/Login");
return Task.FromResult<object>(null);
}
public Task RequestToken(OAuthRequestTokenContext context)
{
string token = context.Request.Cookies[SessionKey];
if (!string.IsNullOrEmpty(token))
{
context.Token = token;
}
return Task.FromResult<object>(null);
}
public Task ValidateIdentity(OAuthValidateIdentityContext context)
{
return Task.FromResult<object>(null);
}
}
Run Code Online (Sandbox Code Playgroud)
我不需要在ValidateIdentity中做任何特殊的事情,但是我需要满足该接口。
要进行连接,请告诉您的应用程序将JwtBearerAuthentication与提供程序一起使用:
// controllers with an [Authorize] attribute will be validated with JWT
app.UseJwtBearerAuthentication(
new JwtBearerAuthenticationOptions
{
AllowedAudiences = audiences.ToArray(),
IssuerSecurityTokenProviders = providers.ToArray(),
Provider = new CookieOAuthBearerProvider()
}
);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
11841 次 |
最近记录: |