Get IPrincipal from OAuth Bearer Token in OWIN

前端 未结 4 1507
说谎
说谎 2020-11-29 22:04

I have successfully added OAuth to my WebAPI 2 project using OWIN. I receive tokens and can use them in the HTTP Header to access resources.

Now I want to use those

4条回答
  •  心在旅途
    2020-11-29 22:25

    I found a part of the solution in this blog post: http://leastprivilege.com/2013/10/31/retrieving-bearer-tokens-from-alternative-locations-in-katanaowin/

    So I created my own Provider as follows:

    public class QueryStringOAuthBearerProvider : OAuthBearerAuthenticationProvider
    {
        public override Task RequestToken(OAuthRequestTokenContext context)
        {
            var value = context.Request.Query.Get("access_token");
    
            if (!string.IsNullOrEmpty(value))
            {
                context.Token = value;
            }
    
            return Task.FromResult(null);
        }
    }
    
    
    

    Then I needed to add it to my App in Startup.Auth.cs like this:

    OAuthBearerOptions = new OAuthBearerAuthenticationOptions()
    {
       Provider = new QueryStringOAuthBearerProvider(),
       AccessTokenProvider = new AuthenticationTokenProvider()
       {
           OnCreate = create,
           OnReceive = receive
       },
    };
    
    app.UseOAuthBearerAuthentication(OAuthBearerOptions);
    

    With a custom AuthenticationTokenProvider, I can retrieve all other values from the token early in the pipeline:

    public static Action create = new Action(c =>
    {
        c.SetToken(c.SerializeTicket());
    });
    
    public static Action receive = new Action(c =>
    {
        c.DeserializeTicket(c.Token);
        c.OwinContext.Environment["Properties"] = c.Ticket.Properties;
    });
    

    And now, for example in my WebSocket Hander, I can retrieve ClientId and others like this:

    IOwinContext owinContext = context.GetOwinContext();
    if (owinContext.Environment.ContainsKey("Properties"))
    {
        AuthenticationProperties properties = owinContext.Environment["Properties"] as AuthenticationProperties;
        string clientId = properties.Dictionary["clientId"];
    ...
     }
    

    提交回复
    热议问题