【问题标题】:Bearer Token Authentication with ASP.net API使用 ASP.net API 进行不记名令牌身份验证
【发布时间】:2013-10-22 21:14:20
【问题描述】:

我正在研究使用 ASP.net Web API 来设置带有不记名令牌的请求身份验证。当您使用 OWIN 服务器中间件时,加密密钥从哪里来?服务器将如何撤销尚未过期的令牌?

【问题讨论】:

  • 你在看服务还是客户端? OAuthAuthorizationServerMiddleware 或 OAuthBearerAuthenticationMiddleware。对于客户端,您无需撤销令牌,只需验证即可。数据保护 API 用作默认加密方法。中间件选项需要提供适当的 DataProtectionProvider 和/或 SecureDataFormat。
  • 我正在查看接受和发布不记名令牌的服务器端
  • 什么是“加密密钥”?你是说访问令牌吗?

标签: oauth asp.net-web-api owin


【解决方案1】:
  1. OWIN ServerMiddleware 的默认 Tiken 数据保护方法是使用DPAPI (Data Protection API)
  2. 为了在服务器端撤销令牌,需要实现令牌存储。您可以使用AccessTokenProvider.Create来创建和存储Token。

以下是此类场景的示例。 以此为例代码sn-ps。

在 Startup.cs 中注册

 app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions
        {
            AuthorizeEndpointPath = new PathString("/Authorize"),
            TokenEndpointPath = new PathString("/Token"),
            ApplicationCanDisplayErrors = true,
            Provider = new ApplicationOAuthProvider(PublicClientId, UserManagerFactory),
            AuthorizationCodeProvider = new MyAuthenticationTokenProvider(TokenType.Code),
            AccessTokenProvider = new MyAuthenticationTokenProvider(TokenType.Access),
            RefreshTokenProvider = new MyAuthenticationTokenProvider(TokenType.Refresh),
            AuthorizationCodeFormat = new MyFormatProvider("MyAudiences"),
            AccessTokenFormat = new MyFormatProvider("MyAudiences"),
            RefreshTokenFormat = new MyFormatProvider("MyAudiences"))
        });
    }

提供加密:这是基于 Katana 项目中的 JwtFormat。仍然不支持 JwtFormat.protect() 方法。所以你需要创建自己的实现。

    //You need to manage your Key in this class
    public class MyFormatProvider: ISecureDataFormat<AuthenticationTicket>
    {
        public MyFormatProvider(string allowedAudiences)
        {
        }
        public string Protect(AuthenticationTicket data)
        {
            return "encrypted";
        }
        public AuthenticationTicket Unprotect(string protectedText)
        {
            return new AuthenticationTicket(new System.Security.Claims.ClaimsIdentity(), new AuthenticationProperties());
        }
    }

令牌提供者

    public enum TokenType { Code,Access,Refresh }
    public class MyAuthenticationTokenProvider : AuthenticationTokenProvider
    {
        TokenType tokenType = TokenType.Access;
        public MyAuthenticationTokenProvider(TokenType tokenType)
        {

        }
        public override void Create(AuthenticationTokenCreateContext context)
        {
            /*Create Token, Store Token and Tiket info*/
            context.SetToken("MyToken");/*This will call Your MyFormatProvider internally*/
            base.Create(context);
        }

        public override void Receive(AuthenticationTokenReceiveContext context)
        {
            /*retrieve Token and Tiket info to process*/
            base.Receive(context);
        }
    }

【讨论】:

    最近更新 更多