【问题标题】:How i can store bearer tokens on server-side and after validate how to delete on logout in Web API 2?我如何在服务器端存储不记名令牌以及验证如何在 Web API 2 中注销时删除?
【发布时间】:2018-08-24 06:29:09
【问题描述】:

我正在创建 web api 项目,默认情况下它有帐户控制器,我在其中找到了 Register、Logout 和其他 api。 使用 Web API 2、OAuth 和 OWIN

通过 /token 我生成了不记名令牌和他的过期时间,存储在 OWIN Cookie 身份验证中。

我的问题是:-

  • 如何在用户注销时删除此令牌,因为在使用注销服务后,我仍然可以调用带有 [Authorize] 修饰的列表数据
  • 我可以将它存储在数据库中并验证它,当用户注销时删除它

退出代码如下

    // POST api/Account/Logout
    [Route("Logout")]
    public IHttpActionResult Logout()
    {
        // Authentication.SignOut(CookieAuthenticationDefaults.AuthenticationType);
return ok();

}

我的 /token 代码如下

 public void ConfigureAuth(IAppBuilder app)
    {
        // Configure the db context and user manager to use a single instance per request
        app.CreatePerOwinContext(ApplicationDbContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);

        // Enable the application to use a cookie to store information for the signed in user
        // and to use a cookie to temporarily store information about a user logging in with a third party login provider
        app.UseCookieAuthentication(new CookieAuthenticationOptions());
        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

        // Configure the application for OAuth based flow
        PublicClientId = "self";
        OAuthOptions = new OAuthAuthorizationServerOptions
        {
            TokenEndpointPath = new PathString("/Token"),
            Provider = new ApplicationOAuthProvider(PublicClientId),
            AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
            // In production mode set AllowInsecureHttp = false
            AllowInsecureHttp = true
        };

}

【问题讨论】:

    标签: asp.net-mvc authentication asp.net-web-api owin restful-authentication


    【解决方案1】:

    您不能删除服务器中的令牌,但是您可以忘记客户端中的令牌。 或者你可以创建刷新令牌服务

    只需创建类

    public class SimpleRefreshTokenProvider : IAuthenticationTokenProvider {
            private static ConcurrentDictionary<string, AuthenticationTicket> _refreshTokens = new ConcurrentDictionary<string, AuthenticationTicket>();
            public async Task CreateAsync(AuthenticationTokenCreateContext context) {
                var guid = Guid.NewGuid().ToString();
                _refreshTokens.TryAdd(guid, context.Ticket);
               context.SetToken(guid);
            }
    
            public async Task ReceiveAsync(AuthenticationTokenReceiveContext context) {
                AuthenticationTicket ticket;
                if (_refreshTokens.TryRemove(context.Token, out ticket)) {
                    context.SetTicket(ticket);
                }
            } 
        }
    

    在里面注册

    static Startup() {
                OAuthOptions = new OAuthAuthorizationServerOptions {
                    TokenEndpointPath = new PathString("/api/Login"),
                    Provider = new OAuthProvider(),
                    RefreshTokenProvider = new SimpleRefreshTokenProvider(),
                    AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(5),
                    AllowInsecureHttp = true,
                };
            }
    

    覆盖 OAuthAuthorizationServerProvider

    public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context) {       
            if (context.TryGetBasicCredentials(out clientId, out clientSecret)) {
                if (clientSecret == "secret") {
                    context.OwinContext.Set<string>("as:client_id", clientId);
                    context.Validated();
                }
            }
        return Task.FromResult<object>(null);
    

    }

    你的服务请求应该是这样的

    Authorization: Basic Y2xpZW50MTpzZWNyZXQ=
    Content-Type: application/x-www-form-urlencoded
    
    username=care%40agentExperience.com&password=test&client_id=client1&clientSecret=secret&grant_type=refresh_token
    

    【讨论】:

    • ,如果服务器不幸重启。令牌会自动删除吗?如果是,那么我需要忽略这种情况,但不知道如何
    • 那么我将如何从应用程序中注销用户,假设我从客户端删除了令牌如果有人获得令牌并将访问信息会发生什么情况。如何处理这个
    • 如果没有可用的互联网连接,用户意外关闭计算机,计算机崩溃,在这种情况下,您永远无法使用注销从数据库中删除令牌。
    • 最小化您的令牌到期时间
    • 什么是clientId,clientSecret? client_id=client1&clientSecret=secret
    猜你喜欢
    • 2014-02-01
    • 2016-09-27
    • 2018-07-11
    • 2016-04-12
    • 2017-10-30
    • 1970-01-01
    • 1970-01-01
    • 2015-05-25
    • 2016-08-06
    相关资源
    最近更新 更多