Пример #1
0
        public override Task ValidateIdentity(OAuthValidateIdentityContext context)
        {
            bool validated = false;

            base.ValidateIdentity(context);
            ApplicationDbContext   dbContext   = context.OwinContext.Get <ApplicationDbContext>();
            ApplicationUserManager userManager = context.OwinContext.GetUserManager <ApplicationUserManager>();

            if (context.Ticket != null && context.Ticket.Identity != null)
            {
                if (context.Ticket.Identity.Claims.SingleOrDefault(c => c.Type == OAuthClientCredentialsGrantKey) != null)
                {
                    Guid clientId = new Guid(context.Ticket.Identity.Name);
                    if (dbContext.OAuthClients.SingleOrDefault(oac => oac.ClientId == clientId && oac.Enabled == true) != null)
                    {
                        validated = true;
                        context.Validated();
                    }
                }
                else
                {
                    Claim oauthSessionId = context.Ticket.Identity.Claims.SingleOrDefault(c => c.Type == OAuthSessionClaimKey);
                    if (oauthSessionId != null)
                    {
                        OAuthSession oauthSession = dbContext.OAuthSessions.SingleOrDefault(oas => oas.Id.ToString() == oauthSessionId.Value);
                        if (oauthSession != null)
                        {
                            validated = true;
                            context.Validated();
                        }
                    }
                }
            }
            if (!validated)
            {
                context.SetError("Invalid Token", "The Access Token is invalid.");
                context.Rejected();
            }
            return(Task.FromResult <object>(null));
        }
