public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            string clientId;
            string clientSecret;

            if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
            {
                context.TryGetFormCredentials(out clientId, out clientSecret);
            }

            if (context.ClientId == null)
            {
                context.SetError("invalid_clientId", "client_Id is not set");
                return Task.FromResult<object>(null);
            }

            var resource = ResourceStore.FindResource(context.ClientId);

            if (resource == null)
            {
                context.SetError("invalid_clientId", string.Format("Invalid client_id '{0}'", context.ClientId));
                return Task.FromResult<object>(null);
            }

            context.Validated();
            return Task.FromResult<object>(null);
        }
        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            string clientId = string.Empty;
            string clientSecret = string.Empty;
            Client client = null;

            if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
            {
                context.TryGetFormCredentials(out clientId, out clientSecret);
            }

            if (context.ClientId == null)
            {
                //Remove the comments from the below line context.SetError, and invalidate context 
                //if you want to force sending clientId/secrects once obtain access tokens. 
                context.Validated();
                //context.SetError("invalid_clientId", "ClientId should be sent.");
                return Task.FromResult<object>(null);
            }

            using (AuthRepository _repo = new AuthRepository())
            {
                client = _repo.FindClient(context.ClientId);
            }

            if (client == null)
            {
                context.SetError("invalid_clientId", string.Format("Client '{0}' is not registered in the system.", context.ClientId));
                return Task.FromResult<object>(null);
            }

            if (client.ApplicationType == ApplicationTypes.NativeConfidential)
            {
                if (string.IsNullOrWhiteSpace(clientSecret))
                {
                    context.SetError("invalid_clientId", "Client secret should be sent.");
                    return Task.FromResult<object>(null);
                }
                else
                {
                    if (client.Secret != HashHelper.GetHash(clientSecret))
                    {
                        context.SetError("invalid_clientId", "Client secret is invalid.");
                        return Task.FromResult<object>(null);
                    }
                }
            }

            if (!client.Active)
            {
                context.SetError("invalid_clientId", "Client is inactive.");
                return Task.FromResult<object>(null);
            }

            context.OwinContext.Set<string>("as:clientAllowedOrigin", client.AllowedOrigin);
            context.OwinContext.Set<string>("as:clientRefreshTokenLifeTime", client.RefreshTokenLifeTime.ToString());

            context.Validated();
            return Task.FromResult<object>(null);
        }
        /// <summary>
        /// Validates the client id
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {

            string clientId;
            string clientSecret;
            // Gets the clientid and client secret from authenticate header
            if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
            {
                // try to get form values
                context.TryGetFormCredentials(out clientId, out clientSecret);

            }

            // Validate clientid and clientsecret. You can omit validating client secret if none is provided in your request (as in sample client request above)
            var validClient = true;//!string.IsNullOrWhiteSpace(clientId);

            if (validClient)
            {
                // Need to make the client_id available for later security checks
                context.OwinContext.Set<string>("as:client_id", clientId);

                context.Validated();
            }
            else
            {
                context.Rejected();
            }

            return Task.FromResult(0);

        }
        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            // validate client credentials
            // should be stored securely (salted, hashed, iterated)
            
            string id, secret;
            if (context.TryGetBasicCredentials(out id, out secret))
            {
                var client = _dbContext
                    .ApiClients
                    .AsEnumerable()
                    .SingleOrDefault(c => c.Id.ToString() == id && c.IsBlacklisted == false);

                if (client != null)
                {
                    // need to make the client_id available for later security checks
                    context.OwinContext.Set("as:client_id", client.Id.ToString());
                    //context.OwinContext.Set("as:client_name", client.Name);
                    context.Validated();
                    return Task.FromResult<object>(null);
                }

            }
            context.Rejected();
            return Task.FromResult<object>(null);
        }
        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            // OAuth2 supports the notion of client authentication
            // this is not used here

            await TaskEx.Run(() => { context.Validated(); });
        }
        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context) {
            var clientId = context.Parameters["client_id"];
            if (!string.IsNullOrWhiteSpace(clientId)) {
                var grantType = context.Parameters["grant_type"];
                var clientSecret = context.Parameters["client_secret"];

                switch (grantType) {
                    case GrantType.Password:
                    case GrantType.ClientCredentials:
                        {
                            /* web application */
                            if (clientSecret == Application.WebApplication.ConsumerSecret) {
                                context.Validated(clientId);
                                return;
                            }

                            /*  mobile application */
                            if (clientSecret == Application.MobileApplication.ConsumerSecret) {
                                context.Validated(clientId);
                                return;
                            }
                        }
                        break;
                    case GrantType.RefreshToken:
                    default:
                        context.Validated(clientId);
                        return;
                }
            }

            context.Rejected();
        }
        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
         

            context.Validated();
            return Task.FromResult<object>(null);
        }
        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            string AuthorizeSecretKey = context.Parameters["authorizeSecretKey"];
            if (AuthorizeSecretKey != AValues.AuthorizeSecretKey)
            {
                context.SetError("invalid_clientId", string.Format("SecretKey '{0}' is not true.", AuthorizeSecretKey));
                return Task.FromResult<object>(null);
            }

            string clientId = string.Empty;
            string clientSecret = string.Empty;

            if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
            {
                context.TryGetFormCredentials(out clientId, out clientSecret);
            }
            if (context.ClientId == null)
            {
                context.Validated();
                return Task.FromResult<object>(null);
            }

            UserViewModel user = RedisHelp.GetLoginUserCache(int.Parse(context.ClientId));
            if (user == null)
            {
                context.SetError("invalid_clientId", string.Format("Client '{0}' is not registered in the system.", context.ClientId));
                return Task.FromResult<object>(null);
            }

            context.Validated();
            return Task.FromResult<object>(null);
        }
 /// <summary>
 /// 验证Client Credentials[client_id与client_secret]
 /// </summary>
 /// <param name="context"></param>
 /// <returns></returns>
 public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
 {
     //http://localhost:48339/token
     //grant_type=client_credentials&client_id=irving&client_secret=123456&scope=user order
     /*
     grant_type     授与方式(固定为 “client_credentials”)
     client_id 	   分配的调用oauth的应用端ID
     client_secret  分配的调用oaut的应用端Secret
     scope 	       授权权限。以空格分隔的权限列表,若不传递此参数,代表请求用户的默认权限
     */
     //validate client credentials should be stored securely (salted, hashed, iterated)
     string clientId;
     string clientSecret;
     //context.TryGetBasicCredentials(out clientId, out clientSecret);
     context.TryGetFormCredentials(out clientId, out clientSecret);
     //验证用户名密码
     var clientValid = await _clientAuthorizationService.ValidateClientAuthorizationSecretAsync(clientId, clientSecret);
     if (!clientValid)
     {
         //Flurl 404 问题
         //context.Response.StatusCode = Convert.ToInt32(HttpStatusCode.OK);
         //context.Rejected();
         context.SetError(AbpConstants.InvalidClient, AbpConstants.InvalidClientErrorDescription);
         return;
     }
     //need to make the client_id available for later security checks
     context.OwinContext.Set<string>("as:client_id", clientId);
     context.Validated(clientId);
 }
        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            try
            {
                var username = context.Parameters["username"];
                var password = context.Parameters["password"];

                if (identityService.AuthenticateUser(username, password))
                {
                    context.OwinContext.Set("securityApi:username", username);
                    context.Validated();
                }
                else
                {
                    context.SetError("Invalid credentials");
                    context.Rejected();
                }
            }
            catch(Exception exception)
            {
                context.SetError(exception.Message);
                context.Rejected();
            }
            return Task.FromResult(0);
        }
        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            string clientId = string.Empty;
            string clientSecret = string.Empty;
            string symmetricKeyAsBase64 = string.Empty;

            if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
            {
                context.TryGetFormCredentials(out clientId, out clientSecret);
            }

            if (context.ClientId == null)
            {
                context.SetError("invalid_clientId", "client_Id is not set");
                return Task.FromResult<object>(null);
            }

            var audience = AudiencesStore.FindAudience(context.ClientId);

            if (audience == null)
            {
                context.SetError("invalid_clientId", string.Format("Invalid client_id '{0}'", context.ClientId));
                return Task.FromResult<object>(null);
            }

            context.Validated();
            return Task.FromResult<object>(null);
        }
        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            // Note: We only support resource owner password grants, in which case there is no client_id involved
            if (context.ClientId == null) context.Validated();

            return Task.FromResult<object>(null);
        }
