Beispiel #1
0
        public async Task <IActionResult> RequestToken([FromForm] RequestTokenModel model)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    var resultProvider = Service <IValidationResultProvider>();

                    var firstResult = resultProvider.Results
                                      .Where(o => !o.IsValid).SelectMany(o => o.Errors).FirstOrDefault();

                    var oauthException = firstResult.CustomState as OAuthException;

                    throw oauthException;
                }

                var tokenResp = await _identityService.ProvideTokenAsync(model);

                return(Ok(tokenResp));
            }
            catch (OAuthException ex)
            {
                return(BadRequest(ex.ErrorResponse));
            }
        }
        public void UploadFile(RequestTokenModel model, string path)
        {
            var fileContent = @"C:\Test\testDoc.txt";

            var id  = GetUploadLink(model, path);
            var res = _service.UploadFile(model.Token, id, fileContent);
        }
Beispiel #3
0
        public ActionResult OAuthCallback(string oauth_token, string oauth_verifier)
        {
            RequestTokenModel model = new RequestTokenModel();

            string requestTokenString = Request[Parameters.OAuth_Token];
            string verifier           = Request[Parameters.OAuth_Verifier];

            RequestTokenModel storedRequestTokenModel = (RequestTokenModel)Session[requestTokenString];

            OAuthKeyConfiguration oauthConfiguration = OAuthKeyConfiguration.GetInstance();

            AlwaysMoveForward.OAuth.Client.RestSharp.OAuthClient oauthClient = new AlwaysMoveForward.OAuth.Client.RestSharp.OAuthClient("", storedRequestTokenModel.ConsumerKey, storedRequestTokenModel.ConsumerSecret, storedRequestTokenModel.EndpointModel);

            if (string.IsNullOrEmpty(verifier))
            {
                throw new Exception("Expected a non-empty verifier value");
            }

            IOAuthToken accessToken;

            try
            {
                accessToken  = oauthClient.ExchangeRequestTokenForAccessToken(storedRequestTokenModel, verifier);
                model.Token  = accessToken.Token;
                model.Secret = accessToken.Secret;
            }
            catch (OAuthException authEx)
            {
                Session["problem"] = authEx.Report;
                Response.Redirect("AccessDenied.aspx");
            }

            return(View(model));
        }
Beispiel #4
0
        public void UploadFile(RequestTokenModel model, string path)
        {
            var fileContent = @"C:\Test\testDoc.txt";
            var newPath     = path.Replace(">", "/"); //Temporary solution. Only for swagger bug

            var json = _service.UploadFile(model.Token, newPath, fileContent);
        }
Beispiel #5
0
        public async Task <IActionResult> RefreshToken([FromBody] RequestTokenModel requestToken)
        {
            // validate ModalState if it's inValid return badRequest
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }
            // get ipAdress for request
            var ipAddress = GetIpAddress();

            var domain = await _context.RefeshTokens.FirstOrDefaultAsync(t => t.Token.Equals(requestToken.Token) && t.CreateByIp.Equals(ipAddress));

            if (domain == null)
            {
                return(BadRequest());
            }
            // revoke current refreshToken
            domain.RevokedDate = DateTime.Now;
            await _context.SaveChangesAsync();

            // generate new token and new refreshToken

            var jwtToken        = GenerateToken(domain.User);
            var newRefreshToken = GenerateRefreshToken(domain.User);
            // no need to save token, but refreshToken needed
            await _context.RefeshTokens.AddAsync(newRefreshToken);

            await _context.SaveChangesAsync();

            return(Ok(new SiginResultModel {
                Token = jwtToken,
                RefeshToken = newRefreshToken.Token
            }));
        }
Beispiel #6
0
        public void CopyFileTo(RequestTokenModel model, string path, string pathTo)
        {
            var newPath   = path.Replace(">", "/");   //Temporary solution. Only for a swagger's bug
            var newPathTo = pathTo.Replace(">", "/"); //Temporary solution. Only for a swagger's bug

            var json = _service.CopyFile(model.Token, newPath, newPathTo).Result;
        }