Пример #2
0
        /// <summary>
        /// Handles validating the identity produced from an OAuth bearer token.
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public virtual Task ValidateIdentity(OAuthValidateIdentityContext context)
        {
            try
            {
                if (!context.Request.Headers.ContainsKey("Authorization"))
                {
                    return(Task.FromResult <object>(null));
                }

                // Retrieve the JWT token in Authorization Header
                var jwt = context.Request.Headers["Authorization"].Replace("Bearer ", string.Empty);

                var handler = new JwtSecurityTokenHandler();

                var token = new JwtSecurityToken(jwt);

                var claimIdentity = new ClaimsIdentity(token.Claims, DefaultAuthenticationTypes.ExternalBearer);

                var param = new TokenValidationParameters
                {
                    ValidateAudience = true,                               // Make this false if token was generated without clientId
                    ValidAudience    = "8ebd73587a354f948ec-93260410010c", //Replace with Client Id Registered on CRM. Token should have been fetched with the same clientId.
                    ValidateIssuer   = true,
                    IssuerSigningKey = _signingKey,
                    IssuerValidator  = (issuer, securityToken, parameters) =>
                    {
                        var allowed = GetAllowedPortal().Trim().ToLowerInvariant();

                        if (issuer.ToLowerInvariant().Equals(allowed))
                        {
                            return(issuer);
                        }

                        throw new Exception("Token Issuer is not a known Portal");
                    }
                };

                SecurityToken validatedToken = null;

                handler.ValidateToken(token.RawData, param, out validatedToken);

                var claimPrincipal = new ClaimsPrincipal(claimIdentity);
                context.Response.Context.Authentication.User = claimPrincipal;
                context.Validated(claimIdentity);
            }
            catch (Exception exception)
            {
                System.Diagnostics.Debug.WriteLine(exception);
                return(null);
            }
            return(Task.FromResult <object>(null));
        }
        public override Task ValidateIdentity(OAuthValidateIdentityContext context)
        {
            var wispContext = context.GetWispContext();

            wispContext.SetIdentity(context);
            if (wispContext.CurrentUser == null || !wispContext.CurrentUser.Active)
            {
                throw new WispHttpException(System.Net.HttpStatusCode.Unauthorized);
            }

            context.Validated();
            return(Task.FromResult(0));
        }
        public async Task ValidateIdentity(OAuthValidateIdentityContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (context.Ticket.Identity.Claims.Count() == 0)
            {
                context.Rejected();
            }
            else if (context.Ticket.Identity.Claims.All(c => c.Issuer == ClaimsIdentity.DefaultIssuer))
            {
                context.Rejected();
            }
            else
            {
                var accessToken = context.Ticket.Identity.FindFirst(Security.ClaimTypes.AccessToken);
                if (accessToken != null && !string.IsNullOrEmpty(accessToken.Value))
                {
                    try
                    {
                        var response = await "https://www.googleapis.com/oauth2/v3/tokeninfo"
                                       .SetQueryParam("access_token", accessToken.Value)
                                       .GetAsync();

                        if (!response.IsSuccessStatusCode)
                        {
                            context.Rejected();
                        }
                        else
                        {
                            context.Validated();
                        }
                    }
                    catch (FlurlHttpException ex)
                    {
                        context.Rejected();
                    }
                }
                else
                {
                    context.Rejected();
                }
            }
        }
        public Task ValidateIdentity(OAuthValidateIdentityContext context)
        {
            if (!string.IsNullOrEmpty(token))
            {
                var tokenHandler         = new JwtSecurityTokenHandler();
                var validationParameters = new TokenValidationParameters()
                {
                    ValidAudience      = "all",
                    IssuerSigningToken = new BinarySecretSecurityToken(Convert.FromBase64String("KJiuweUH2234KJBJbkjk234234fgdfc56566")),
                    ValidIssuer        = "http://vcdbpoc-staging.azurewebsites.net"
                };
                try
                {
                    SecurityToken securityToken;
                    var           claimsPrinciple = tokenHandler.ValidateToken(token, validationParameters, out securityToken);

                    context.Validated(new ClaimsIdentity(claimsPrinciple.Claims, OAuthDefaults.AuthenticationType));
                    return(Task.FromResult(0));
                }
                catch (Exception ex)
                {
                    context.Rejected();
                    return(Task.FromResult(0));
                }

                //var notPadded = token.Split('.')[1];
                //var padded = notPadded.PadRight(notPadded.Length + (4 - notPadded.Length % 4) % 4, '=');
                //var urlUnescaped = padded.Replace('-', '+').Replace('_', '/');
                //var claimsPart = Convert.FromBase64String(urlUnescaped);

                //var obj = JObject.Parse(Encoding.UTF8.GetString(claimsPart, 0, claimsPart.Length));

                //// simple, not handling specific types, arrays, etc.
                //foreach (var prop in obj.Properties().AsJEnumerable())
                //{
                //    if (!context.Ticket.Identity.HasClaim(prop.Name, prop.Value.Value<string>()))
                //    {
                //        context.Ticket.Identity.AddClaim(new Claim(prop.Name, prop.Value.Value<string>()));
                //    }
                //}
            }

            context.Rejected();
            return(Task.FromResult(0));
        }
        public Task ValidateIdentity(OAuthValidateIdentityContext context)
        {
            context.Rejected();

            Guid userSessionToken;

            if (JwtHelper.TryGetUserSessionToken(context.Ticket.Identity, out userSessionToken))
            {
                using (var container = UnityConfig.GetContainer().CreateChildContainer())
                {
                    var userSessionBusinessLogic = (IUserSessionBusinessLogic)container.Resolve(typeof(IUserSessionBusinessLogic));

                    var isValid = userSessionBusinessLogic.GetIsUserSessionValid(userSessionToken);
                    if (isValid)
                    {
                        context.Validated();
                    }
                }
            }

            return(Task.CompletedTask);
        }
        public override Task ValidateIdentity(OAuthValidateIdentityContext context)
        {
            if (context.Ticket.Properties.ExpiresUtc < DateTime.UtcNow)
            {
                context.SetError("invalid_grant", "Access Token has expired.");
                context.Rejected();
                return(ThreadingExtensions.NoResult);
            }

            var userId     = context.Ticket.Identity.GetUserGuid();
            var issuedGuid = context.Ticket.Properties
                             .GetIssuedGuid();

            if (!_authKeyRepository.ValidateAuthKey(userId, issuedGuid))
            {
                context.SetError("invalid_token", "Access Token has not been properly set or has been invalidated.");
                context.Rejected();
                return(ThreadingExtensions.NoResult);
            }

            context.Validated();
            return(ThreadingExtensions.NoResult);
        }
        public override async Task ValidateIdentity(OAuthValidateIdentityContext context)
        {
            var owinContext = context.OwinContext;

            var ticket   = context.Ticket;
            var identity = ticket?.Identity;

            if (identity == null || owinContext == null)
            {
                context.Rejected();

                return;
            }

            var claimClientId = identity.FindFirst(IntersectClaimTypes.ClientId);

            if (!Guid.TryParse(claimClientId?.Value, out var clientId))
            {
                context.SetError("invalid_token_client");

                return;
            }

            var claimUserId = identity.FindFirst(IntersectClaimTypes.UserId);

            if (!Guid.TryParse(claimUserId?.Value, out var userId))
            {
                context.SetError("invalid_token_user");

                return;
            }

            var claimTicketId = identity.FindFirst(IntersectClaimTypes.TicketId);

            if (!Guid.TryParse(claimTicketId?.Value, out var ticketId))
            {
                context.SetError("invalid_ticket_id");

                return;
            }

            var refreshToken = RefreshToken.FindForTicket(ticketId);

            if (refreshToken == null)
            {
                context.Rejected();

                return;
            }

            if (ticket.Properties?.ExpiresUtc < DateTime.UtcNow)
            {
                context.SetError("access_token_expired");

                return;
            }

            if (refreshToken.ClientId != clientId || refreshToken.UserId != userId)
            {
                RefreshToken.Remove(refreshToken.Id, true);
                context.Rejected();

                return;
            }

            owinContext.Set("refresh_token", refreshToken);
            context.Validated();
        }