예제 #13
0
        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            try
            {
                string clientId, clientSecret;
                if (context.TryGetBasicCredentials(out clientId, out clientSecret) || context.TryGetFormCredentials(out clientId, out clientSecret))
                {
                    if (Validator.ValidateClient(clientId, clientSecret))
                    {
                        context.Validated();
                    }
                }
                else
                {
                    context.SetError("Invalid credentials");
                    context.Rejected();
                }
            }
            catch (Exception e)
            {
                context.SetError("Server error");
                context.Rejected();
            }

        }
        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            // Resource owner password credentials does not provide a client ID.
            if (context.ClientId == null) context.Validated();

            return Task.FromResult<object>(null);
        }
예제 #15
0
        /// <summary>
        /// responsible for validating if the Resource server (audience) is already registered in our Authorization server by reading the client_id value from the request
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            string clientId;
            string clientSecret;

            if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
            {
                context.TryGetFormCredentials(out clientId, out clientSecret);
            }

            if (context.ClientId == null && String.IsNullOrWhiteSpace(clientId))
            {
                context.SetError("invalid_clientId", "client_Id is not set");
            }
            else if (!context.HasError)
            {
                var audience = AudiencesStore.Instance.FindAudience(context.ClientId);
                if (audience == null)
                {
                  context.SetError("invalid_clientId", String.Format("Client '{0}' is not registered in the system.", context.ClientId));
                }
                else
                {
                    context.OwinContext.Set("as:clientId", clientId);
                    context.OwinContext.Set("as:clientAllowedOrigin", audience.AllowedOrigin);
                    context.Validated();
                }
            }
            return Task.FromResult<object>(null);
        }
		public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
		{
			context.Validated();

			await Task.FromResult<object>(null);

		}
        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            //TODO Validate null property
            string id, secret;
            context.TryGetFormCredentials(out id, out secret);

            var type = context.Parameters.Get("type");
            switch (type)
            {
                case "admin":
                    if (id == null) id = context.Parameters.Get("Username") + "_SysAdmin";
                    context.Validated();
                    break;
                case "app":
                    if (secret != null) context.Validated();
                    break;
                default:
                    if (id != null) context.Validated();
                    type = string.Empty;
                    break;
            }

            context.OwinContext.Set<string>("as:client_id", id);
            context.OwinContext.Set<string>("as:client_secret", secret);
            context.OwinContext.Set<string>("as:type", type);
        }
        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            string clientId;
            string clientSecret;

            //first try to get the client details from the Authorization Basic header
            if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
            {
                //no details in the Authorization Header so try to find matching post values
                context.TryGetFormCredentials(out clientId, out clientSecret);
            }

            if (string.IsNullOrWhiteSpace(clientId) || string.IsNullOrWhiteSpace(clientSecret))
            {
                context.SetError("client_not_authorized", "invalid client details");
                return Task.FromResult<object>(null);
            }

            var dataLayer = new RepoManager(new DataLayerDapper()).DataLayer;
            var audienceDto = dataLayer.GetAudience(clientId);

            if (audienceDto == null || !clientSecret.Equals(audienceDto.Secret))
            {
                context.SetError("unauthorized_client", "unauthorized client");
                return Task.FromResult<object>(null);
            }

            context.Validated();
            return Task.FromResult<object>(null);
        }
