如何在服务器端和验证后存储承载令牌,如何在Web API 2中注销?

时间:2022-04-22 15:34:34

I am creating web api project, by default it have account controller in which i found Register,Logout and other api's . Using Web API 2, OAuth and OWIN

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

By /token i generated bearer token and his expiry time which is storing in OWIN Cookie authentication.

通过/令牌,我生成了无记名令牌和他的到期时间,它将存储在OWIN Cookie认证中。

My Question is : -

我的问题是:-

  • how i can delete this token when user logout because after using logout service i can still call list data which is decorated with [Authorize]
  • 如何在用户登出时删除这个令牌,因为在使用登出服务之后,我仍然可以调用列表数据,它被修饰为[Authorize]
  • can i store it in database and validate it, delete it when user logout
  • 我可以将它存储在数据库中并进行验证,在用户登出时删除它吗

Logout code is below

注销代码下面

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

}

}

and my /token code is below

我的/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
        };

}

}

1 个解决方案

#1


1  

You cannot delete the token in server, however you can forget the token in client side. Or you can create refresh token service

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

Just create the class

只是创建类

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);
            }
        } 
    }

Register it in

注册在

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

Override OAuthAuthorizationServerProvider

覆盖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);

}

}

and your service request should be look like this

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

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

#1


1  

You cannot delete the token in server, however you can forget the token in client side. Or you can create refresh token service

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

Just create the class

只是创建类

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);
            }
        } 
    }

Register it in

注册在

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

Override OAuthAuthorizationServerProvider

覆盖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);

}

}

and your service request should be look like this

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

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