예제 #1
0
        private OAuthBearerAuthenticationProvider CreateOAuthBearerAuthenticationProvider()
        {
            var tokenProvider = new OAuthBearerAuthenticationProvider
            {
                OnRequestToken = context =>
                {
                    // get the request from the context.
                    var request = context.Request;

                    // if the header collection contains an X-ACCESS-TOKEN key.
                    // this is a hack because I couldn't set the Authorization header from angularjs.
                    if (request.Headers.ContainsKey("X-ACCESS-TOKEN"))
                    {
                        // set the token from the X-ACCESS-TOKEN header.
                        context.Token = request.Headers["X-ACCESS-TOKEN"];

                        // exit out of the method. If this header is set no more token discovery is perfomed.
                        return(Task.FromResult <object>(null));
                    }


                    if (request.Headers.ContainsKey("Authorization"))
                    {
                        context.Token = request.Headers["Authorization"];
                    }
                    else if (request.Cookies["access_token"] != null)
                    {
                        context.Token = request.Cookies["access_token"];
                    }
                    else
                    {
                        var value = request.Query.Get("access_token");
                        if (!string.IsNullOrEmpty(value))
                        {
                            context.Token = value;
                        }
                    }
                    return(Task.FromResult <object>(null));
                }
            };

            return(tokenProvider);
        }
예제 #2
0
        public async Task Token_From_QueryString()
        {
            var provider = new OAuthBearerAuthenticationProvider
            {
                OnRequestToken = c =>
                {
                    var qs = c.OwinContext.Request.Query;
                    c.Token = qs.Get("access_token");

                    return(Task.FromResult(0));
                }
            };

            _options.TokenProvider = provider;

            var client = PipelineFactory.CreateHttpClient(_options);
            var token  = TokenFactory.CreateTokenString(TokenFactory.CreateToken());

            var result = await client.GetAsync("http://test?access_token=" + token);

            result.StatusCode.Should().Be(HttpStatusCode.OK);
        }
예제 #3
0
        public async Task Valid_Token_With_ValidatingIdentity_Deny_Access()
        {
            var provider = new OAuthBearerAuthenticationProvider
            {
                OnValidateIdentity = c =>
                {
                    c.Rejected();

                    return(Task.FromResult(0));
                }
            };

            _options.TokenProvider = provider;

            var client = PipelineFactory.CreateHttpClient(_options);
            var token  = TokenFactory.CreateTokenString(TokenFactory.CreateToken());

            client.SetBearerToken(token);

            var result = await client.GetAsync("http://test");

            result.StatusCode.Should().Be(HttpStatusCode.Unauthorized);
        }
        public static IAppBuilder UseJsonWebToken(this IAppBuilder app, string issuer, string audience, X509Certificate2 signingKey, OAuthBearerAuthenticationProvider location = null)
        {
            if (app == null)
            {
                throw new ArgumentNullException("app");
            }

            var options = new JwtBearerAuthenticationOptions
            {
                AllowedAudiences             = new[] { audience },
                IssuerSecurityTokenProviders = new[]
                {
                    new X509CertificateSecurityTokenProvider(
                        issuer,
                        signingKey)
                }
            };

            if (location != null)
            {
                options.Provider = location;
            }

            app.UseJwtBearerAuthentication(options);

            return(app);
        }
        public static IAppBuilder UseJsonWebToken(this IAppBuilder app, string issuer, string audience, string signingKey, string type = null, OAuthBearerAuthenticationProvider location = null)
        {
            if (app == null)
            {
                throw new ArgumentNullException("app");
            }

            var options = new JwtBearerAuthenticationOptions
            {
                AllowedAudiences             = new[] { audience },
                IssuerSecurityTokenProviders = new[]
                {
                    new SymmetricKeyIssuerSecurityTokenProvider(
                        issuer,
                        signingKey)
                }
            };

            if (!string.IsNullOrEmpty(type))
            {
                options.AuthenticationType = type;
            }

            if (location != null)
            {
                options.Provider = location;
            }

            app.UseJwtBearerAuthentication(options);

            return(app);
        }
