Exemple #1
0
        public HttpResponseMessage Token([FromBody] OAuthTokenRequest tokenRequest)
        {
            HttpContext.Response.Headers.Add("Cache-Control", "no-store");
            HttpContext.Response.Headers.Add("Pragma", "no-store");

            // Fetch client and validate
            var client = _oAuthClientService.FindValidClient(
                tokenRequest.ClientId,
                tokenRequest.ClientSecret,
                tokenRequest.GrantType);

            if (client == null)
            {
                return(new HttpResponseMessage(HttpStatusCode.BadRequest)
                {
                    Content = new StringContent(JsonConvert.SerializeObject(new OAuthTokenErrorResponse(OAuthTokenErrors.InvalidClient)))
                });
            }

            switch (tokenRequest.GrantType)
            {
            case OAuthGrantTypes.Password:
                return(ProcessPasswordGrant(client, tokenRequest));

            case OAuthGrantTypes.RefreshToken:
                return(ProcessRefreshTokenGrant(client, tokenRequest));
            }
            var answer = new HttpResponseMessage(HttpStatusCode.BadRequest)
            {
                Content = new StringContent(JsonConvert.SerializeObject(new OAuthTokenErrorResponse(OAuthTokenErrors.InvalidGrant)))
            };

            return(answer);
        }
        public object Token(OAuthTokenRequest request)
        {
            if (!Context.Options.AllowInsecureHttp && Request.RequestUri.Scheme != Uri.UriSchemeHttps)
            {
                throw new OAuthResponseException(HttpStatusCode.UpgradeRequired, new { invalid_scheme = "Requests must be made over HTTPS" });
            }

            if (request == null)
            {
                throw new OAuthResponseException(HttpStatusCode.BadRequest, new { invalid_request = "Invalid request, please make sure to post request data as application/x-www-form-urlencoded" });
            }

            ProcessClient(request);

            SetAllowedOriginHeader();

            switch (request.grant_type)
            {
            case "password":
                return(ProcessPasswordTokenRequest(request));

            case "refresh_token":
                return(ProcessRefreshTokenRequest(request));

            default:
                throw new OAuthResponseException(HttpStatusCode.BadRequest, new { invalid_grant = "Invalid grant_type" });
            }
        }
        protected object ProcessRefreshTokenRequest(OAuthTokenRequest request)
        {
            // Don't do anything if we don't have a token store registered
            if (Context.Services.RefreshTokenStore == null)
            {
                throw new OAuthResponseException(HttpStatusCode.BadRequest, new { invalid_refreshToken = "A refresh token store is not registered in the system" });
            }

            // Lookup the refresh token
            var key   = request.refresh_token.GenerateHash();
            var token = Context.Services.RefreshTokenStore.FindRefreshToken(key);

            if (token != null)
            {
                if (token.ExpiresUtc <= DateTime.UtcNow)
                {
                    throw new OAuthResponseException(HttpStatusCode.Unauthorized, new { invalid_refreshToken = "The refresh token has expired" });
                }

                if (Client != null && token.ClientId != Client.ClientId)
                {
                    throw new OAuthResponseException(HttpStatusCode.Unauthorized, new { invalid_clientId = "Refresh token is issued to a different clientId" });
                }

                if (token.Realm != Context.Realm)
                {
                    throw new OAuthResponseException(HttpStatusCode.Unauthorized, new { invalid_realm = "Refresh token is issued to a different realm" });
                }

                return(ProcessUsernameRequest(token.Subject));
            }

            throw new OAuthResponseException(HttpStatusCode.Unauthorized, new { invalid_refreshToken = $"Refresh token {request.refresh_token} not found" });
        }
