asp.net-mvc - 我如何在服务器端存储不记名 token 以及验证如何在 Web API 2 中注销时删除?

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

我正在创建 web api 项目,默认情况下它有帐户 Controller ,我在其中找到了注册、注销和其他 api。 使用 Web API 2、OAuth 和 OWIN

通过/token 我生成了不记名 token 及其到期时间,该 token 存储在 OWIN Cookie 身份验证中。

我的问题是:-

  • 我如何在用户注销时删除此 token ,因为在使用注销服务后我仍然可以调用用 [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
        };

最佳答案

您无法删除服务器中的 token ,但您可以忘记客户端中的 token 。 或者您可以创建刷新 token 服务

只需创建类

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

关于asp.net-mvc - 我如何在服务器端存储不记名 token 以及验证如何在 Web API 2 中注销时删除?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49299557/

相关文章:

asp.net-mvc - Asp.Net MVC和 session

linux - 网络设备的 ACL

c# - "Namespace could not be found"带有 ASP 5 和本地项目引用

c# - Asp.net Web api 请求的资源不支持http方法 'GET'

c# - 通过 Web API 实现现场级安全

c# - 无法在 MonoDevelop 中打开 ASP.NET MVC 3 解决方案的测试项目

javascript - 将复杂的字典发布到 Controller

jquery - 查找与用户选择的 <li> 元素关联的数据

PHP:无法限制对页面的访问

java - TargetAuthenticationStrategy,更改优先顺序