public override Task TokenEndpoint(OAuthTokenEndpointContext context)
        {
            foreach (var claim in context.Identity.Claims)
            {
                if (claim.Type == ClaimTypes.Email)
                {
                    context.AdditionalResponseParameters.Add("email", claim.Value);
                }

                if (claim.Type == ClaimTypes.Role)
                {
                    context.AdditionalResponseParameters.Add("role", claim.Value);
                }

                if (claim.Type == ClaimTypes.MobilePhone)
                {
                    context.AdditionalResponseParameters.Add("mobile_number", claim.Value);
                }

                if (claim.Type == ClaimTypes.Country)
                {
                    context.AdditionalResponseParameters.Add("country", claim.Value);
                }

                if(claim.Type == "MobileNumberConfirmed")
                {
                    context.AdditionalResponseParameters.Add("mobile_number_confirmed", claim.Value);
                }
            }

            return Task.FromResult<object>(null);
        }
 public override async Task TokenEndpoint(OAuthTokenEndpointContext context)
 {
     foreach (KeyValuePair<string, string> property in context.Properties.Dictionary)
     {
         context.AdditionalResponseParameters.Add(property.Key, property.Value);
     }
 }
        public override Task TokenEndpoint(OAuthTokenEndpointContext context) {
            foreach (KeyValuePair<string, string> property in context.Properties.Dictionary) {
                context.AdditionalResponseParameters.Add(property.Key, property.Value);
            }

            return Task.FromResult<object>(null);
        }
 public override Task TokenEndpoint(OAuthTokenEndpointContext context)
 {
     var isFilledClaim = context.Identity.Claims.FirstOrDefault(x => x.Type == "profileFiled");
     if (isFilledClaim != null)
     {
         var isFilled = isFilledClaim.Value;
         context.AdditionalResponseParameters.Add("isFilled",bool.Parse(isFilled));
     }
     return base.TokenEndpoint(context);
 }
 /// <summary>
 /// Is used to add additional return values to the token response message
 /// </summary>
 public override Task TokenEndpoint(OAuthTokenEndpointContext context)
 {
     foreach (var property in context.Properties.Dictionary)
     {
         context.AdditionalResponseParameters.Add(property.Key, property.Value);
     }
     //var userSessionClaim = context.Identity.FindFirst(claim => claim.Type == ApiConstants.Claims.UserSessionID);
     //context.AdditionalResponseParameters.Add(userSessionClaim.Type, userSessionClaim.Value);
     return Task.FromResult<object>(null);
 }
        public override Task TokenEndpoint(OAuthTokenEndpointContext context)
        {

            #region " Getting time to update service country and lease time "
            Int32 UpdateTimeInMinutes = 5;
            if (WebConfigurationManager.AppSettings["UpdateTimeInMinutes"] != null && WebConfigurationManager.AppSettings["UpdateTimeInMinutes"].Trim().Length > 0)
            {
                UpdateTimeInMinutes = Convert.ToInt32(WebConfigurationManager.AppSettings["UpdateTimeInMinutes"].Trim());
            }
            #endregion

            #region " Getting Token Expiry Time from Config file "
            Int32 days = 0;
            if (WebConfigurationManager.AppSettings["ExpiryDateTimeInDays"] != null && WebConfigurationManager.AppSettings["ExpiryDateTimeInDays"].Trim().Length > 0)
            {
                days = Convert.ToInt32(WebConfigurationManager.AppSettings["ExpiryDateTimeInDays"].Trim());
            } 
            #endregion

            #region " Assigning Token Expiry Time "
            foreach (KeyValuePair<string, string> property in context.Properties.Dictionary)
            {
                //.expires
                if (property.Key == ".expires")
                {
                    context.AdditionalResponseParameters.Add(property.Key, DateTime.Today.AddDays(days));
                }
                else if (property.Key == "expires_in")
                {
                    int seconds = days * 60 * 60;
                    context.AdditionalResponseParameters.Add(property.Key, seconds);
                }
                else
                {
                    context.AdditionalResponseParameters.Add(property.Key, property.Value);
                }

            } 
            #endregion

            #region " Writting values in Response object "
            context.AdditionalResponseParameters.Add("userName", userADName);
            context.AdditionalResponseParameters.Add("userEmail", userADEmail);
            context.AdditionalResponseParameters.Add("userPhone", userADPhone);
            context.AdditionalResponseParameters.Add("UpdateTimeInMinutes", UpdateTimeInMinutes); 
            #endregion
            return Task.FromResult<object>(null);
        }
        public override Task TokenEndpoint(OAuthTokenEndpointContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            var claims = context.Identity.Claims.ToArray();
            foreach (var claim in claims)
            {
                if (claim.ValueType == "self")
                {
                    context.AdditionalResponseParameters[claim.Type] = claim.Value;
                    context.Identity.RemoveClaim(claim);
                }
            }
            return base.TokenEndpoint(context);
        }
 public override Task TokenEndpoint(OAuthTokenEndpointContext context)
 {
     foreach (KeyValuePair<string, string> property in context.Properties.Dictionary)
     {
         context.AdditionalResponseParameters.Add(property.Key, property.Value);
     }
     # region Response back some additional parameters by using /Token method OR Identity
     if (HttpContext.Current.Request.Browser["IsMobileDevice"] == "true")
     {
         context.AdditionalResponseParameters.Add("AntiForgeryToken", deviceId);
     }
     else 
     {
         context.AdditionalResponseParameters.Add("AntiForgeryToken", ip);
     }
     #endregion
     return Task.FromResult<object>(null);
 }
        public override async Task TokenEndpoint(OAuthTokenEndpointContext context)
        {


           
                context.AdditionalResponseParameters.Add("empresaId", _usuario.EmpresaId);
                context.AdditionalResponseParameters.Add("ImagemUsuario", _usuario.ImagemUsuario);
                context.AdditionalResponseParameters.Add("EmpresaImagem", _usuario.Empresa.EmpresaImagem);
                context.AdditionalResponseParameters.Add("NomeEmpresa", _usuario.Empresa.NomeEmpresa);

            foreach (var role in _roles)
            {
                context.AdditionalResponseParameters.Add("roles", role.Key);
                context.AdditionalResponseParameters.Add("IdRole", role.Value);
            }

            await Task.FromResult(context);

        }
        public override Task TokenEndpoint(OAuthTokenEndpointContext context)
        {
            var issued = context.Properties.Dictionary[".issued"];
            var expires = context.Properties.Dictionary[".expires"];
            var roles = context.Properties.Dictionary["roles"];
            var userId = context.Properties.Dictionary["userId"];
            var userName = context.Properties.Dictionary["userName"];
            var firstName = context.Properties.Dictionary["firstName"];
            var lastName = context.Properties.Dictionary["lastName"];

            context.AdditionalResponseParameters.Add(".issued", issued);
            context.AdditionalResponseParameters.Add(".expires", expires);
            context.AdditionalResponseParameters.Add("roles", roles);
            context.AdditionalResponseParameters.Add("userId", userId);
            context.AdditionalResponseParameters.Add("userName", userName);
            context.AdditionalResponseParameters.Add("firstName", firstName);
            context.AdditionalResponseParameters.Add("lastName", lastName);

            return Task.FromResult<object>(null);
        }
        private async Task InvokeTokenEndpointAsync()
        {
            DateTimeOffset currentUtc = Options.SystemClock.UtcNow;

            // remove milliseconds in case they don't round-trip
            currentUtc = currentUtc.Subtract(TimeSpan.FromMilliseconds(currentUtc.Millisecond));

            IFormCollection form = await Request.ReadFormAsync();

            var clientContext = new OAuthValidateClientAuthenticationContext(
                Context,
                Options,
                form);

            await Options.Provider.ValidateClientAuthentication(clientContext);

            if (!clientContext.IsValidated)
            {
                _logger.WriteError("clientID is not valid.");
                if (!clientContext.HasError)
                {
                    clientContext.SetError(Constants.Errors.InvalidClient);
                }
                await SendErrorAsJsonAsync(clientContext);

                return;
            }

            var tokenEndpointRequest = new TokenEndpointRequest(form);

            var validatingContext = new OAuthValidateTokenRequestContext(Context, Options, tokenEndpointRequest, clientContext);

            AuthenticationTicket ticket = null;

            if (tokenEndpointRequest.IsAuthorizationCodeGrantType)
            {
                // Authorization Code Grant http://tools.ietf.org/html/rfc6749#section-4.1
                // Access Token Request http://tools.ietf.org/html/rfc6749#section-4.1.3
                ticket = await InvokeTokenEndpointAuthorizationCodeGrantAsync(validatingContext, currentUtc);
            }
            else if (tokenEndpointRequest.IsResourceOwnerPasswordCredentialsGrantType)
            {
                // Resource Owner Password Credentials Grant http://tools.ietf.org/html/rfc6749#section-4.3
                // Access Token Request http://tools.ietf.org/html/rfc6749#section-4.3.2
                ticket = await InvokeTokenEndpointResourceOwnerPasswordCredentialsGrantAsync(validatingContext, currentUtc);
            }
            else if (tokenEndpointRequest.IsClientCredentialsGrantType)
            {
                // Client Credentials Grant http://tools.ietf.org/html/rfc6749#section-4.4
                // Access Token Request http://tools.ietf.org/html/rfc6749#section-4.4.2
                ticket = await InvokeTokenEndpointClientCredentialsGrantAsync(validatingContext, currentUtc);
            }
            else if (tokenEndpointRequest.IsRefreshTokenGrantType)
            {
                // Refreshing an Access Token
                // http://tools.ietf.org/html/rfc6749#section-6
                ticket = await InvokeTokenEndpointRefreshTokenGrantAsync(validatingContext, currentUtc);
            }
            else if (tokenEndpointRequest.IsCustomExtensionGrantType)
            {
                // Defining New Authorization Grant Types
                // http://tools.ietf.org/html/rfc6749#section-8.3
                ticket = await InvokeTokenEndpointCustomGrantAsync(validatingContext, currentUtc);
            }
            else
            {
                // Error Response http://tools.ietf.org/html/rfc6749#section-5.2
                // The authorization grant type is not supported by the
                // authorization server.
                _logger.WriteError("grant type is not recognized");
                validatingContext.SetError(Constants.Errors.UnsupportedGrantType);
            }

            if (ticket == null)
            {
                await SendErrorAsJsonAsync(validatingContext);

                return;
            }

            ticket.Properties.IssuedUtc  = currentUtc;
            ticket.Properties.ExpiresUtc = currentUtc.Add(Options.AccessTokenExpireTimeSpan);

            var tokenEndpointContext = new OAuthTokenEndpointContext(
                Context,
                Options,
                ticket,
                tokenEndpointRequest);

            await Options.Provider.TokenEndpoint(tokenEndpointContext);

            if (tokenEndpointContext.TokenIssued)
            {
                ticket = new AuthenticationTicket(
                    tokenEndpointContext.Identity,
                    tokenEndpointContext.Properties);
            }
            else
            {
                _logger.WriteError("Token was not issued to tokenEndpointContext");
                validatingContext.SetError(Constants.Errors.InvalidGrant);
                await SendErrorAsJsonAsync(validatingContext);

                return;
            }

            var accessTokenContext = new AuthenticationTokenCreateContext(
                Context,
                Options.AccessTokenFormat,
                ticket);

            await Options.AccessTokenProvider.CreateAsync(accessTokenContext);

            string accessToken = accessTokenContext.Token;

            if (string.IsNullOrEmpty(accessToken))
            {
                accessToken = accessTokenContext.SerializeTicket();
            }
            DateTimeOffset?accessTokenExpiresUtc = ticket.Properties.ExpiresUtc;

            var refreshTokenCreateContext = new AuthenticationTokenCreateContext(
                Context,
                Options.RefreshTokenFormat,
                accessTokenContext.Ticket);
            await Options.RefreshTokenProvider.CreateAsync(refreshTokenCreateContext);

            string refreshToken = refreshTokenCreateContext.Token;

            var memory = new MemoryStream();

            byte[] body;
            using (var writer = new JsonTextWriter(new StreamWriter(memory)))
            {
                writer.WriteStartObject();
                writer.WritePropertyName(Constants.Parameters.AccessToken);
                writer.WriteValue(accessToken);
                writer.WritePropertyName(Constants.Parameters.TokenType);
                writer.WriteValue(Constants.TokenTypes.Bearer);
                if (accessTokenExpiresUtc.HasValue)
                {
                    TimeSpan?expiresTimeSpan = accessTokenExpiresUtc - currentUtc;
                    var      expiresIn       = (long)expiresTimeSpan.Value.TotalSeconds;
                    if (expiresIn > 0)
                    {
                        writer.WritePropertyName(Constants.Parameters.ExpiresIn);
                        writer.WriteValue(expiresIn);
                    }
                }
                if (!String.IsNullOrEmpty(refreshToken))
                {
                    writer.WritePropertyName(Constants.Parameters.RefreshToken);
                    writer.WriteValue(refreshToken);
                }
                foreach (var additionalResponseParameter in tokenEndpointContext.AdditionalResponseParameters)
                {
                    writer.WritePropertyName(additionalResponseParameter.Key);
                    writer.WriteValue(additionalResponseParameter.Value);
                }
                writer.WriteEndObject();
                writer.Flush();
                body = memory.ToArray();
            }
            Response.ContentType = "application/json;charset=UTF-8";
            Response.Headers.Set("Cache-Control", "no-cache");
            Response.Headers.Set("Pragma", "no-cache");
            Response.Headers.Set("Expires", "-1");
            Response.ContentLength = memory.ToArray().Length;
            await Response.WriteAsync(body, Request.CallCancelled);
        }
        /// <summary>
        /// Called at the final stage of a successful Token endpoint request. An application may implement this call in order to do any final 
        /// modification of the claims being used to issue access or refresh tokens. This call may also be used in order to add additional 
        /// response parameters to the Token endpoint's json response body.
        /// </summary>
        /// <param name="context">The context of the event carries information in and results out.</param>
        /// <returns>Task to enable asynchronous execution</returns>
        public override Task TokenEndpoint(OAuthTokenEndpointContext context)
        {
            // Add all entries that we've added to the validated ticket (using the AuthenticationProperties):
            foreach (KeyValuePair<string, string> property in context.Properties.Dictionary)
            {
                context.AdditionalResponseParameters.Add(property.Key, property.Value);
            }

            return Task.FromResult<object>(null);
        }