Exemple #4
0
        public async Task <bool> ExchangeOAuthCode(string oauthCode)
        {
            var url     = "https://api.trakt.tv/oauth/token";
            var request = new HttpRequestMessage(HttpMethod.Post, url);
            var content = new OAuthTokenRequest
            {
                Code         = oauthCode,
                ClientId     = _configuration.TraktClientId,
                ClientSecret = _configuration.TraktClientSecret,
                RedirectUri  = Constants.RedirectUri,
                GrantType    = "authorization_code"
            };

            request.Content = new StringContent(JsonConvert.SerializeObject(content), Encoding.UTF8, "application/json");
            var response = await _httpClient.SendAsync(request);

            if (response.IsSuccessStatusCode)
            {
                var responseContent = await response.Content.ReadAsStringAsync();

                var accessToken = JsonConvert.DeserializeObject <AccessTokenResponse>(responseContent);
                await _tokenRepository.SaveAccessToken(accessToken);

                return(true);
            }

            return(false);
        }
        public IActionResult FakeToken([FromForm] OAuthTokenRequest request)
        {
            Console.WriteLine("Got Fake token request");
            object resp = null;

            if (request.grant_type == "authorization_code")
            {
                resp = new
                {
                    token_type    = "Bearer",
                    access_token  = Utils.RandomString(10),
                    refresh_token = Utils.RandomString(10),
                    expires_in    = 3600
                };
            }
            else
            {
                resp = new
                {
                    token_type   = "Bearer",
                    access_token = Utils.RandomString(10),
                    expires_in   = 3600
                };
            }

            return(Ok(resp));
        }
Exemple #6
0
        /// <summary>
        /// Verify incoming request for access token
        /// </summary>
        public static bool VerifyOAuthRequestTokenParameters(OAuthTokenRequest tokenRequest)
        {
            if (!string.IsNullOrEmpty(tokenRequest.grant_type) &&
                !tokenRequest.grant_type.Equals(OAuthConstants.ACCESS_TOKEN))
            {
                throw new ApiException(HttpStatusCode.BadRequest, "Missing required parameter:  grant_type");
            }

            if (!string.IsNullOrEmpty(tokenRequest.scope) && !tokenRequest.scope.Equals(DEFAULT_SCOPE))
            {
                throw new ApiException(HttpStatusCode.BadRequest, "The specified scope is invalid");
            }

            if (string.IsNullOrEmpty(tokenRequest.scope))
            {
                tokenRequest.scope = DEFAULT_SCOPE;
            }

            if (string.IsNullOrEmpty(tokenRequest.username))
            {
                throw new ApiException(HttpStatusCode.BadRequest, "Missing required parameter:  username");
            }

            if (string.IsNullOrEmpty(tokenRequest.password))
            {
                throw new ApiException(HttpStatusCode.BadRequest, "Missing required parameter:  password");
            }

            return(true);
        }
        /// <inheritdoc/>
        public OAuthToken GetTokenFromCode(string code, string redirectUri)
        {
            Preconditions.NotEmpty("code", code);
            Preconditions.NotEmpty("redirectUri", redirectUri);

            var request = new HttpRequest();

            request.Method = "POST";
            request.Url    = TokenUrl;

            var requestBody = new OAuthTokenRequest
            {
                ClientId     = this.clientId,
                ClientSecret = this.clientSecret,
                GrantType    = CodeGrantType,
                Code         = code,
                RedirectUri  = redirectUri,
            };

            request.SetJsonBody(requestBody);

            var tokenResponse = this.HttpClient.GetJsonResponse <OAuthTokenResponse>(request);

            return(tokenResponse.ToToken());
        }
