Example #1
0
 public void Receive(AuthenticationTokenReceiveContext context)
 {
     //Nichts machen, da wir es nicht brauchen, aber das Interface zu weit gefasst ist
 }
Example #2
0
 private void ReceiveRefreshToken(AuthenticationTokenReceiveContext context)
 {
     // context.DeserializeTicket(context.Token);
     throw new NotImplementedException();
 }
 public void Receive(AuthenticationTokenReceiveContext context)
 {
     throw new NotImplementedException();
 }
 public void Receive(AuthenticationTokenReceiveContext context)
 {
     ReceiveAsync(context).RunSynchronously();
 }
 public void Receive(AuthenticationTokenReceiveContext context)
 {
     ReceiveAsync(context);
 }
Example #6
0
 private static void RecieveRefreshToken(AuthenticationTokenReceiveContext obj)
 {
     //throw new NotImplementedException();
     obj.DeserializeTicket(obj.Token);
 }
 public override Task ReceiveAsync(AuthenticationTokenReceiveContext context)
 {
     //刷新token时,先从数据库删除
     context.DeserializeTicket(context.Token);
     return(Task.FromResult(0));
 }
Example #8
0
 public override Task ReceiveAsync(AuthenticationTokenReceiveContext context)
 {
     return(base.ReceiveAsync(context));
 }
Example #9
0
 private void ReceiveRefreshToken(AuthenticationTokenReceiveContext context)
 {
 }
Example #10
0
        public override async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
        {
            if (_options.EnableValidationResultCache)
            {
                var cachedClaims = await _options.ValidationResultCache.GetAsync(context.Token)
                                   .ConfigureAwait(false);

                if (cachedClaims != null)
                {
                    SetAuthenticationTicket(context, cachedClaims);
                    return;
                }
            }

            IntrospectionResponse response;

            try
            {
                var request = new TokenIntrospectionRequest
                {
                    Address = this.introspectionEndpoint,
                    Token   = context.Token
                };

                if (!string.IsNullOrEmpty(this._options.ApiName))
                {
                    request.ClientId     = this._options.ApiName;
                    request.ClientSecret = this._options.ApiSecret;
                }

                response = await this.httpClient.IntrospectTokenAsync(request)
                           .ConfigureAwait(false);

                if (response.IsError)
                {
                    _logger.WriteError("Error returned from introspection endpoint: " + response.Error);
                    return;
                }
                if (!response.IsActive)
                {
                    _logger.WriteVerbose("Inactive token: " + context.Token);
                    return;
                }
            }
            catch (Exception ex)
            {
                _logger.WriteError("Exception while contacting introspection endpoint: " + ex.ToString());
                return;
            }

            var claims = new List <Claim>();

            foreach (var claim in response.Claims)
            {
                if (!string.Equals(claim.Type, "active", StringComparison.Ordinal))
                {
                    claims.Add(new Claim(claim.Type, claim.Value));
                }
            }

            if (_options.EnableValidationResultCache)
            {
                await _options.ValidationResultCache.AddAsync(context.Token, claims)
                .ConfigureAwait(false);
            }

            SetAuthenticationTicket(context, claims);
        }
Example #11
0
 public override void Receive(AuthenticationTokenReceiveContext context)
 {
     base.Receive(context);
 }
        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");
                    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");
                    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);
            }
        }
        public void Receive(AuthenticationTokenReceiveContext context)
        {
            var task = ReceiveAsync(context);

            task.Wait();
        }
 public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
 {
     context.DeserializeTicket(context.Token);
 }
Example #15
0
 public Task ReceiveAsync(AuthenticationTokenReceiveContext context)
 {
     Receive(context);
     return(Task.FromResult(0));
 }
Example #16
0
 private void ReceiveAuthenticationCode(AuthenticationTokenReceiveContext context)
 {
 }
 public void Receive(AuthenticationTokenReceiveContext context)
 {
 }
Example #18
0
 /// <summary>Receive</summary>
 /// <param name="context">AuthenticationTokenReceiveContext</param>
 public void Receive(AuthenticationTokenReceiveContext context)
 {
     this.ReceiveAuthenticationCode(context);
 }