Beispiel #7
0
        /// <summary>
        /// Generates user token after successful register/login
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        private string GenerateUserToken(RequestTokenModel request)
        {
            string token = string.Empty;

            var claim = new List <Claim>()
            {
                new Claim(ClaimTypes.Email, request.Email),
            };

            if (request.Roles != null)
            {
                for (int i = 0; i < request.Roles.Count; i++)
                {
                    claim.Add(new Claim(ClaimTypes.Role, request.Roles.ToList()[i].RoleName));
                }
            }


            var key         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_tokenManagement.Secret));
            var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var jwtToken = new JwtSecurityToken(
                _tokenManagement.Issuer,
                _tokenManagement.Audience,
                claim,
                expires: DateTime.Now.AddMinutes(_tokenManagement.AccessExpiration),
                signingCredentials: credentials
                );

            token = new JwtSecurityTokenHandler().WriteToken(jwtToken);
            return(token);
        }
Beispiel #8
0
        public void GetRequestToken(string consumerKey, string consumerSecret, string callbackUrl, string serviceUri, string requestTokenUri, string authorizationUri, string accessTokenUri)
        {
            RequestTokenModel model = new RequestTokenModel();

            model.ConsumerKey    = consumerKey;
            model.ConsumerSecret = consumerSecret;

            EndpointModel endpointModel = new EndpointModel();

            endpointModel.ServiceUri       = serviceUri;
            endpointModel.RequestTokenUri  = requestTokenUri;
            endpointModel.AuthorizationUri = authorizationUri;
            endpointModel.AccessTokenUri   = accessTokenUri;
            model.EndpointModel            = endpointModel;

            OAuthClientBase oauthClient = OAuthClient.CreateClient(consumerKey, consumerSecret, endpointModel);

            if (oauthClient != null)
            {
                IOAuthToken requestToken = oauthClient.GetRequestToken(this.GenerateRealm(TestUserId, "*****@*****.**"), callbackUrl);
                model.Token  = requestToken.Token;
                model.Secret = requestToken.Secret;
            }

            Session[model.Token] = model;

            string authorizationUrl = oauthClient.GetUserAuthorizationUrl(model);

            this.Response.Redirect(authorizationUrl, false);
        }
Beispiel #9
0
        public ActionResult GetInlineOAuthToken(string consumerKey, string consumerSecret, string callbackUrl, string serviceUri, string requestTokenUri, string authorizationUri, string accessTokenUri)
        {
            RequestTokenModel model = new RequestTokenModel();

            model.ConsumerKey    = consumerKey;
            model.ConsumerSecret = consumerSecret;

            EndpointModel endpointModel = new EndpointModel();

            endpointModel.ServiceUri       = serviceUri;
            endpointModel.RequestTokenUri  = requestTokenUri;
            endpointModel.AuthorizationUri = authorizationUri;
            endpointModel.AccessTokenUri   = accessTokenUri;
            model.EndpointModel            = endpointModel;

            OAuthClient oauthClient = new OAuthClient(model.ConsumerKey, model.ConsumerSecret, model.EndpointModel);

            try
            {
                IOAuthToken accessToken = oauthClient.GetInlineAccessToken(Realm.GetDefault());
                model.Token  = accessToken.Token;
                model.Secret = accessToken.Secret;
            }
            catch (OAuthException authEx)
            {
                Session["problem"] = authEx.Report;
                Response.Redirect("AccessDenied.aspx");
            }

            return(View("OauthCallback", model));
        }
Beispiel #10
0
        public void GetRequestToken(string consumerKey, string consumerSecret, string callbackUrl, string serviceUri, string requestTokenUri, string authorizationUri, string accessTokenUri)
        {
            RequestTokenModel model = new RequestTokenModel();

            model.ConsumerKey    = consumerKey;
            model.ConsumerSecret = consumerSecret;

            EndpointModel endpointModel = new EndpointModel();

            endpointModel.ServiceUri       = serviceUri;
            endpointModel.RequestTokenUri  = requestTokenUri;
            endpointModel.AuthorizationUri = authorizationUri;
            endpointModel.AccessTokenUri   = accessTokenUri;
            model.EndpointModel            = endpointModel;

            Session["endpoints"] = model;

            OAuthClient oauthClient = new OAuthClient(endpointModel, TestSite.MvcApplication.GetTokenManager(consumerKey, consumerSecret));

            if (oauthClient != null)
            {
                Realm realm = this.GenerateRealm(OpenAuthController.TestUserId, "*****@*****.**");
                oauthClient.GetRequestToken(realm, callbackUrl);
            }
        }