Exemple #8
0
        /// <summary>
        /// Authenticates this system against the specified realm
        /// </summary>
        public static IPrincipal Authenticate(String realm, String user, String password)
        {
            var oauthRequest = new OAuthTokenRequest(user, password, "*")
            {
                ClientId     = "fiddler",
                ClientSecret = "fiddler"
            };

            // Client for authentication
            try
            {
                using (var client = CreateClient($"{realm}/auth", false))
                {
                    var response = client.Post <OAuthTokenRequest, OAuthTokenResponse>("oauth2_token", "application/x-www-form-urlencoded", oauthRequest);
                    if (!String.IsNullOrEmpty(response.AccessToken))
                    {
                        AuthenticationContext.EnterContext(new TokenClaimsPrincipal(response.AccessToken, response.IdToken, response.TokenType, response.RefreshToken, null));
                    }
                    else
                    {
                        throw new Exception("Could not retrieve token from server");
                    }
                    return(AuthenticationContext.Current.Principal);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Could not authenticate: {0}", e);
                throw new Exception($"Could not authenticate", e);
            }
        }
Exemple #9
0
 private OAuthTokenRequest CheckForDefault(OAuthTokenRequest request)
 {
     if (request.username == null && request.grant_type == "default_token")
     {
         request.username = "******";
         request.password = "";
     }
     return(request);
 }
        protected object ProcessPasswordTokenRequest(OAuthTokenRequest request)
        {
            // Validate the user
            if (Context.Services.UserService.ValidateUser(request.username, request.password))
            {
                return(ProcessUsernameRequest(request.username));
            }

            throw new OAuthResponseException(HttpStatusCode.Unauthorized, new { invalid_grant = "The username and/or password is incorrect" });
        }
Exemple #11
0
        public AccessToken GetApplicationToken(string applicationId, string applicationSecret, string state = null)
        {
            OAuthTokenRequest request = new OAuthTokenRequest
            {
                grant_type    = OAuthGrantTypes.APPLICATION,
                client_id     = applicationId,
                client_secret = applicationSecret,
                state         = state
            };

            OAuthTokenResponse response = _service.CreateAccessToken(request);

            return(GetResponse(response, AccessTokenType.Application));
        }
Exemple #12
0
        public AccessToken GetAccessToken(string authorizationCode, string applicationId, string applicationSecret, string applicationUri = null)
        {
            OAuthTokenRequest request = new OAuthTokenRequest
            {
                grant_type    = OAuthGrantTypes.USER,
                code          = authorizationCode,
                client_id     = applicationId,
                client_secret = applicationSecret,
                redirect_uri  = applicationUri
            };

            OAuthTokenResponse response = _service.CreateAccessToken(request);

            return(GetResponse(response, AccessTokenType.User));
        }
Exemple #13
0
        public AccessToken RefreshUserToken(string refreshToken, string applicationId, string applicationSecret)
        {
            OAuthTokenRequest request = new OAuthTokenRequest
            {
                grant_type    = OAuthGrantTypes.REFRESH,
                refresh_token = refreshToken,

                client_id     = applicationId,
                client_secret = applicationSecret
            };

            OAuthTokenResponse response = _service.CreateAccessToken(request);

            return(GetResponse(response, AccessTokenType.User));
        }
        protected object ProcessPasswordTokenRequest(OAuthTokenRequest request)
        {
            // Make sure we have a username and password
            if (string.IsNullOrWhiteSpace(request.username) || string.IsNullOrWhiteSpace(request.password))
            {
                throw new OAuthResponseException(HttpStatusCode.BadRequest, new { invalid_grant = "No username and/or password provided" });
            }

            // Validate the user
            if (Context.Services.UserService.ValidateUser(request.username, request.password))
            {
                return(GenerateTokenResponse(request.username, request.device_id));
            }

            throw new OAuthResponseException(HttpStatusCode.Unauthorized, new { invalid_grant = "The username and/or password is incorrect" });
        }
Exemple #15
0
        /// <summary>
        /// Perform an asynchronous OAuth login request with the given credentials
        /// </summary>
        /// <param name="credentials">The credentials to authenticate with</param>
        public async Task Login(OAuthTokenRequest credentials)
        {
            if (String.IsNullOrWhiteSpace(credentials.ClientId) || String.IsNullOrWhiteSpace(credentials.ClientSecret))
            {
                throw new ArgumentException("ClientId and ClientSecret must be populated. Get them at https://q.daskeyboard.com/account");
            }

            var msg = new HttpRequestMessage(HttpMethod.Post, "oauth/1.4/token")
            {
                Content = new StringContent(JsonConvert.SerializeObject(credentials), Encoding.UTF8, "application/json")
            };

            //Set the auth header on our client so future request are authenticated
            var result = await _client.GetResult <OAuthTokenResponse>(msg).ConfigureAwait(false);

            _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
        }
        protected object ProcessRefreshTokenRequest(OAuthTokenRequest request)
        {
            // Make sure we have refresh token
            if (string.IsNullOrWhiteSpace(request.refresh_token))
            {
                throw new OAuthResponseException(HttpStatusCode.BadRequest, new { invalid_refreshToken = "No refresh token provided" });
            }

            // Don't do anything if we don't have a token store registered
            if (Context.Services.RefreshTokenStore == null)
            {
                throw new OAuthResponseException(HttpStatusCode.BadRequest, new { invalid_refreshToken = "A refresh token store is not registered in the system" });
            }

            // Lookup the refresh token
            var key   = request.refresh_token.GenerateHash();
            var token = Context.Services.RefreshTokenStore.FindRefreshToken(key);

            if (token != null)
            {
                if (token.ExpiresUtc <= DateTime.UtcNow)
                {
                    throw new OAuthResponseException(HttpStatusCode.Unauthorized, new { invalid_refreshToken = "The refresh token has expired" });
                }

                if (Client != null && token.ClientId != Client.ClientId)
                {
                    throw new OAuthResponseException(HttpStatusCode.Unauthorized, new { invalid_clientId = "Refresh token is issued to a different clientId" });
                }

                if (token.Realm != Context.Realm)
                {
                    throw new OAuthResponseException(HttpStatusCode.Unauthorized, new { invalid_realm = "Refresh token is issued to a different realm" });
                }

                if (!token.DeviceId.IsNullOrWhiteSpace() && token.DeviceId != request.device_id)
                {
                    throw new OAuthResponseException(HttpStatusCode.Unauthorized, new { invalid_deviceId = "Refresh token is associated with a different device" });
                }

                return(GenerateTokenResponse(token.Subject, token.DeviceId));
            }

            throw new OAuthResponseException(HttpStatusCode.Unauthorized, new { invalid_refreshToken = $"Refresh token {request.refresh_token} not found" });
        }
Exemple #17
0
        private HttpResponseMessage ProcessRefreshTokenGrant(OAuthClient client, OAuthTokenRequest tokenRequest)
        {
            // Validate refresh token
            var refreshToken =
                _oAuthRefreshTokenService.FindValidRefreshToken(tokenRequest.ClientId, tokenRequest.RefreshToken);

            if (refreshToken == null)
            {
                // Refresh token is invalid
                return(new HttpResponseMessage(HttpStatusCode.Forbidden));
            }

            // Get claims
            var claims = _oAuthUserProvider.GetClaimsByUserId(refreshToken.UserId);

            // TODO: Move ClaimsIdentity generation to service?
            var claimsIdentity = new ClaimsIdentity("OAuth");

            claimsIdentity.AddClaims(claims);

            var accessTokenExpiresIn = _oAuthAccessTokenService.GetAccessTokenLifetimeSeconds(client);
            var accessToken          = _oAuthAccessTokenService.GenerateAccessToken(claimsIdentity, client);
            var newRefreshToken      = _oAuthRefreshTokenService.GenerateRefreshToken(Request,
                                                                                      refreshToken.UserId,
                                                                                      client,
                                                                                      tokenRequest.Scopes
                                                                                      ?.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries)
                                                                                      .ToList());

            // Persist refresh new token and delete old
            _oAuthRefreshTokenStorage.Delete(refreshToken.Token);
            _oAuthRefreshTokenStorage.Save(newRefreshToken);
            var answer = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(JsonConvert.SerializeObject(new OAuthTokenResponse
                {
                    TokenType    = OAuthTokenTypes.Bearer,
                    AccessToken  = accessToken,
                    RefreshToken = newRefreshToken.Token,
                    ExpiresIn    = accessTokenExpiresIn,
                }))
            };

            return(answer);
        }