示例#13
0
 /// <summary>
 /// Called at the final stage of a successful Token endpoint request. An application may implement this call in order to do any final
 /// modification of the claims being used to issue access or refresh tokens. This call may also be used in order to add additional
 /// response parameters to the Token endpoint's json response body.
 /// </summary>
 /// <param name="context">The context of the event carries information in and results out.</param>
 /// <returns>Task to enable asynchronous execution</returns>
 public virtual Task TokenEndpoint(OAuthTokenEndpointContext context)
 {
     return(OnTokenEndpoint.Invoke(context));
 }
 public override Task TokenEndpoint(OAuthTokenEndpointContext context)
 {
     foreach (KeyValuePair<string, string> keyValuePair in (IEnumerable<KeyValuePair<string, string>>)context.Properties.Dictionary)
         context.AdditionalResponseParameters.Add(keyValuePair.Key, (object)keyValuePair.Value);
     return (Task)Task.FromResult<object>((object)null);
 }
 public override Task TokenEndpoint(OAuthTokenEndpointContext context)
 {
     foreach (KeyValuePair<string, string> property in context.Properties.Dictionary)
     {
         context.AdditionalResponseParameters.Add(property.Key, property.Value);
     }
     //to jest tymczasowe rozwiązanie , czyli pewnie juz tak zostanie 
     context.AdditionalResponseParameters.Add("roles",
         context.Identity.Name == "Admin" ? "Admin" : "User");
     return Task.FromResult<object>(null);
 }
 public override Task TokenEndpoint(OAuthTokenEndpointContext context)
 {
     return base.TokenEndpoint(context);
 }
 public override Task TokenEndpoint(OAuthTokenEndpointContext context)
 {
     //Called at the final stage of a successful Token endpoint request. do any final modification of the claims being used to issue access or refresh tokens
     return base.TokenEndpoint(context);
 }
        /// <summary>
        /// Called at the final stage of a successful Token endpoint request. An application may implement this call in order to do any final
        /// modification of the claims being used to issue access or refresh tokens. This call may also be used in order to add additional
        /// response parameters to the Token endpoint's json response body.
        /// </summary>
        /// <param name="context">The context of the event carries information in and results out.</param>
        /// <returns>
        /// Task to enable asynchronous execution
        /// </returns>
        public override Task TokenEndpoint(OAuthTokenEndpointContext context)
        {
         
            var userType = context.OwinContext.Get<string>("user_type");

            context.AdditionalResponseParameters.Add("user_type", userType);


            return Task.FromResult<object>(null);
        }