Beispiel #11
0
        public ActionResult OAuthCallback(string oauth_token, string oauth_verifier)
        {
            RequestTokenModel model        = new RequestTokenModel();
            RequestTokenModel sessionModel = Session["endpoints"] as RequestTokenModel;

            model = sessionModel;

            OAuthKeyConfiguration oauthConfiguration = OAuthKeyConfiguration.GetInstance();

            if (string.IsNullOrEmpty(oauth_verifier))
            {
                throw new Exception("Expected a non-empty verifier value");
            }

            OAuthClient oauthClient = new OAuthClient(sessionModel.EndpointModel, TestSite.MvcApplication.GetTokenManager(sessionModel.ConsumerKey, sessionModel.ConsumerSecret));

            if (oauthClient != null)
            {
                IOAuthToken oauthToken = oauthClient.ExchangeRequestTokenForAccessToken(oauth_verifier);

                if (oauthToken != null)
                {
                    model.Token  = oauthToken.Token;
                    model.Secret = oauthToken.Secret;
                }
            }

            return(View(model));
        }
Beispiel #12
0
        public DropboxItem GetFile(RequestTokenModel model, string path)
        {
            var newPath = path.Replace(">", "/"); //Temporary solution. Only for a swagger's bug

            var json = _service.GetFile(model.Token, newPath).Result;

            return(JsonConvert.DeserializeObject <DropboxItem>(json));
        }
Beispiel #13
0
        public string DownloadFile(RequestTokenModel model, string path)
        {
            var newPath = path.Replace(">", "/"); //Temporary solution. Only for swagger bug

            var json = _service.GetLinkToDownloadFile(model.Token, newPath).Result;

            return(JsonConvert.DeserializeObject <LinkToDownloadModel>(json).link);
        }
        public IList <string> GetList(RequestTokenModel model, string folderId)
        {
            var json = _service.GetList(model.Token, folderId).Result;

            var items = JsonConvert.DeserializeObject <ChildrenListModel>(json).items as List <ChildrenModel>;
            var list  = new List <string>();

            items.ForEach(item => list.Add(item.id));

            return(list);
        }
        public Dictionary <string, string> GetList(RequestTokenModel model)
        {
            var json  = _service.GetList(model.Token).Result;
            var files = JsonConvert.DeserializeObject <FilesListModel>(json)._embedded.items as List <YandexdiscItem>;

            var list = new Dictionary <string, string>();

            files.ForEach(file => list.Add(file.name, file.path.Replace("disk:", "")));

            return(list);
        }
Beispiel #16
0
        public Dictionary <string, string> GetList(RequestTokenModel model, string folderId = "root")
        {
            var json  = _service.GetList(model.Token, folderId).Result;
            var files = JsonConvert.DeserializeObject <FilesListModel>(json).value as List <OneDriveItem>;

            var list = new Dictionary <string, string>();

            files.ForEach(file => list.Add(file.name, file.id));

            return(list);
        }
        public Dictionary <string, string> GetList(RequestTokenModel model)
        {
            var json  = _service.GetList(model.Token).Result;
            var files = JsonConvert.DeserializeObject <FilesListModel>(json).files as List <File>;

            var list = new Dictionary <string, string>();

            files.ForEach(file => list.Add(file.Id, file.Name));

            return(list);
        }
        private string GetUploadLink(RequestTokenModel model, string path)
        {
            var uploadModel = new UploadInfoRequestModel()
            {
                description = "file description",
                mimeType    = "text/plain",
                title       = "test file"
            };

            var json = _service.GetUploadModel(model.Token, uploadModel).Result;

            return(JsonConvert.DeserializeObject <UploadInfoResponseModel>(json).id);
        }
Beispiel #19
0
        public Dictionary <string, string> GetList(RequestTokenModel model, string path = "")
        {
            var newPath = path.Replace(">", "/"); //Temporary solution. Only for a swagger's bug

            var json  = _service.GetList(model.Token, newPath).Result;
            var files = JsonConvert.DeserializeObject <FilesListModel>(json).entries as List <DropboxItem>;

            var list = new Dictionary <string, string>();

            files.ForEach(file => list.Add(file.path_lower, file.name));

            return(list);
        }