Exemple #18
0
        public async Task <OAuthTokenResponse> GetOAuthTokenAsync(OAuthTokenRequest request)
        {
            var formData = new Dictionary <string, string>
            {
                { "client_id", request.ClientId },
                { "client_secret", request.ClientSecret },
                { "code", request.Code },
                { "redirect_uri", request.RedirectUri.ToString() },
            };

            using (var content = new FormUrlEncodedContent(formData))
                using (var response = await _httpClient.PostAsync("https://slack.com/api/oauth.access", content))
                {
                    var json = await response.Content.ReadAsStringAsync();

                    return(Deserialize <OAuthTokenResponse>(json));
                }
        }
        public OAuthTokenResponse Post(OAuthTokenRequest request)
        {
            var clientId     = FlycowApiClientSettingsProvider.GetClientId();
            var clientSecret = FlycowApiClientSettingsProvider.GetClientSecret();

            if (clientId != request.client_id || clientSecret != request.client_secret)
            {
                throw new InvalidCredentialsException();
            }

            var expiresInSeconds = 3600;

            return(new OAuthTokenResponse()
            {
                access_token = clientId,
                expires_in = expiresInSeconds,
                token_type = "Bearer",
                scope = request.scope
            });
        }
Exemple #20
0
        private HttpResponseMessage ProcessPasswordGrant(OAuthClient client, OAuthTokenRequest tokenRequest)
        {
            var scopes = (tokenRequest.Scopes ?? "")
                         .Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries)
                         .ToList();

            if (!_oAuthUserProvider.ValidateUser(tokenRequest.Username, tokenRequest.Password, scopes))
            {
                // User is invalid
                return(new HttpResponseMessage(HttpStatusCode.Forbidden));
            }

            // Get claims
            var claims = _oAuthUserProvider.GetClaimsByUsername(tokenRequest.Username);
            var userId = _oAuthUserProvider.GetUserId(tokenRequest.Username);

            // TODO: Move ClaimsIdentity generation to service?
            var claimsIdentity = new ClaimsIdentity("OAuth");

            claimsIdentity.AddClaims(claims);

            var accessTokenExpiresIn = _oAuthAccessTokenService.GetAccessTokenLifetimeSeconds(client);
            var accessToken          = _oAuthAccessTokenService.GenerateAccessToken(claimsIdentity, client);
            var refreshToken         = _oAuthRefreshTokenService.GenerateRefreshToken(Request, userId, client, scopes);

            // Persist refresh token
            _oAuthRefreshTokenStorage.Save(refreshToken);
            var answer = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(JsonConvert.SerializeObject(new OAuthTokenResponse
                {
                    TokenType    = OAuthTokenTypes.Bearer,
                    AccessToken  = accessToken,
                    RefreshToken = refreshToken.Token,
                    ExpiresIn    = accessTokenExpiresIn,
                    Scope        = string.Join(" ", scopes),
                }))
            };

            return(answer);
        }