예제 #19
0
        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            try
            {
                var username = context.Parameters["username"];
                var password = context.Parameters["password"];

                if (username == password)
                {
                    context.OwinContext.Set("otf:username", username);
                    context.Validated();
                }
                else
                {
                    context.SetError("Invalid credentials");
                    context.Rejected();
                }
            }
            catch
            {
                context.SetError("Server error");
                context.Rejected();
            }
            return Task.FromResult(0);
        }
 public override async Task ValidateClientAuthentication(
     OAuthValidateClientAuthenticationContext context)
 {
     // This call is required...
     // but we're not using client authentication, so validate and move on...
     await Task.FromResult(context.Validated());
 }
 public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
 {
     await Task.Run(() =>
     {
         context.Validated();
     });
 }
        /// <summary>
        /// 第一步:客户端认证
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            string grant_type = context.Parameters[Constant.GrantTypes.GrantType];

            if (grant_type == Constant.GrantTypes.Password)
            {
                string username = context.Parameters[Constant.GrantTypes.UserName];
                string password = context.Parameters[Constant.GrantTypes.Password];

                //TODO 调用登录逻辑
                bool loginFlag = true;
                if (loginFlag)
                {
                    //把当前用户存入上下文
                    context.OwinContext.Set<string>("loginuser", username);
                    bool flag = context.Validated();
                }
                else
                {
                    context.Rejected();
                    return;
                }
            }
            else if (grant_type == Constant.GrantTypes.RefreshToken)
            {
                bool flag = context.Validated();
            }
            else
            {
                context.Rejected();
                return;
            }
        }
 public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
 {
     await Task.Factory.StartNew(() =>
     {
         context.Validated();
     });
 }