Beispiel #20
0
        public async Task <TokenResponseModel> ProvideTokenAsync(RequestTokenModel requestModel)
        {
            AppUserEntity entity = null;

            switch (requestModel.GrantType)
            {
            case SecurityConsts.GrantTypes.Password:
            {
                entity = await AuthenticateAsync(requestModel.Username, requestModel.Password);
            }
            break;

            case SecurityConsts.GrantTypes.RefreshToken:
            {
                var validResult = ValidateRefreshToken(requestModel.RefreshToken);

                entity = await _userManager.FindByIdAsync(validResult.IdentityName());
            }
            break;

            default:
            {
                throw OAuthException.UnsupportedGrantType(description: nameof(requestModel.GrantType));
            }
            }

            if (entity == null)
            {
                throw OAuthException.InvalidGrant();
            }

            var identity =
                await GetIdentityAsync(entity, JwtBearerDefaults.AuthenticationScheme);

            #region Handle scope
            if (requestModel.Scope != null)
            {
                // demo only, real scenario: validate requested scopes first --> ...
                var scopes = requestModel.Scope.Split(',')
                             .Select(scope => new Claim(SecurityConsts.ClaimTypes.AppScope, scope.Trim())).ToArray();

                identity.AddClaims(scopes);
            }
            #endregion

            var principal = new ClaimsPrincipal(identity);

            var tokenResponse = GenerateTokenResponse(principal);

            return(tokenResponse);
        }
Beispiel #21
0
        public async Task <IActionResult> GetToken([FromBody] RequestTokenModel model)
        {
            try
            {
                GrantTypeHelper.CheckAllowGenerateToken(model.GrantType);

                var tokenModel = await _authenticationService.GetTokenAsync(model, this.GetRequestCancellationToken())
                                 .ConfigureAwait(true);

                return(Ok(tokenModel));
            }
            catch (CoreException e)
            {
                ErrorModel errorModel = new ErrorModel(e.Code, e.Message, e.AdditionalData);

                return(BadRequest(errorModel));
            }
        }
Beispiel #22
0
        public async Task <IActionResult> GetToken(RequestTokenModel model)
        {
            var client             = _clientFactory.CreateClient();
            var authProviderConfig = _configuration.GetSection("AuthenticationProvider");

            var response = await client.RequestPasswordTokenAsync(new PasswordTokenRequest
            {
                Address   = $"{authProviderConfig["Url"]}/connect/token",
                GrantType = GrantType.ResourceOwnerPassword,

                ClientId     = authProviderConfig["ClientId"],
                ClientSecret = authProviderConfig["ClientSecret"],

                UserName = model.UserName,
                Password = model.Password
            });

            return(CreateContentResult(response));
        }
Beispiel #23
0
        /// <summary> Request a token for a user (Login) </summary>
        public ActionResult RequestToken([FromBody] RequestTokenModel model)
        {
            if (model == null ||
                (string.IsNullOrWhiteSpace(model.UserName)) ||
                string.IsNullOrWhiteSpace(model.Password))
            {
                return(CreateResponse("None of the parameters can be null"));
            }

            Validator validator = new Validator();

            DataResult <User> dr = authorizeCore.Authenticate(new User()
            {
                UserName = model.UserName, Password = model.Password
            }, _appSettings.Value.Secret);

            if (!dr.Success)
            {
                return(CreateResponse(dr.ErrorMessage));
            }

            User user = dr.Data.FirstOrDefault();

            Settings settings = UserCore.Instance.GetSettings(user.Id);

            JObject data = new JObject();

            data["user"] = JToken.FromObject(new { userName = user.UserName, token = user.Token });

            if (settings != null)
            {
                data["settings"] = JToken.FromObject(new { enabledNotifications   = settings.EnabledNotifications,
                                                           notificationRecipients = settings.NotificationRecipients });
            }

            return(CreateResponse(data: JsonConvert.SerializeObject(data), success: dr.Success));
        }
        public File GetFile(RequestTokenModel model, string fileId)
        {
            var json = _service.GetFile(model.Token, fileId).Result;

            return(JsonConvert.DeserializeObject <File>(json));
        }
 public void CopyFileTo(RequestTokenModel model, string fileId, string parentId)
 {
     var json = _service.CopyFile(model.Token, fileId, parentId).Result;
 }
