コード例 #1
0
ファイル: OAuthService.cs プロジェクト: Dahub/DaOAuthV2
        private TokenInfoDto GenerateTokenForRefreshToken(AskTokenDto tokenInfo, IStringLocalizer errorLocal)
        {
            TokenInfoDto toReturn = null;

            if (String.IsNullOrWhiteSpace(tokenInfo.ClientPublicId))
            {
                throw new DaOAuthTokenException()
                      {
                          Error       = OAuthConvention.ErrorNameRefreshToken,
                          Description = errorLocal["RefreshTokenParameterError"]
                      };
            }

            using (var context = RepositoriesFactory.CreateContext())
            {
                var clientRepo = RepositoriesFactory.GetClientRepository(context);
                var myClient   = clientRepo.GetByPublicId(tokenInfo.ClientPublicId);

                if (!CheckIfClientsCredentialsAreValid(myClient, tokenInfo.AuthorizationHeader))
                {
                    throw new DaOAuthTokenException()
                          {
                              Error       = OAuthConvention.ErrorNameUnauthorizedClient,
                              Description = errorLocal["UnauthorizedClient"]
                          };
                }

                var tokenDetail = JwtService.ExtractToken(new ExtractTokenDto()
                {
                    Token     = tokenInfo.RefreshToken,
                    TokenName = OAuthConvention.RefreshToken
                });

                if (!CheckIfTokenIsValid(tokenDetail, context))
                {
                    throw new DaOAuthTokenException()
                          {
                              Error       = OAuthConvention.ErrorNameInvalidGrant,
                              Description = errorLocal["RefreshTokenInvalid"]
                          };
                }

                if (!CheckIfScopesAreAuthorizedForClient(tokenDetail.ClientId, tokenInfo.Scope))
                {
                    throw new DaOAuthTokenException()
                          {
                              Error       = OAuthConvention.ErrorNameInvalidScope,
                              Description = errorLocal["UnauthorizedScope"]
                          };
                }

                toReturn = GenerateAccessTokenAndUpdateRefreshToken(tokenInfo, context, tokenDetail.UserName);

                context.Commit();
            }

            return(toReturn);
        }
コード例 #2
0
ファイル: OAuthService.cs プロジェクト: Dahub/DaOAuthV2
        private TokenInfoDto GenerateTokenForClientCredentailsGrant(AskTokenDto tokenInfo, IStringLocalizer errorLocal)
        {
            TokenInfoDto toReturn = null;

            using (var context = RepositoriesFactory.CreateContext())
            {
                var clientRepo = RepositoriesFactory.GetClientRepository(context);
                var myClient   = clientRepo.GetByPublicId(tokenInfo.ClientPublicId);

                if (!CheckIfClientsCredentialsAreValid(myClient, tokenInfo.AuthorizationHeader))
                {
                    throw new DaOAuthTokenException()
                          {
                              Error       = OAuthConvention.ErrorNameUnauthorizedClient,
                              Description = errorLocal["UnauthorizedClient"]
                          };
                }

                if (!CheckIfScopesAreAuthorizedForClient(myClient.PublicId, tokenInfo.Scope))
                {
                    throw new DaOAuthTokenException()
                          {
                              Error       = OAuthConvention.ErrorNameInvalidScope,
                              Description = errorLocal["UnauthorizedScope"]
                          };
                }

                var accesToken = JwtService.GenerateToken(new CreateTokenDto()
                {
                    ClientPublicId  = myClient.PublicId,
                    Scope           = tokenInfo.Scope,
                    SecondsLifeTime = Configuration.AccesTokenLifeTimeInSeconds,
                    TokenName       = OAuthConvention.AccessToken,
                    UserName        = String.Empty
                });

                toReturn = new TokenInfoDto()
                {
                    AccessToken = accesToken.Token,
                    ExpireIn    = Configuration.AccesTokenLifeTimeInSeconds,
                    Scope       = tokenInfo.Scope,
                    TokenType   = OAuthConvention.AccessToken
                };
            }

            return(toReturn);
        }