Exemple #21
0
        public OAuthTokenResponse Authenticate(OAuthTokenRequest request)
        {
            var tokenHandler = new JwtSecurityTokenHandler();

            // I use sometimes some sort of default user, if you don't want that, just remove this
            request = CheckForDefault(request);
            User[] users = repository.ReadValue <User[]>("Users");
            if (!users.ToList().Any(s => s.username == request.username))
            {
                return(null);
            }


            // Here you should add some sort of password check



            var key           = Encoding.ASCII.GetBytes(_appSettings.Secret);
            var claimIdentity = new ClaimsIdentity(new Claim[]
            {
                new Claim(ClaimTypes.Name, request.username),
            });
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject            = claimIdentity,
                Expires            = DateTime.UtcNow.AddDays(7),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var token = tokenHandler.CreateToken(tokenDescriptor);

            return(new OAuthTokenResponse()
            {
                access_token = tokenHandler.WriteToken(token),
                token_type = "Jwt Token",
                expires_in = ((DateTimeOffset)tokenDescriptor.Expires.Value).ToUnixTimeSeconds(),
                refresh_token = ""
            });
        }
Exemple #22
0
        /// <summary>
        /// Requests the token.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentNullException">oauth token request</exception>
        /// <exception cref="System.Exception"></exception>
        public OAuthTokenResponse RequestToken(OAuthTokenRequest request)
        {
            try
            {
                #region pre-processing

                if (request == null)
                {
                    throw new ArgumentNullException("oauth token request");
                }

                #endregion pre-processing


                #region processing

                List <KeyValuePair <string, string> > parameters = new List <KeyValuePair <string, string> >();
                parameters.Add(new KeyValuePair <string, string>("grant_type", request.GrantType));
                parameters.Add(new KeyValuePair <string, string>("client_id", request.ClientId));
                parameters.Add(new KeyValuePair <string, string>("client_secret", request.ClientSecret));
                parameters.Add(new KeyValuePair <string, string>("code", request.Code));
                string jsonResult = PostFormUrlEncodedContentRequest(string.Concat(PushbulletConstants.BaseUrlNonVersion, PushbulletConstants.OAuthUrls.OAuthToken), parameters);
                var    result     = jsonResult.JsonToOjbect <OAuthTokenResponse>();
                return(result);

                #endregion processing
            }
            catch (WebException ex)
            {
                var statusCode = ((HttpWebResponse)ex.Response).StatusCode;
                throw new Exception(string.Format(PushbulletConstants.OAuthErrorMessages.WebExceptionFormat, statusCode, ex.Message), ex);
            }
            catch (Exception)
            {
                throw;
            }
        }