Example #19
0
 public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
 {
     Receive(context);
 }
Example #20
0
 /// <summary>ReceiveAsync</summary>
 /// <param name="context">AuthenticationTokenReceiveContext</param>
 /// <returns>Task</returns>
 public Task ReceiveAsync(AuthenticationTokenReceiveContext context)
 {
     return(Task.Factory.StartNew(() => this.ReceiveAuthenticationCode(context)));
 }
 private void ReceiveRefreshToken(AuthenticationTokenReceiveContext context)
 {
     context.DeserializeTicket(context.Token);
 }
Example #22
0
        /// <summary>ReceiveAuthenticationCode</summary>
        /// <param name="context">AuthenticationTokenReceiveContext</param>
        private void ReceiveAuthenticationCode(AuthenticationTokenReceiveContext context)
        {
            IEnumerable <string> values = null;

            switch (ASPNETIdentityConfig.UserStoreType)
            {
            case EnumUserStoreType.Memory:
                string value;
                if (_authenticationCodes.TryRemove(context.Token, out value))
                {
                    context.DeserializeTicket(value);
                }
                break;

            case EnumUserStoreType.SqlServer:
            case EnumUserStoreType.ODPManagedDriver:
            case EnumUserStoreType.PostgreSQL:     // DMBMS

                using (IDbConnection cnn = DataAccess.CreateConnection())
                {
                    cnn.Open();

                    switch (ASPNETIdentityConfig.UserStoreType)
                    {
                    case EnumUserStoreType.SqlServer:

                        values = cnn.Query <string>(
                            "SELECT [Value] FROM [AuthenticationCodeDictionary] WHERE [Key] = @Key", new { Key = context.Token });

                        context.DeserializeTicket(values.AsList()[0]);

                        cnn.Execute(
                            "DELETE FROM [AuthenticationCodeDictionary] WHERE [Key] = @Key", new { Key = context.Token });

                        break;

                    case EnumUserStoreType.ODPManagedDriver:

                        values = cnn.Query <string>(
                            "SELECT \"Value\" FROM \"AuthenticationCodeDictionary\" WHERE \"Key\" = :Key", new { Key = context.Token });

                        context.DeserializeTicket(values.AsList()[0]);

                        cnn.Execute(
                            "DELETE FROM \"AuthenticationCodeDictionary\" WHERE \"Key\" = :Key", new { Key = context.Token });

                        break;

                    case EnumUserStoreType.PostgreSQL:

                        values = cnn.Query <string>(
                            "SELECT \"value\" FROM \"authenticationcodedictionary\" WHERE \"key\" = @Key", new { Key = context.Token });

                        context.DeserializeTicket(values.AsList()[0]);

                        cnn.Execute(
                            "DELETE FROM \"authenticationcodedictionary\" WHERE \"key\" = @Key", new { Key = context.Token });

                        break;
                    }
                }

                break;
            }
        }
 public override void Receive(AuthenticationTokenReceiveContext context)
 {
     context.DeserializeTicket(context.Token);
 }