コード例 #3
0
ファイル: OAuthService.cs プロジェクト: Dahub/DaOAuthV2
        private TokenInfoDto GenerateAccessTokenAndUpdateRefreshToken(AskTokenDto tokenInfo, IContext context, string userName)
        {
            TokenInfoDto toReturn;
            var          newRefreshToken = JwtService.GenerateToken(new CreateTokenDto()
            {
                ClientPublicId  = tokenInfo.ClientPublicId,
                Scope           = tokenInfo.Scope,
                SecondsLifeTime = Configuration.RefreshTokenLifeTimeInSeconds,
                TokenName       = OAuthConvention.RefreshToken,
                UserName        = userName
            });

            var accesToken = JwtService.GenerateToken(new CreateTokenDto()
            {
                ClientPublicId  = tokenInfo.ClientPublicId,
                Scope           = tokenInfo.Scope,
                SecondsLifeTime = Configuration.AccesTokenLifeTimeInSeconds,
                TokenName       = OAuthConvention.AccessToken,
                UserName        = userName
            });

            var userClientRepo = RepositoriesFactory.GetUserClientRepository(context);
            var myUc           = userClientRepo.GetUserClientByClientPublicIdAndUserName(tokenInfo.ClientPublicId, userName);

            myUc.RefreshToken = newRefreshToken.Token;
            userClientRepo.Update(myUc);

            toReturn = new TokenInfoDto()
            {
                AccessToken  = accesToken.Token,
                ExpireIn     = Configuration.AccesTokenLifeTimeInSeconds,
                RefreshToken = newRefreshToken.Token,
                Scope        = tokenInfo.Scope,
                TokenType    = OAuthConvention.AccessToken
            };
            return(toReturn);
        }
コード例 #4
0
ファイル: OAuthService.cs プロジェクト: Dahub/DaOAuthV2
        public Uri GenererateUriForAuthorize(AskAuthorizeDto authorizeInfo)
        {
            IList <ValidationResult> ExtendValidation(AskAuthorizeDto toValidate)
            {
                var resource = this.GetErrorStringLocalizer();
                IList <ValidationResult> result = new List <ValidationResult>();

                if (!String.IsNullOrEmpty(toValidate.RedirectUri) && !IsUriCorrect(toValidate.RedirectUri))
                {
                    result.Add(new ValidationResult(resource["AuthorizeAuthorizeRedirectUrlIncorrect"]));
                }

                return(result);
            }

            Uri toReturn = null;

            Logger.LogInformation($"Ask for authorize, client : {authorizeInfo.ClientPublicId} - response_type : {authorizeInfo.ResponseType}");

            var errorLocal = GetErrorStringLocalizer();

            Validate(authorizeInfo, ExtendValidation);

            if (String.IsNullOrEmpty(authorizeInfo.ResponseType))
            {
                throw new DaOAuthRedirectException()
                      {
                          RedirectUri = GenerateRedirectErrorMessage(
                              authorizeInfo.RedirectUri,
                              OAuthConvention.ErrorNameInvalidRequest,
                              errorLocal["AuthorizeResponseTypeParameterMandatory"],
                              authorizeInfo.State)
                      };
            }

            if (!authorizeInfo.ResponseType.Equals(OAuthConvention.ResponseTypeCode, StringComparison.Ordinal) &&
                !authorizeInfo.ResponseType.Equals(OAuthConvention.ResponseTypeToken, StringComparison.Ordinal))
            {
                throw new DaOAuthRedirectException()
                      {
                          RedirectUri = GenerateRedirectErrorMessage(
                              authorizeInfo.RedirectUri,
                              OAuthConvention.ErrorNameUnsupportedResponseType,
                              errorLocal["AuthorizeUnsupportedResponseType"],
                              authorizeInfo.State)
                      };
            }

            if (String.IsNullOrEmpty(authorizeInfo.ClientPublicId))
            {
                throw new DaOAuthRedirectException()
                      {
                          RedirectUri = GenerateRedirectErrorMessage(
                              authorizeInfo.RedirectUri,
                              OAuthConvention.ErrorNameInvalidRequest,
                              errorLocal["AuthorizeClientIdParameterMandatory"],
                              authorizeInfo.State)
                      };
            }

            if (!CheckIfClientIsValid(authorizeInfo.ClientPublicId, new Uri(authorizeInfo.RedirectUri),
                                      authorizeInfo.ResponseType.Equals(OAuthConvention.ResponseTypeCode, StringComparison.Ordinal) ? EClientType.CONFIDENTIAL : EClientType.PUBLIC))
            {
                throw new DaOAuthRedirectException()
                      {
                          RedirectUri = GenerateRedirectErrorMessage(
                              authorizeInfo.RedirectUri,
                              OAuthConvention.ErrorNameUnauthorizedClient,
                              errorLocal["UnauthorizedClient"],
                              authorizeInfo.State)
                      };
            }

            if (!CheckIfScopesAreAuthorizedForClient(authorizeInfo.ClientPublicId, authorizeInfo.Scope))
            {
                throw new DaOAuthRedirectException()
                      {
                          RedirectUri = GenerateRedirectErrorMessage(
                              authorizeInfo.RedirectUri,
                              OAuthConvention.ErrorNameInvalidScope,
                              errorLocal["UnauthorizedScope"],
                              authorizeInfo.State)
                      };
            }

            if (!CheckIfUserHasAuthorizeOrDeniedClientAccess(authorizeInfo.ClientPublicId, authorizeInfo.UserName))
            {
                throw new DaOAuthRedirectException()
                      {
                          RedirectUri = new Uri($"{Configuration.AuthorizeClientPageUrl}?" +
                                                $"response_type={authorizeInfo.ResponseType}&" +
                                                $"client_id={authorizeInfo.ClientPublicId}&" +
                                                $"state={authorizeInfo.State}&" +
                                                $"redirect_uri={authorizeInfo.RedirectUri}&" +
                                                $"scope={authorizeInfo.Scope}")
                      };
            }

            if (!CheckIfUserHasAuthorizeClient(authorizeInfo.ClientPublicId, authorizeInfo.UserName))
            {
                throw new DaOAuthRedirectException()
                      {
                          RedirectUri = GenerateRedirectErrorMessage(
                              authorizeInfo.RedirectUri,
                              OAuthConvention.ErrorNameAccessDenied,
                              errorLocal["AccessDenied"],
                              authorizeInfo.State)
                      };
            }

            switch (authorizeInfo.ResponseType)
            {
            case OAuthConvention.ResponseTypeCode:
                var myCode       = GenerateAndSaveCode(authorizeInfo.ClientPublicId, authorizeInfo.UserName, authorizeInfo.Scope);
                var codeLocation = String.Concat(authorizeInfo.RedirectUri, "?code=", myCode);
                if (!String.IsNullOrEmpty(authorizeInfo.State))
                {
                    codeLocation = String.Concat(codeLocation, "&state=", authorizeInfo.State);
                }

                toReturn = new Uri(codeLocation);
                break;

            default:     // response_type token
                var myToken = JwtService.GenerateToken(new CreateTokenDto()
                {
                    SecondsLifeTime = Configuration.AccesTokenLifeTimeInSeconds,
                    ClientPublicId  = authorizeInfo.ClientPublicId,
                    Scope           = authorizeInfo.Scope,
                    TokenName       = OAuthConvention.AccessToken,
                    UserName        = authorizeInfo.UserName
                });
                var tokenLocation = String.Concat(authorizeInfo.RedirectUri, "?token=", myToken.Token, "&token_type=bearer&expires_in=", Configuration.AccesTokenLifeTimeInSeconds);
                if (!String.IsNullOrEmpty(authorizeInfo.State))
                {
                    tokenLocation = String.Concat(tokenLocation, "&state=", authorizeInfo.State);
                }

                toReturn = new Uri(tokenLocation);
                break;
            }

            return(toReturn);
        }