Beispiel #26
0
 public void UploadFile(RequestTokenModel model, string parentId)
 {
     var fileContent = @"C:\Test\testDoc.txt";
     var res         = _service.UploadFile(model.Token, parentId, fileContent);
 }
        public async Task <ActionResult> RequestResetToken(RequestTokenModel model)
        {
            var success = false;

            if (ModelState.IsValid)
            {
                ApplicationUser user = null;
                #region validate email
                bool   emailValid = false;
                string username   = "";
                string extension  = "";
                string email      = model.Email.ToLower();
                try
                {
                    username  = model.Email.Substring(0, model.Email.IndexOf('@')).ToLower();
                    extension = model.Email.Substring(model.Email.IndexOf('@') + 1).ToLower();

                    var userInfo = (from u in db.Users
                                    where u.UserName.Equals(username) && u.Email.Equals(email) && u.Verified == true
                                    select u);

                    // validate the email extension and username the student entered
                    var count = await userInfo.CountAsync();

                    if (count > 0)
                    {
                        emailValid = true;
                        user       = await userInfo.FirstAsync();
                    }
                    else
                    {
                        emailValid = false;
                        ModelState.AddModelError("Email", "The student email address entered is not valid");
                    }
                }
                catch (Exception e)
                {
                    emailValid = false;
                    Trace.WriteLine(e.Message, "Reset Token Request");
                    ModelState.AddModelError("Email", "The student email address entered is not valid");
                }
                #endregion

                #region send reset email
                if (emailValid)
                {
                    string clientName = user.TitleID + " " + user.Intials + " " + user.Surname;

                    success = NotificationsHelper.SendPasswordResetEmail(user.Email, clientName, this.ControllerContext);
                    if (!success)
                    {
                        Trace.WriteLine(String.Format("*** WARNING:  A reset email to '{0}' failed.", user.Email));
                        ModelState.AddModelError("", "An error occured while sending a reset password email. Please try again later");
                    }
                }
                #endregion
            }

            ViewBag.Success = success;
            return(View());
        }
Beispiel #28
0
        GetTokenAsync(RequestTokenModel model,
                      CancellationToken cancellationToken = default)
        {
            var systemNow = SystemHelper.SystemTimeNow;

            //var appService = _serviceProvider.GetService<IApplicationService>();

            //appService.CheckValid(model.ClientId, model.GrantType);
            var userService = _serviceProvider.GetService <IUserService>();


            var tokenModel = new TokenModel
            {
                ExpireIn = systemNow.AddSeconds(3600).ToTimestamp(),
                //State = model.State,
                TokenType = TokenType.AuthTokenType
            };

            switch (model.GrantType)
            {
            case GrantType.AuthorizationCode:
            //case GrantType.AuthorizationCodePKCE:
            //{
            //    AuthorizeCodeStorageModel authorizeCodeStorageModel = GetValidCode(model);

            //    var userBasicInfo = GetUserBasicInfoByUserName(authorizeCodeStorageModel.UserName);

            //    tokenModel.AccessToken = JwtHelper.Generate(userBasicInfo, 3600);

            //    tokenModel.RefreshToken = GenerateRefreshToken(userBasicInfo.Id);

            //    break;
            //}
            //case GrantType.Implicit:
            //{
            //    var userBasicInfo = GetUserBasicInfoByUserName(model.UserName);

            //    tokenModel.AccessToken = JwtHelper.Generate(userBasicInfo, 3600);

            //    break;
            //}
            case GrantType.ResourceOwner:
            {
                CheckValidSignIn(model.UserName, model.Password);

                var userBasicInfo = GetUserBasicInfoByUserName(model.UserName);

                tokenModel.AccessToken = JwtHelper.Generate(userBasicInfo, 3600);

                tokenModel.RefreshToken = GenerateRefreshToken(userBasicInfo.Id);

                break;
            }

            case GrantType.RefreshToken:
            {
                CheckValidRefreshToken(model.RefreshToken);

                tokenModel.RefreshToken = model.RefreshToken;

                var userBasicInfo = GetUserBasicInfoByRefreshToken(model.RefreshToken);

                tokenModel.AccessToken = JwtHelper.Generate(userBasicInfo, 3600);

                break;
            }
            }

            return(Task.FromResult(tokenModel));
        }
 public string DownloadFile(RequestTokenModel model, string fileId)
 {
     return(_service.GetLinkToDownloadFile(model.Token, fileId).Result);
 }
 public void DeleteFile(RequestTokenModel model, string fileId)
 {
     var json = _service.DeleteFile(model.Token, fileId).Result;
 }