Пример #9
0
            public override Task ValidateIdentity(OAuthValidateIdentityContext context)
            {
                var authorizationBearerToken = context.Request.Headers["Authorization"];

                if (string.IsNullOrWhiteSpace(authorizationBearerToken))
                {
                    context.Rejected();

                    return(Task.FromResult(false));
                }
                else
                {
                    var authorizationBearerTokenParts = authorizationBearerToken
                                                        .Split(' ');

                    var accessToken = authorizationBearerTokenParts
                                      .LastOrDefault();

                    var          claims = new List <Claim>();
                    StuntmanUser user   = null;

                    if (authorizationBearerTokenParts.Count() != 2 ||
                        string.IsNullOrWhiteSpace(accessToken))
                    {
                        context.Response.StatusCode   = 400;
                        context.Response.ReasonPhrase = "Authorization header is not in correct format.";

                        context.Rejected();

                        return(Task.FromResult(false));
                    }
                    else
                    {
                        user = options.Users
                               .Where(x => x.AccessToken == accessToken)
                               .FirstOrDefault();

                        if (user == null)
                        {
                            if (!options.AllowBearerTokenPassthrough)
                            {
                                context.Response.StatusCode   = 403;
                                context.Response.ReasonPhrase =
                                    $"options provided does not include the requested '{accessToken}' user.";

                                context.Rejected();
                            }

                            return(Task.FromResult(false));
                        }
                        else
                        {
                            claims.Add(new Claim("access_token", accessToken));
                        }
                    }

                    claims.Add(new Claim(ClaimTypes.Name, user.Name));
                    claims.AddRange(user.Claims);

                    var identity = new ClaimsIdentity(claims, Constants.StuntmanAuthenticationType, user.NameClaimType, user.RoleClaimType);

                    context.Validated(identity);

                    var authManager = context.OwinContext.Authentication;

                    authManager.SignIn(identity);

                    if (options.AfterBearerValidateIdentity != null)
                    {
                        options.AfterBearerValidateIdentity(context);
                    }

                    return(Task.FromResult(true));
                }
            }
Пример #10
0
    protected override async Task <AuthenticationTicket> AuthenticateCoreAsync()
    {
        try
        {
            // Find token in default location
            string requestToken  = null;
            string authorization = Request.Headers.Get("Authorization");
            if (!string.IsNullOrEmpty(authorization))
            {
                if (authorization.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
                {
                    requestToken = authorization.Substring("Bearer ".Length).Trim();
                }
            }

            // Give application opportunity to find from a different location, adjust, or reject token
            var requestTokenContext = new OAuthRequestTokenContext(Context, requestToken);
            await Options.Provider.RequestToken(requestTokenContext);

            // If no token found, no further work possible
            if (string.IsNullOrEmpty(requestTokenContext.Token))
            {
                return(null);
            }

            // Call provider to process the token into data
            var tokenReceiveContext = new AuthenticationTokenReceiveContext(
                Context,
                Options.AccessTokenFormat,
                requestTokenContext.Token);

            await Options.AccessTokenProvider.ReceiveAsync(tokenReceiveContext);

            if (tokenReceiveContext.Ticket == null)
            {
                tokenReceiveContext.DeserializeTicket(tokenReceiveContext.Token);
            }

            AuthenticationTicket ticket = tokenReceiveContext.Ticket;
            if (ticket == null)
            {
                _logger.WriteWarning("invalid bearer token received");
                Context.Set("oauth.token_invalid", true);
                return(null);
            }

            // Validate expiration time if present
            DateTimeOffset currentUtc = Options.SystemClock.UtcNow;

            if (ticket.Properties.ExpiresUtc.HasValue &&
                ticket.Properties.ExpiresUtc.Value < currentUtc)
            {
                _logger.WriteWarning("expired bearer token received");
                Context.Set("oauth.token_expired", true);
                return(null);
            }

            // Give application final opportunity to override results
            var context = new OAuthValidateIdentityContext(Context, Options, ticket);
            if (ticket != null &&
                ticket.Identity != null &&
                ticket.Identity.IsAuthenticated)
            {
                // bearer token with identity starts validated
                context.Validated();
            }
            if (Options.Provider != null)
            {
                await Options.Provider.ValidateIdentity(context);
            }
            if (!context.IsValidated)
            {
                return(null);
            }

            // resulting identity values go back to caller
            return(context.Ticket);
        }
        catch (Exception ex)
        {
            _logger.WriteError("Authentication failed", ex);
            return(null);
        }
    }
Пример #11
0
 private static Task HandleOnValidateIdentity(OAuthValidateIdentityContext context)
 {
     context.Validated();
     return(Task.CompletedTask);
 }
Пример #12
0
 public Task ValidateIdentity(OAuthValidateIdentityContext context)
 {
     context.Validated();
     return(Task.FromResult(0));
 }