Web API / OWIN, SignalR & Authorization

后端 未结 3 644
误落风尘
误落风尘 2021-01-30 07:29

I am developing a prototype of an AngularJS, Web API, SignalR application as a potential starting point for a new project in VS 2013.

At this stage, I\'m pretty much usi

3条回答
  •  -上瘾入骨i
    2021-01-30 08:03

    I use a class like this:

    public class OAuthTokenProvider : OAuthBearerAuthenticationProvider
    {
        private List> _locations;
        private readonly Regex _bearerRegex = new Regex("((B|b)earer\\s)");
        private const string AuthHeader = "Authorization";
    
        /// 
        /// By Default the Token will be searched for on the "Authorization" header.
        ///  pass additional getters that might return a token string
        /// 
        /// 
        public OAuthTokenProvider(params Func[] locations)
        {
            _locations = locations.ToList();
            //Header is used by default
            _locations.Add(x => x.Headers.Get(AuthHeader));
        }
    
        public override Task RequestToken(OAuthRequestTokenContext context)
        {
            var getter = _locations.FirstOrDefault(x => !String.IsNullOrWhiteSpace(x(context.Request)));
            if (getter != null)
            {
                var tokenStr = getter(context.Request);
                context.Token = _bearerRegex.Replace(tokenStr, "").Trim();
            }
            return Task.FromResult(null);
        }
    }
    
    
    

    Which instead of just passing on the token to the header, parses it and sets it on the context.

    Then it could be used in your app configuration like this:

    app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
    {
        Provider = new OAuthTokenProvider(
             req => req.Query.Get("bearer_token"),
             req => req.Query.Get("access_token"),
             req => req.Query.Get("token"),
             req => req.Headers.Get("X-Token"))    
    });
    

    Then the following styles of requests would have their token un-encrypted, for use with authentication and authorization:

    GET https://www.myapp.com/authorized/endpoint?bearer_token=123ABC HTTP/1.1
    GET https://www.myapp.com/authorized/endpoint?access_token=123ABC HTTP/1.1
    GET https://www.myapp.com/authorized/endpoint?token=123ABC HTTP/1.1
    
    GET https://www.myapp.com/authorized/endpoint HTTP/1.1
    X-Token: 123ABC
    
    GET https://www.myapp.com/authorized/endpoint HTTP/1.1
    Authorization: 123ABC
    

    提交回复
    热议问题