Example #24
0
        private async Task <AuthenticationTicket> InvokeTokenEndpointAuthorizationCodeGrantAsync(
            OAuthValidateTokenRequestContext validatingContext,
            DateTimeOffset currentUtc)
        {
            TokenEndpointRequest tokenEndpointRequest = validatingContext.TokenRequest;

            var authorizationCodeContext = new AuthenticationTokenReceiveContext(
                Context,
                Options.AuthorizationCodeFormat,
                tokenEndpointRequest.AuthorizationCodeGrant.Code);

            await Options.AuthorizationCodeProvider.ReceiveAsync(authorizationCodeContext);

            AuthenticationTicket ticket = authorizationCodeContext.Ticket;

            if (ticket == null)
            {
                _logger.WriteError("invalid authorization code");
                validatingContext.SetError(Constants.Errors.InvalidGrant);
                return(null);
            }

            if (!ticket.Properties.ExpiresUtc.HasValue ||
                ticket.Properties.ExpiresUtc < currentUtc)
            {
                _logger.WriteError("expired authorization code");
                validatingContext.SetError(Constants.Errors.InvalidGrant);
                return(null);
            }

            string clientId;

            if (!ticket.Properties.Dictionary.TryGetValue(Constants.Extra.ClientId, out clientId) ||
                !String.Equals(clientId, validatingContext.ClientContext.ClientId, StringComparison.Ordinal))
            {
                _logger.WriteError("authorization code does not contain matching client_id");
                validatingContext.SetError(Constants.Errors.InvalidGrant);
                return(null);
            }

            string redirectUri;

            if (ticket.Properties.Dictionary.TryGetValue(Constants.Extra.RedirectUri, out redirectUri))
            {
                ticket.Properties.Dictionary.Remove(Constants.Extra.RedirectUri);
                if (!String.Equals(redirectUri, tokenEndpointRequest.AuthorizationCodeGrant.RedirectUri, StringComparison.Ordinal))
                {
                    _logger.WriteError("authorization code does not contain matching redirect_uri");
                    validatingContext.SetError(Constants.Errors.InvalidGrant);
                    return(null);
                }
            }

            await Options.Provider.ValidateTokenRequest(validatingContext);

            var grantContext = new OAuthGrantAuthorizationCodeContext(
                Context, Options, ticket);

            if (validatingContext.IsValidated)
            {
                await Options.Provider.GrantAuthorizationCode(grantContext);
            }

            return(ReturnOutcome(
                       validatingContext,
                       grantContext,
                       grantContext.Ticket,
                       Constants.Errors.InvalidGrant));
        }
Example #25
0
 public Task ReceiveAsync(AuthenticationTokenReceiveContext context) =>
 Task.Run(() => Receive(context));
Example #26
0
 private void ReceiveRefreshToken(AuthenticationTokenReceiveContext context)
 {
     // このおまじないをするとCreateRefreshToken()イベントが発生してアクセストークンとリフレッシュトークンが再生成される
     context.DeserializeTicket(context.Token);
 }
 public Task ReceiveAsync(AuthenticationTokenReceiveContext context)
 {
     throw new NotImplementedException();
 }
        public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
        {
            context.DeserializeTicket(context.Token);

            if (context.Ticket == null)
            {
                context.Response.StatusCode   = 400;
                context.Response.ContentType  = "application/json";
                context.Response.ReasonPhrase = "invalid token";
                return;
            }

            if (context.Ticket.Properties.ExpiresUtc <= DateTime.UtcNow)
            {
                context.Response.StatusCode   = 401;
                context.Response.ContentType  = "application/json";
                context.Response.ReasonPhrase = "unauthorized";
                return;
            }

            var data = await context.Request.ReadFormAsync();

            var selectedClient = data.Where(x => x.Key == "selectedClient").Select(x => x.Value).LastOrDefault().LastOrDefault();

            var userManager  = HttpContext.Current.GetOwinContext().GetUserManager <ApplicationUserManager>();
            var rhnetcontext = HttpContext.Current.GetOwinContext().GetUserManager <RhNetContext>();

            Client client = await(from x in rhnetcontext.Clients where x.Cnpj == selectedClient select x).FirstOrDefaultAsync();


            if (client == null)
            {
                context.Response.StatusCode  = 400;
                context.Response.ContentType = "application/json";

                context.Response.ReasonPhrase = "Cliente não associado a um cliente ou cliente selecionado incorreto";
                return;
            }

            if (client.Situation == Enums.ClientSituation.Bloqueado && context.Ticket.Identity.Name != "master")
            {
                context.Response.StatusCode   = 400;
                context.Response.ContentType  = "application/json";
                context.Response.ReasonPhrase = "Cliente bloqueado. Entre em contato com um administrador do sistema";
                return;
            }

            if (client.Situation == Enums.ClientSituation.Inativo && context.Ticket.Identity.Name != "master")
            {
                context.Response.StatusCode   = 400;
                context.Response.ContentType  = "application/json";
                context.Response.ReasonPhrase = "Cliente inativo. Entre em contato com um administrador do sistema";
                return;
            }



            var roles = (await userManager.GetRoleByClientAsync(context.Ticket.Identity.Name, selectedClient)).Select(e => new { name = e.Name, description = e.Description });

            var claims = await userManager.GetClaimsAsync(context.Ticket.Identity.Name, selectedClient);

            if (roles.Count() == 0)
            {
                context.Response.StatusCode   = 400;
                context.Response.ContentType  = "application/json";
                context.Response.ReasonPhrase = "Cliente não associado a um perfil neste cliente. Entre em contato com um administrador do sistema";
                return;
            }

            context.Ticket.Properties.Dictionary.Remove("currentClient");

            context.Ticket.Properties.Dictionary.Add("currentClient", Newtonsoft.Json.JsonConvert.SerializeObject(new
            {
                id          = client.Id,
                cnpj        = client.Cnpj,
                description = client.Description,
                situation   = client.Situation
            }));

            foreach (Claim claim in context.Ticket.Identity.Claims)
            {
                if (claim.Type == ClaimTypes.Role)
                {
                    if (roles.Where(e => e.name == claim.Value).Count() == 0)
                    {
                        context.Ticket.Identity.RemoveClaim(claim);
                    }
                }

                if (claim.Type == "permission")
                {
                    if (claims.Where(e => e.Value == claim.Value).Count() == 0)
                    {
                        context.Ticket.Identity.RemoveClaim(claim);
                    }
                }
            }



            context.Ticket.Properties.Dictionary.Remove("profiles");
            context.Ticket.Properties.Dictionary.Add("profiles", Newtonsoft.Json.JsonConvert.SerializeObject(roles));

            for (var i = 0; i < roles.Count(); i++)
            {
                if (context.Ticket.Identity.Claims.Where(e => e.Type == ClaimTypes.Role && e.Value == roles.ElementAt(i).name).Count() == 0)
                {
                    context.Ticket.Identity.AddClaim(new Claim(ClaimTypes.Role, roles.ElementAt(i).name));
                }
            }

            for (var i = 0; i < claims.Count(); i++)
            {
                if (context.Ticket.Identity.Claims.Where(e => e.Type == claims.ElementAt(i).Type&& e.Value == claims.ElementAt(i).Value).Count() == 0)
                {
                    context.Ticket.Identity.AddClaim(new Claim(claims[i].Type, claims[i].Value));
                }
            }

            Receive(context);
        }