Exemple #23
0
        /// <summary>
        /// A method that executes request token flow
        /// </summary>
        public OAuthTokenResponse ExecuteTokenFlow(OAuthTokenRequest tokenRequest)
        {
            VerifyOAuthRequestTokenParameters(tokenRequest);

            long retrievedMemberId = VerifyCredentials(tokenRequest.username, tokenRequest.password);

            Guid accessTokenGuid  = Guid.NewGuid();
            Guid refreshTokenGuid = Guid.NewGuid();

            DateTime validFrom = DateTime.UtcNow;
            DateTime validTo   = validFrom.AddDays(1);

            AddMemberAuthorization(accessTokenGuid, retrievedMemberId, tokenRequest.scope, validFrom, validTo);

            return(new OAuthTokenResponse
            {
                access_token = accessTokenGuid.ToString(),
                expires_in = null,
                refresh_token = refreshTokenGuid.ToString(),
                scope = tokenRequest.scope,
                token_type = TOKEN_TYPE_BEARER,
                MemberID = retrievedMemberId
            });
        }
Exemple #24
0
        /// <summary>
        /// A method that executes refresh token flow
        /// </summary>
        public OAuthRefreshTokenResponse ExecuteRefreshTokenFlow(OAuthTokenRequest tokenRequest)
        {
            if (!string.IsNullOrEmpty(tokenRequest.scope) && !tokenRequest.scope.Equals(DEFAULT_SCOPE))
            {
                throw new ApiException(HttpStatusCode.BadRequest, "The specified scope is invalid");
            }

            if (string.IsNullOrEmpty(tokenRequest.refresh_token))
            {
                throw new ApiException(HttpStatusCode.BadRequest, "Missing required parameter:  refresh_token");
            }

            Guid accessToken        = Guid.NewGuid();
            long memberId           = RefreshMemberAuthorization(tokenRequest.refresh_token, accessToken.ToString());
            var  oAuthTokenResponse = new OAuthRefreshTokenResponse
            {
                MemberID     = memberId,
                access_token = accessToken.ToString(),
                token_type   = TOKEN_TYPE_BEARER,
                scope        = tokenRequest.scope
            };

            return(oAuthTokenResponse);
        }
        protected void ProcessClient(OAuthTokenRequest request)
        {
            if (Context.Services.ClientStore != null)
            {
                if (string.IsNullOrWhiteSpace(request.client_id))
                {
                    throw new OAuthResponseException(HttpStatusCode.Unauthorized, new { invalid_clientId = "A client_id is required" });
                }

                var client = Context.Services.ClientStore.FindClient(request.client_id);
                if (client == null)
                {
                    throw new OAuthResponseException(HttpStatusCode.Unauthorized, new { invalid_clientId = $"Client {request.client_id} is not registered in the system" });
                }

                if (client.SecurityLevel == SecurityLevel.Secure)
                {
                    if (string.IsNullOrWhiteSpace(request.client_secret))
                    {
                        throw new OAuthResponseException(HttpStatusCode.Unauthorized, new { invalid_clientSecret = "A client_secret is required" });
                    }

                    if (client.Secret != request.client_secret.GenerateOAuthHash())
                    {
                        throw new OAuthResponseException(HttpStatusCode.Unauthorized, new { invalid_clientSecret = "Invalid client_secret" });
                    }
                }

                if (!client.Active)
                {
                    throw new OAuthResponseException(HttpStatusCode.Unauthorized, new { invalid_clientId = "Client is inactive" });
                }

                Client = client;
            }
        }