예제 #24
0
        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext ctx)
        {
            string clientId = string.Empty;
            string clientSecret = string.Empty;
            Client client = null;

            if(!ctx.TryGetBasicCredentials(out clientId,out clientSecret))
            {
                ctx.TryGetFormCredentials(out clientId, out clientSecret);
            }

            if(ctx.ClientId == null)
            {
                ctx.SetError("No clientId specified ! ");
                return Task.FromResult<object>(null);
            }

            using(AuthRepository _repo = new AuthRepository())
            {
                client = _repo.FindClient(clientId);
            }

            if(client == null)
            {
                ctx.SetError("clientId not found !");
                return Task.FromResult<object>(null);
            }

            if (client.ApplicationType == ApplicationTypes.Native)
            {
                if (string.IsNullOrWhiteSpace(clientSecret))
                {
                    ctx.SetError("invalid_clientId", "Client secret should be sent.");
                    return Task.FromResult<object>(null);
                }
                else
                {
                    if (client.Secret != GetHash(clientSecret)) 
                    {
                        ctx.SetError("invalid_clientId", "Client secret is invalid.");
                        return Task.FromResult<object>(null);
                    }
                }
            }

            if (!client.Active)
            {
                ctx.SetError("invalid_clientId", "Client is inactive.");
                return Task.FromResult<object>(null);
            }

            ctx.OwinContext.Set<string>("as:clientAllowedOrigin", client.AllowedOrigin);
            ctx.OwinContext.Set<string>("as:clientRefreshTokenLifeTime", client.RefreshTokenLifeTime.ToString());

            ctx.Validated();
            return Task.FromResult<object>(null);


        }
 public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
 {
     string clientId = "jeremy";
     string clientSecret = string.Empty;
     context.TryGetFormCredentials(out clientId, out clientSecret);
     context.OwinContext.Set<string>("as:client_id", clientId);
     context.Validated(clientId);
     return base.ValidateClientAuthentication(context);
 }
        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            string clientId;
            string clientSecret;

            if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
            {
                context.TryGetFormCredentials(out clientId, out clientSecret);
            }

            if (string.IsNullOrWhiteSpace(clientId))
            {
                context.SetError("invalid_clientId", "client_id is not set.");
                await Task.FromResult<object>(null);
                return;
            }
            //TODO: get authClient (application) from db in future
            var authClient = new AuthClientService().Get(clientId);

            // auth client is null
            if (authClient == null)
            {
                context.SetError("invalid_clientId", "client_id is not valid.");
                await Task.FromResult<object>(null);
                return;
            }

            // authclient is enabled
            if (!authClient.Enabled)
            {
                context.SetError("invalid_clientId", "client_id is not valid.");
                await Task.FromResult<object>(null);
                return;
            }

            // make sure secret isn't null or empty
            if (string.IsNullOrWhiteSpace(clientSecret))
            {
                context.SetError("invalid_clientId", "Client secret should be sent.");
                await Task.FromResult<object>(null);
                return;
            }

            // make sure secret matches
            if (clientSecret != authClient.Base64Secret)
            {
                context.SetError("invalid_clientId", "Client secret is invalid.");
                await Task.FromResult<object>(null);
                return;
            }

            context.OwinContext.Set("authClient", authClient);

            context.Validated();

            await Task.FromResult<object>(null);
        }
        /// <summary>
        /// Called to validate that the origin of the request is a registered "client_id", and that the correct credentials for that client are
        ///             present on the request. If the web application accepts Basic authentication credentials, 
        ///             context.TryGetBasicCredentials(out clientId, out clientSecret) may be called to acquire those values if present in the request header. If the web 
        ///             application accepts "client_id" and "client_secret" as form encoded POST parameters, 
        ///             context.TryGetFormCredentials(out clientId, out clientSecret) may be called to acquire those values if present in the request body.
        ///             If context.Validated is not called the request will not proceed further. 
        /// </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 ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {

            string clientId = string.Empty;
            string clientSecret = string.Empty;
            AuthorizedClient authorizedClient = null;

            if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
            {
                context.TryGetFormCredentials(out clientId, out clientSecret);
            }

            if (context.ClientId == null)
            {
                context.SetError("invalid_clientId", "ClientId should be sent.");
                return Task.FromResult<object>(null);
            }

            using (var repo = new AuthRepository())
                authorizedClient = repo.FindAuthorizedClient(context.ClientId);

            if (authorizedClient == null)
            {
                context.SetError("invalid_clientId", string.Format("Client '{0}' is not registered in the system.", context.ClientId));
                return Task.FromResult<object>(null);
            }

            if (authorizedClient.ApplicationType == ApplicationTypes.NativeConfidential)
            {
                if (string.IsNullOrWhiteSpace(clientSecret))
                {
                    context.SetError("invalid_clientId", "Client secret should be sent.");
                    return Task.FromResult<object>(null);
                }
                else
                {
                    if (authorizedClient.Secret != HashHelper.GetHash(clientSecret))
                    {
                        context.SetError("invalid_clientId", "Client secret is invalid.");
                        return Task.FromResult<object>(null);
                    }
                }
            }

            if (!authorizedClient.Active)
            {
                context.SetError("invalid_clientId", "Client is inactive.");
                return Task.FromResult<object>(null);
            }

            context.OwinContext.Set<string>("as:clientAllowedOrigin", authorizedClient.AllowedOrigin);
            context.OwinContext.Set<string>("as:clientRefreshTokenLifeTime", authorizedClient.RefreshTokenLifeTime.ToString());

            context.Validated();
            return Task.FromResult<object>(null);
        }
        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            // Les informations d'identification du mot de passe du propriétaire de la ressource ne fournissent pas un ID client.
            if (context.ClientId == null)
            {
                context.Validated();
            }

            return Task.FromResult<object>(null);
        }
        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            // 資源擁有者密碼認證並未提供用戶端 ID。
            if (context.ClientId == null)
            {
                context.Validated();
            }

            return Task.FromResult<object>(null);
        }
        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            // Die Kennwortanmeldeinformationen des Ressourcenbesitzers stellen keine Client-ID bereit.
            if (context.ClientId == null)
            {
                context.Validated();
            }

            return Task.FromResult<object>(null);
        }
예제 #31
0
        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 tokenEndpointResponseContext = new OAuthTokenEndpointResponseContext(
                Context,
                Options,
                ticket,
                tokenEndpointRequest,
                accessToken,
                tokenEndpointContext.AdditionalResponseParameters);

            await Options.Provider.TokenEndpointResponse(tokenEndpointResponseContext);

            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 tokenEndpointResponseContext.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 = body.Length;
            await Response.WriteAsync(body, Request.CallCancelled);
        }
예제 #32
0
 public override async Task ValidateClientAuthentication(Microsoft.Owin.Security.OAuth.OAuthValidateClientAuthenticationContext context)
 {
     context.Validated();
 }