Example #29
0
        public override async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
        {
            string tokenHash = null;

            if (_options.EnableValidationResultCache)
            {
                tokenHash = context.Token.ToSha256();

                var cachedClaims = await _options.ValidationResultCache.GetAsync(tokenHash);

                if (cachedClaims != null)
                {
                    SetAuthenticationTicket(context, cachedClaims);
                    return;
                }
            }

            var form = new Dictionary <string, string>
            {
                { "token", context.Token }
            };

            HttpResponseMessage response = null;

            try
            {
                response = await _client.PostAsync(_tokenValidationEndpoint, new FormUrlEncodedContent(form));

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    _logger.WriteInformation("Error returned from token validation endpoint: " + response.ReasonPhrase);
                    return;
                }
            }
            catch (Exception ex)
            {
                _logger.WriteError("Exception while contacting token validation endpoint: " + ex.ToString());
                return;
            }

            var jsonString = await response.Content.ReadAsStringAsync();

            var dictionary = JsonConvert.DeserializeObject <Dictionary <string, object> >(jsonString);

            var claims = new List <Claim>();

            foreach (var item in dictionary)
            {
                var values = item.Value as IEnumerable <object>;

                if (values == null)
                {
                    claims.Add(new Claim(item.Key, item.Value.ToString()));
                }
                else
                {
                    foreach (var value in values)
                    {
                        claims.Add(new Claim(item.Key, value.ToString()));
                    }
                }
            }

            if (_options.EnableValidationResultCache)
            {
                await _options.ValidationResultCache.AddAsync(tokenHash, claims);
            }

            SetAuthenticationTicket(context, claims);
        }
Example #30
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="context"></param>
 public void Receive(AuthenticationTokenReceiveContext context)
 {
     logger.Debug("Receive");
 }