Exemple #26
0
        public IActionResult CreateAccessToken([FromForm] OAuthTokenRequest tokenRequest)
        {
            IActionResult result = null;

            if (string.Compare(tokenRequest.grant_type, "password", true) == 0)
            {
                Model.AccessKey accessKey = BusinessLogicFactory.AccessKeys.GetAccessKey(tokenRequest.username);
                if (accessKey != null)
                {
                    if (string.Compare(tokenRequest.password, accessKey.Secret) == 0)
                    {
                        OAuthToken token = CreateOAuthToken(accessKey.OrganisationID);
                        result = new ObjectResult(token)
                        {
                            StatusCode = (int)HttpStatusCode.Created
                        };
                    }
                    else
                    {
                        _logger.LogDebug($"Incorrect Secret for Organisation {accessKey.OrganisationID} with access key: {accessKey.Name}");
                        result = new UnauthorizedResult();
                    }
                }
                else
                {
                    _logger.LogDebug($"No organisation with key: {tokenRequest.username}");
                    result = new UnauthorizedResult();
                }
            }
            else if (string.Compare(tokenRequest.grant_type, "refresh_token", true) == 0)
            {
                OrganisationSecurityTokenHandler handler = _AuthOptions.SecurityTokenValidators.OfType <OrganisationSecurityTokenHandler>().FirstOrDefault();
                JwtSecurityToken securityToken           = handler.ReadJwtToken(tokenRequest.refresh_token);

                if (securityToken != null)
                {
                    Claim organisationClaim = securityToken.Claims.ToList().Find(c => c.Type.Equals(OrganisationIdentity.OrganisationClaim));
                    Claim refreshTokenClaim = securityToken.Claims.ToList().Find(c => c.Type.Equals(RefreshTokenClaim));

                    if (organisationClaim != null && refreshTokenClaim != null && refreshTokenClaim.Value.Equals(RefreshTokenExists))
                    {
                        int organisationID;
                        if (int.TryParse(organisationClaim.Value, out organisationID) && organisationID > 0)
                        {
                            OAuthToken token = CreateOAuthToken(organisationID);
                            result = new ObjectResult(token)
                            {
                                StatusCode = (int)HttpStatusCode.Created
                            };
                        }
                        else
                        {
                            _logger.LogDebug($"Failed to parse organisationID in refresh token: {tokenRequest.refresh_token}");
                            result = new BadRequestResult();
                        }
                    }
                    else
                    {
                        _logger.LogDebug($"Refresh token does not have expected claims: {tokenRequest.refresh_token}");
                        result = new BadRequestResult();
                    }
                }
                else
                {
                    _logger.LogDebug($"Invalid refresh token: {tokenRequest.refresh_token}");
                    result = new BadRequestResult();
                }
            }
            else
            {
                result = new BadRequestResult();
            }

            return(result);
        }
Exemple #27
0
        public IActionResult Oauthtokenpost(OAuthTokenRequest request)
        {
            OAuthTokenResponse token = service.Authenticate(request);

            return(Ok(token));
        }