加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-web-api – 从数据存储实现动态OAuthBearerServerOption

发布时间:2020-12-16 09:13:42 所属栏目:asp.Net 来源:网络整理
导读:这篇文章的上下文涉及ASP.NET Web API 2.2 OWIN 环境是具有OWIN服务器和Web Api的单个应用程序. 背景: 在Startup类中,必须指定OAuthBearerServerOptions提供给OAuthBearerAuthenticationProvider.这些选项是在OWIN服务器启动期间创建的.在OAuthBearerServer
这篇文章的上下文涉及ASP.NET Web API 2.2 OWIN
环境是具有OWIN服务器和Web Api的单个应用程序.

背景:

在Startup类中,必须指定OAuthBearerServerOptions提供给OAuthBearerAuthenticationProvider.这些选项是在OWIN服务器启动期间创建的.在OAuthBearerServerOptions,我必须指定AccessTokenExpireTimeSpan,以便我可以确保令牌到期.

问题

我必须能够基于每个身份验证请求动态指定过期时间跨度.我不确定这是否可以做到并且在想:

>可以吗?
>如果是的话;在哪一点上我可以执行此查找并分配到期日期?

启动配置内容:

var config = new HttpConfiguration();

    WebApiConfig.Register(config);


    var container = builder.Build();
    config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

    var OAuthServerOptions = new OAuthAuthorizationServerOptions()
    {
        AllowInsecureHttp = true,TokenEndpointPath = new PathString("/OAuth"),AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(**THIS NEEDS TO BE DYNAMIC**)),Provider = new AuthorizationServerProvider()
    };

    //STOP!!!!!!!!
    //DO NOT CHANGE THE ORDER OF THE BELOW app.Use statements!!!!!

    //Token Generation 
    app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll); //this MUST come before oauth registration
    app.USEOAuthAuthorizationServer(OAuthServerOptions);
    app.USEOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()
    {
        Provider = new BearerProvider()
    });
    app.UseAutofacMiddleware(container); //this MUST come before UseAutofacWebApi
    app.UseAutofacWebApi(config);//this MUST come before app.UseWebApi
    app.UseWebApi(config);

我开始搞乱BearerProvider类(请参阅上面的app.USEOAuthBearerAuthentication以了解我使用此类的位置)以及具体的ValidateIdentity方法,但不确定这是否是auth工作流中设置此值的正确点.这似乎是合适的,但我寻求验证我的立场.

public class BearerProvider : OAuthBearerAuthenticationProvider
{
    public override async Task RequestToken(OAuthRequestTokenContext context)
    {
        await base.RequestToken(context);

        //No token? attempt to retrieve from query string
        if (String.IsNullOrEmpty(context.Token))
        {
            context.Token = context.Request.Query.Get("access_token");

        }
    }
    public override Task ValidateIdentity(OAuthValidateIdentityContext context)
    {
        //context.Ticket.Properties.ExpiresUtc= //SOME DB CALL TO FIND OUT EXPIRE VALUE..IS THIS PROPER?
        return base.ValidateIdentity(context);
    }
}

提前致谢!

解决方法

设置context.Options.AccessTokenExpireTimeSpan实际上将更改全局值,并影响所有不适用于原始需求的请求.

正确的位置是TokenEndpoint方法.

public override Task TokenEndpoint(OAuthTokenEndpointContext context)
{
    ...

    if (someCondition)
    {
        context.Properties.ExpiresUtc = GetExpirationDateFromDB();
    }

    ...
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读