예제 #6
0
        public static void ConfigureHmacBearerTokenAuthentication(this IAppBuilder appBuilder, string[] authenticatedPaths)
        {
            appBuilder.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
            {
                Provider = new OAuthBearerAuthenticationProvider
                {
                    //This is the first callback made when OWIN starts
                    //to process the request, here we need to set the token
                    //to null if we don't want it to be processed - basically
                    //this is where we need to:
                    // * check the current request URL to see if we should auth the request (only deploy end points)
                    OnRequestToken = context =>
                    {
                        var umbPath = GlobalSettings.UmbracoMvcArea;

                        var applicationBasePath = (context.Request.PathBase.HasValue ? context.Request.PathBase.Value : string.Empty).EnsureEndsWith('/');

                        var requestPath = context.Request.Uri.CleanPathAndQuery();

                        //Only authenticated endpoints to be authenticated and these must have the projectid
                        //and memberid headers in the request
                        if (authenticatedPaths.Any(s => requestPath.StartsWith($"{applicationBasePath}{umbPath}/{s}", StringComparison.InvariantCultureIgnoreCase)) &&
                            EnsureHeaderValues(context, ProjectAuthConstants.ProjectIdHeader, ProjectAuthConstants.MemberIdHeader))
                        {
                            return(Task.FromResult(0));
                        }

                        context.Token = null;
                        return(Task.FromResult(0));
                    }
                },
                AccessTokenProvider = new AuthenticationTokenProvider
                {
                    //Callback used to parse the token in the request,
                    //if the token parses correctly then we should assign a ticket
                    //to the request, this is the "User" that will get assigned to
                    //the request with Claims.
                    //If the token is invalid, then don't assign a ticket and OWIN
                    //will take care of the rest (not authenticated)
                    OnReceive = context =>
                    {
                        var requestPath = context.Request.Uri.CleanPathAndQuery();
                        if (!TryGetHeaderValue(context, ProjectAuthConstants.ProjectIdHeader, out var projectId))
                        {
                            throw new InvalidOperationException("No project Id found in request"); // this will never happen
                        }
                        if (!TryGetHeaderValue(context, ProjectAuthConstants.MemberIdHeader, out var memberId))
                        {
                            throw new InvalidOperationException("No member Id found in request"); // this will never happen
                        }
                        var umbracoHelper = new Umbraco.Web.UmbracoHelper(Umbraco.Web.UmbracoContext.Current);
                        var project       = umbracoHelper.TypedContent(projectId);

                        if (project.GetPropertyValue <int>("owner") != memberId)
                        {
                            throw new InvalidOperationException("The user does not have owner permissions of the package"); // we generate the key ourselves, so would only happen if people edited the key themselves
                        }
                        //Get the stored auth key for this project and member
                        var tokenService = new ProjectAuthKeyService(ApplicationContext.Current.DatabaseContext);
                        var authKeys     = tokenService.GetAllAuthKeysForProject(projectId);

                        var timestamp = new DateTime();

                        if (authKeys.Any(authKey =>
                                         HMACAuthentication.ValidateToken(context.Token, requestPath, authKey, out timestamp)))
                        {
                            //If ok, create a ticket here with the Claims we need to check for in AuthZ
                            var ticket = new AuthenticationTicket(
                                new ClaimsIdentity(
                                    new List <Claim>
                            {
                                new Claim(ProjectAuthConstants.BearerTokenClaimType, ProjectAuthConstants.BearerTokenClaimValue),
                                new Claim(ProjectAuthConstants.ProjectIdClaim, projectId.ToInvariantString()),
                                new Claim(ProjectAuthConstants.MemberIdClaim, memberId.ToInvariantString()),
                            },

                                    //The authentication type = this is important, if not set
                                    //then the ticket's IsAuthenticated property will be false
                                    authenticationType: ProjectAuthConstants.BearerTokenAuthenticationType),
                                new AuthenticationProperties
                            {
                                //Expires after 5 minutes in case there are some long running operations
                                ExpiresUtc = timestamp.AddMinutes(5)
                            });

                            context.SetTicket(ticket);
                        }
                        else
                        {
                            throw new InvalidOperationException("Token validation failed");
                        }
                    }
                }
            });