如何在服务器端存储承载令牌,并在验证如何在Web API 2中注销时删除?

时间:2018-03-15 12:31:02

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

我正在创建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();

}

我的/令牌代码在

之下
 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
        };

}

1 个答案:

答案 0 :(得分: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