示例#19
0
        public override Task TokenEndpoint(OAuthTokenEndpointContext context)
        {
            foreach (var property in context.Properties.Dictionary)
            {
                context.AdditionalResponseParameters.Add(property.Key, property.Value);
            }
            if (!context.AdditionalResponseParameters.ContainsKey("UserId"))
            {
                context.AdditionalResponseParameters.Add("UserId", context.Identity.GetUserId());
            }
            else
            {
                context.AdditionalResponseParameters["UserId"] = context.Identity.GetUserId();
            }

            return Task.FromResult<object>(null);
        }
 public override Task TokenEndpoint(OAuthTokenEndpointContext context)
 {
     foreach (KeyValuePair<string, string> keyValuePair in context.Properties.Dictionary)
     {
         if (keyValuePair.Key == "isFirstLogin")
         {
             bool result;
             if (!bool.TryParse(keyValuePair.Value, out result))
                 result = false;
             context.AdditionalResponseParameters.Add(keyValuePair.Key, result ? 1 : 0);
         }
         else
             context.AdditionalResponseParameters.Add(keyValuePair.Key, keyValuePair.Value);
     }
     if (context.Properties.Dictionary["as:client_id"] == "MMuaVe")
     {
         var list = context.OwinContext.Get<IList<Claim>>("data:claims");
         if (list != null)
         {
             foreach (KeyValuePair<string, string> keyValuePair in _mobileProfileClaims)
             {
                 KeyValuePair<string, string> profileClaim = keyValuePair;
                 Claim claim = list.FirstOrDefault(m => m.Type == profileClaim.Key);
                 if (claim != null)
                     context.AdditionalResponseParameters.Add(profileClaim.Value, string.IsNullOrEmpty(claim.Value) ? string.Empty : claim.Value);
                 else
                     context.AdditionalResponseParameters.Add(profileClaim.Value, string.Empty);
             }
         }
     }
     return Task.FromResult<object>(null);
 }
 public override async Task TokenEndpoint(OAuthTokenEndpointContext context)
 {
     using (var repo = new AuthRepository())
     {
         var role = context.Identity.Claims.First(c => c.Type == ClaimTypes.Role).Value;
             
         context.AdditionalResponseParameters.Add("role", role);
     }
 }
 public Task TokenEndpoint(OAuthTokenEndpointContext context)
 {
     throw new NotImplementedException();
 }
        public override Task TokenEndpoint(OAuthTokenEndpointContext context)
        {
            //Serialize useful information to token here
            if (context.Identity != null)
            {
                var roles = context.Identity.FindAll(ClaimTypes.Role)
                   .Select(x => x.Value)
                   .ToArray();
                var userNameClaim = context.Identity.FindFirst(ClaimTypes.Name);
                var userIdClaim = context.Identity.FindFirst(ClaimTypes.Sid);
                if (userNameClaim == null || userIdClaim == null)
                {
                    throw new InvalidOperationException("User id or user name claim is missing from the identity.");
                }
                context.AdditionalResponseParameters.Add("roles", JsonConvert.SerializeObject(roles));
                context.AdditionalResponseParameters.Add("userName", userNameClaim.Value);
                context.AdditionalResponseParameters.Add("userId", userIdClaim.Value);
            }

            return base.TokenEndpoint(context);
        }
示例#24
0
 public override Task TokenEndpoint(OAuthTokenEndpointContext context)
 {
     var id = context.Identity.GetUserId();
     if (id != null)
         context.AdditionalResponseParameters.Add("userID", id);
     return Task.FromResult<object>(null);
 }
 /// <summary>
 /// Called at the final stage of a successful Token endpoint request. An application may implement this call in order to do any final 
 /// modification of the claims being used to issue access or refresh tokens. This call may also be used in order to add additional 
 /// response parameters to the Token endpoint's json response body.
 /// </summary>
 /// <param name="context">The context of the event carries information in and results out.</param>
 /// <returns>Task to enable asynchronous execution</returns>
 public virtual Task TokenEndpoint(OAuthTokenEndpointContext context)
 {
     return OnTokenEndpoint.Invoke(context);
 }
        public override Task TokenEndpoint(OAuthTokenEndpointContext context)
        {
            foreach (var property in context.Properties.Dictionary)
            {
                context.AdditionalResponseParameters.Add(property.Key, property.Value);
            }

            return ThreadingExtensions.NoResult;
        }