コード例 #5
0
ファイル: OAuthService.cs プロジェクト: Dahub/DaOAuthV2
        public IntrospectInfoDto Introspect(AskIntrospectDto introspectInfo)
        {
            Validate(introspectInfo);

            Logger.LogInformation($"Introspect token {introspectInfo.Token}");

            var toReturn = new IntrospectInfoDto()
            {
                IsValid = false
            };

            var authsInfos = introspectInfo.AuthorizationHeader.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

            if (authsInfos.Length != 2)
            {
                return(toReturn);
            }

            if (!authsInfos[0].Equals("Basic", StringComparison.OrdinalIgnoreCase))
            {
                return(toReturn);
            }

            var credentials    = Encoding.UTF8.GetString(Convert.FromBase64String(authsInfos[1]));
            var separatorIndex = credentials.IndexOf(':');

            if (separatorIndex == -1)
            {
                return(toReturn);
            }

            var             rsLogin = credentials.Substring(0, separatorIndex);
            RessourceServer rs      = null;

            using (var context = RepositoriesFactory.CreateContext())
            {
                var rsRepo = RepositoriesFactory.GetRessourceServerRepository(context);
                rs = rsRepo.GetByLogin(rsLogin);

                if (rs == null)
                {
                    return(toReturn);
                }

                var rsSecret = credentials.Substring(separatorIndex + 1);
                if (!EncryptonService.AreEqualsSha256(String.Concat(Configuration.PasswordSalt, rsSecret), rs.ServerSecret))
                {
                    return(toReturn);
                }

                if (!rs.IsValid)
                {
                    return(toReturn);
                }

                var tokenInfo = JwtService.ExtractToken(new ExtractTokenDto()
                {
                    TokenName = OAuthConvention.AccessToken,
                    Token     = introspectInfo.Token
                });

                if (!tokenInfo.IsValid)
                {
                    return(toReturn);
                }

                toReturn.ClientPublicId = tokenInfo.ClientId;
                toReturn.Expire         = tokenInfo.Expire;
                toReturn.IsValid        = true;
                toReturn.Scope          = tokenInfo.Scope;
                toReturn.UserName       = tokenInfo.UserName;
                toReturn.Audiences      = rsRepo.GetAll().Where(r => r.IsValid.Equals(true)).Select(r => r.Name).ToArray();
            }

            return(toReturn);
        }