Esempio n. 1
0
        /// <summary>
        /// Recuperar la información de usuario del token
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        public UsuariInfo DecodeJwtToken(string token)
        {
            // EXTRAE LA INFORMACIÓN DEL TOKEN JWT.
            var handler = new JwtSecurityTokenHandler();
            var _token  = handler?.ReadJwtToken(token);

            // CREA EL PERFIL DE INFORMACIÓN DEL USUARIO
            // A PARTIR DE LOS CLAIMS DEL TOKEN JWT
            var _usuarioInfo = new UsuariInfo()
            {
                Id = new Guid(_token?.Claims?.
                              SingleOrDefault(x => x.Type == "nameid")?.Value
                              ?? _token.Id),

                Email = _token?.Claims?.
                        SingleOrDefault(x => x.Type == "email")?.Value,

                Rol = _token?.Claims?.
                      SingleOrDefault(x => x.Type.Contains("role"))?.Value,

                ValidoDesde = _token.ValidFrom,

                ValidoHasta = _token.ValidTo
            };

            return(_usuarioInfo);
        }
Esempio n. 2
0
        public async Task Invoke(HttpContext context, DataContext dataContext)
        {
            string authorize = context.Request.Headers["Authorization"];
            string route     = context.Request.Path;

            // Validate
            if (!route.StartsWith("/api"))
            {
                context.Session.SetInt32(SessionConstant.NeedAuthorize, 0);
                await next(context);

                return;
            }

            route = route.Substring("/api/".Length);

            var isAuthorize = needAuthorize(route);

            if (isAuthorize == false)
            {
                context.Session.SetInt32(SessionConstant.NeedAuthorize, 0);
                await next(context);
            }
            else
            {
                context.Session.SetInt32(SessionConstant.NeedAuthorize, 1);

                if (authorize != null && authorize.StartsWith("Bearer"))
                {
                    string token = authorize.Substring("Bearer ".Length).Trim();

                    var handler = new JwtSecurityTokenHandler();
                    if (handler.CanReadToken(token))
                    {
                        var decodeToken = handler.ReadJwtToken(token);

                        if (route.StartsWith("admin/"))
                        {
                            context.Session.SetString(SessionConstant.Site, SessionConstant.Admin);

                            var userId = decodeToken.Claims.FirstOrDefault(c => c.Type == "nameid") != null?
                                         decodeToken.Claims.FirstOrDefault(c => c.Type == "nameid").Value : null;

                            var username = decodeToken.Claims.FirstOrDefault(c => c.Type == "unique_name") != null?
                                           decodeToken.Claims.FirstOrDefault(c => c.Type == "unique_name").Value : null;

                            var role = decodeToken.Claims.FirstOrDefault(c => c.Type == "role") != null?
                                       decodeToken.Claims.FirstOrDefault(c => c.Type == "role").Value : null;

                            var user = await dataContext.Users.FirstOrDefaultAsync(u => u.Id.ToString() == userId);

                            if (user == null || user.Username != username || userId == null)
                            {
                                await MiddlewareHelper.AccessDenied(context);

                                return;
                            }

                            context.Session.SetString(SessionConstant.Route, route);
                            context.Session.SetString(SessionConstant.Role, role);
                            context.Session.SetString(SessionConstant.Username, username);
                        }
                        else if (route.StartsWith("client/"))
                        {
                            context.Session.SetString(SessionConstant.Site, SessionConstant.Client);

                            var username = decodeToken.Claims.FirstOrDefault(c => c.Type == "sub") != null?
                                           decodeToken.Claims.FirstOrDefault(c => c.Type == "sub").Value : null;

                            //
                            // var customer = await dataContext.Customers.FirstOrDefaultAsync(c => c.Username == username);

                            if (username == null)
                            {
                                await MiddlewareHelper.AccessDenied(context);

                                return;
                            }

                            context.Session.SetString(SessionConstant.Username, username);
                        }

                        await next(context);
                    }
                    else
                    {
                        await MiddlewareHelper.AccessDenied(context);

                        return;
                    }
                }
                else
                {
                    await MiddlewareHelper.AccessDenied(context);

                    return;
                }
            }
        }
Esempio n. 3
0
        public IActionResult Validate(UserVM userVM)
        {
            if (userVM.UserName == null)
            {
                var jsonUserVM  = JsonConvert.SerializeObject(userVM);
                var buffer      = System.Text.Encoding.UTF8.GetBytes(jsonUserVM);
                var byteContent = new ByteArrayContent(buffer);
                byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                var resTask = client.PostAsync("user/login/", byteContent);
                resTask.Wait();
                var result = resTask.Result;
                if (result.IsSuccessStatusCode)
                {
                    var data = result.Content.ReadAsStringAsync().Result;
                    if (data != "")
                    {
                        //var json = JsonConvert.DeserializeObject(data).ToString();
                        //var account = JsonConvert.DeserializeObject<UserVM>(json);
                        var handler = new JwtSecurityTokenHandler();
                        var tokenS  = handler.ReadJwtToken(data);
                        var account = new UserVM();
                        account.Id       = tokenS.Claims.First(claim => claim.Type == "Id").Value;
                        account.UserName = tokenS.Claims.First(claim => claim.Type == "UserName").Value;
                        account.Email    = tokenS.Claims.First(claim => claim.Type == "Email").Value;
                        account.RoleName = tokenS.Claims.First(claim => claim.Type == "RoleName").Value;

                        if (account.VerifyCode != null)
                        {
                            if (userVM.VerifyCode != account.VerifyCode)
                            {
                                return(Json(new { status = true, msg = "Check your Code" }));
                            }
                        }

                        else if (account.RoleName == "Admin" || account.RoleName == "Sales")
                        {
                            HttpContext.Session.SetString("id", account.Id);
                            HttpContext.Session.SetString("username", account.UserName);
                            HttpContext.Session.SetString("email", account.Email);
                            HttpContext.Session.SetString("lvl", account.RoleName);
                            if (account.RoleName == "Admin")
                            {
                                return(Json(new { status = true, msg = "Login Successfully !", acc = "Admin" }));
                            }
                            else
                            {
                                return(Json(new { status = true, msg = "Login Successfully !", acc = "Sales" }));
                            }
                        }
                        else
                        {
                            return(Json(new { status = false, msg = "Invalid Username or Password!" }));
                        }
                    }
                    else
                    {
                        return(Json(new { status = false, msg = "Username Not Found!" }));
                    }
                }
                else
                {
                    //return RedirectToAction("Login","Auth");
                    return(Json(new { status = false, msg = "Username Not Found!" }));
                }
            }
            else if (userVM.UserName != null)
            {
                var json        = JsonConvert.SerializeObject(userVM);
                var buffer      = System.Text.Encoding.UTF8.GetBytes(json);
                var byteContent = new ByteArrayContent(buffer);
                byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                var result = client.PostAsync("user/", byteContent).Result;
                if (result.IsSuccessStatusCode)
                {
                    return(Json(new { status = true, code = result, msg = "Register Success! " }));
                }
                else
                {
                    return(Json(new { status = false, msg = "Something Wrong!" }));
                }
            }
            return(Redirect("/login"));
        }
Esempio n. 4
0
        public async Task <IActionResult> ChangeTicket([FromBody] TicketChangeInput input = null)
        {
            // Check that every input is there
            if (input == null)
            {
                return(BadRequest(new GeneralMessage()
                {
                    Message = "Missing input data"
                }));
            }

            Category cat = null;

            if (!string.IsNullOrEmpty(input.System) && !string.IsNullOrWhiteSpace(input.System) && !string.IsNullOrEmpty(input.CategoryName) && !string.IsNullOrWhiteSpace(input.CategoryName))
            {
                var sys = await _dbHandler.GetSystemAsync(input.System);

                if (sys == null)
                {
                    return(BadRequest(new GeneralMessage()
                    {
                        Message = "Invalid system is defined"
                    }));
                }

                cat = await _dbHandler.GetCategoryAsync(input.CategoryName, sys);

                if (cat == null)
                {
                    return(BadRequest(new GeneralMessage()
                    {
                        Message = "Invalid category is defined"
                    }));
                }
            }

            input.Category = cat;

            // Get user who wants remove user
            var re          = Request;
            var headers     = re.Headers;
            var tokenString = headers["Authorization"];

            var handler = new JwtSecurityTokenHandler();
            var token   = handler.ReadJwtToken(tokenString[0].Split(' ')[1]);

            var claims        = token.Claims;
            var usernameClaim = claims.Where(x => x.Type == ClaimTypes.Name).FirstOrDefault();
            var user          = await _dbHandler.GetUserAsync(usernameClaim.Value);

            input.ChangederUser = user;

            if (input.CategoryName == null)
            {
                input.Category = null;
            }
            if (input.Refernce == null)
            {
                input.Refernce = "";
            }
            if (input.System == null)
            {
                input.System = "";
            }
            if (input.Title == null)
            {
                input.Title = "";
            }

            var respond = await _dbHandler.ChangeTicketAsync(input);

            if (respond.MessageType == MessageType.NOK)
            {
                return(BadRequest(new GeneralMessage()
                {
                    Message = respond.MessageText
                }));
            }

            return(Ok(new GeneralMessage()
            {
                Message = respond.MessageText
            }));
        }
Esempio n. 5
0
        public async Task <IActionResult> CloseTicket(int id = -1, string reference = null, string system = null)
        {
            // Get user name who wants to get info
            var re          = Request;
            var headers     = re.Headers;
            var tokenString = headers["Authorization"];

            var handler = new JwtSecurityTokenHandler();
            var token   = handler.ReadJwtToken(tokenString[0].Split(' ')[1]);

            var claims        = token.Claims;
            var usernameClaim = claims.Where(x => x.Type == ClaimTypes.Name).FirstOrDefault();
            var user          = await _dbHandler.GetUserAsync(usernameClaim.Value);

            if (user == null)
            {
                return(BadRequest(new GeneralMessage()
                {
                    Message = "User does not exist"
                }));
            }

            // Close the ticket
            if (id != -1)
            {
                // Get ticket, return with BadRequest of requestor can't close the ticket
                var ticket = await _dbHandler.GetTicketAsync(id);

                if (ticket == null)
                {
                    return(BadRequest(new GeneralMessage()
                    {
                        Message = "Ticket does not exist"
                    }));
                }

                if (ticket.UserId != user.Id && user.Role != UserRole.Admin)
                {
                    return(BadRequest(new GeneralMessage()
                    {
                        Message = "Only Admin or ticket owner can close ticket"
                    }));
                }

                // Close the ticket
                var respond = await _dbHandler.CloseTicketAsync(id, user);

                if (respond.MessageType == MessageType.NOK)
                {
                    return(BadRequest(new GeneralMessage()
                    {
                        Message = respond.MessageText
                    }));
                }

                return(Ok(new GeneralMessage()
                {
                    Message = respond.MessageText
                }));
            }
            else if (reference != null && system != null)
            {
                // Get ticket, return with BadRequest of requestor can't close the ticket
                var ticketList = await _dbHandler.GetTicketAsync(reference, system);

                if (ticketList == null)
                {
                    return(BadRequest(new GeneralMessage()
                    {
                        Message = "Ticket does not exist"
                    }));
                }

                var ticket = ticketList.FirstOrDefault(s => s.Status.Equals("Open"));
                if (ticket == null)
                {
                    return(BadRequest(new GeneralMessage()
                    {
                        Message = "Ticket does not exist"
                    }));
                }

                if (ticket.UserId != user.Id && user.Role != UserRole.Admin)
                {
                    return(BadRequest(new GeneralMessage()
                    {
                        Message = "Only Admin or ticket owner can close ticket"
                    }));
                }

                // Close the ticket
                var respond = await _dbHandler.CloseTicketAsync(ticket.Id, user);

                if (respond.MessageType == MessageType.NOK)
                {
                    return(BadRequest(new GeneralMessage()
                    {
                        Message = respond.MessageText
                    }));
                }

                return(Ok(new GeneralMessage()
                {
                    Message = respond.MessageText
                }));
            }
            else
            {
                return(BadRequest(new GeneralMessage()
                {
                    Message = "Invalid input parameter. Specify ID or Reference value and system name"
                }));
            }
        }
        public async Task <IActionResult> Add()
        {
            var token = HttpContext.Request.Headers["Authorization"].Last().Split(" ").Last();

            string[] roles   = { "User" };
            var      handler = new JwtSecurityTokenHandler();

            if (RoleService.CheckRoles(token, roles, _userManager))
            {
                var httpRequest = HttpContext.Request;
                var file        = httpRequest.Body;

                //checks the size of file
                var imageHandler = new ImageSecurityHandler();
                if (!imageHandler.CheckFileSize(httpRequest.ContentLength.Value))
                {
                    _logger.LogInformation($"size is {httpRequest.ContentLength}");
                    return(BadRequest("Photo must be between 5KB and 5MB"));
                }
                //checks the format of file
                if (!imageHandler.CheckFileFormat(httpRequest.ContentType))
                {
                    _logger.LogInformation($"file format is {httpRequest.ContentType}");
                    return(BadRequest("Wrong file format"));
                }

                var sub = handler.ReadJwtToken(token).Payload.Sub;

                var credentials =
                    GoogleCredential.FromFile("../Infrastructure/Images/GCStorage/Rosta-a2299c0ab851.json");
                var storage = StorageClient.CreateAsync(credentials);

                var lastId = 0;
                if (storage.Result
                    .ListObjects("deep-castle-261418-user-photo-bucket")
                    .Select(x => x.Name)
                    .Count(x => x.Contains(sub)) > 0)
                {
                    lastId = int.Parse(storage.Result
                                       .ListObjects("deep-castle-261418-user-photo-bucket")
                                       .Select(x => x.Name).Last(x => x.Contains(sub))
                                       .Split("-").Last());
                }


                var detailsRepository   = new UserDetailsRepository();
                var details             = detailsRepository.GetByUserId(sub);
                var candidacyRepository = new CandidacyRepository();
                var candidacy           = candidacyRepository.GetAll().Last(x => x.OwnerId == details.Id);

                //Checks if User have candidacy
                if (candidacyRepository.GetAll().Count(x => x.OwnerId == details.Id) == 0)
                {
                    return(BadRequest("User didnt submited candidacy."));
                }

                //Uploading Photo to Google Cloud and updating indecies.
                var photoName = $"{sub}-profilePhoto-{lastId + 1}";
                storage.Result.UploadObject("deep-castle-261418-user-photo-bucket", photoName,
                                            MediaTypeNames.Image.Jpeg, file, null);

                candidacy.PhotoPath = photoName;
                candidacyRepository.Edit(candidacy);

                return(Ok());
            }

            return(Unauthorized());
        }
Esempio n. 7
0
        public TResult Parse <TResult>(string jwtEncodedString,
                                       string issuer, string[] validAudiences,
                                       Func <string, JwtSecurityToken, ClaimsPrincipal, TResult> onSuccess,
                                       Func <string, TResult> onInvalidToken)
        {
            // From: https://developer.apple.com/documentation/signinwithapplerestapi/verifying_a_user
            // To verify the identity token, your app server must:
            // * Verify the JWS E256 signature using the server’s public key
            // * Verify the nonce for the authentication
            // * Verify that the iss field contains https://appleid.apple.com
            // * Verify that the aud field is the developer’s client_id
            // * Verify that the time is earlier than the exp value of the token

            var handler = new JwtSecurityTokenHandler();
            var token   = handler.ReadJwtToken(jwtEncodedString);

            return(this.DecodeRSA(token.Header.Kid,
                                  rsaParams =>
            {
                var validationParameters = new TokenValidationParameters()
                {
                    ValidateAudience = true,
                    ValidIssuer = issuer,
                    ValidAudiences = validAudiences,
                    IssuerSigningKey = new RsaSecurityKey(rsaParams),
                    RequireExpirationTime = true,
                };

                try
                {
                    var principal = handler.ValidateToken(jwtEncodedString, validationParameters,
                                                          out SecurityToken validatedToken);

                    return principal.Claims
                    .Where(claim => System.Security.Claims.ClaimTypes.NameIdentifier.Equals(claim.Type, StringComparison.OrdinalIgnoreCase))
                    .First(
                        (claim, next) =>
                    {
                        return onSuccess(claim.Value, token, principal);
                    },
                        () => onInvalidToken("JWT did not specifiy a claims identity."));
                }
                catch (ArgumentException ex)
                {
                    return onInvalidToken(ex.Message);
                }
                catch (Microsoft.IdentityModel.Tokens.SecurityTokenInvalidIssuerException ex)
                {
                    return onInvalidToken(ex.Message);
                }
                catch (Microsoft.IdentityModel.Tokens.SecurityTokenExpiredException ex)
                {
                    return onInvalidToken(ex.Message);
                }
                catch (Microsoft.IdentityModel.Tokens.SecurityTokenException ex)
                {
                    return onInvalidToken(ex.Message);
                }
            },
                                  () => onInvalidToken("Key does not match OAuth key tokens")));
        }
        /// <summary>
        /// Validates the specified identity token.
        /// </summary>
        /// <param name="identityToken">The identity token.</param>
        /// <returns>The validation result</returns>
        public async Task <IdentityTokenValidationResult> ValidateAsync(string identityToken)
        {
            _logger.LogTrace("Validate");

            var handler = new JwtSecurityTokenHandler();

            handler.InboundClaimTypeMap.Clear();

            // setup general validation parameters
            var parameters = new TokenValidationParameters
            {
                ValidIssuer   = _options.ProviderInformation.IssuerName,
                ValidAudience = _options.ClientId,

                NameClaimType = _options.NameClaimType,
                RoleClaimType = _options.RoleClaimType,

                ClockSkew = _options.ClockSkew
            };

            // read the token signing algorithm
            JwtSecurityToken jwt;

            try
            {
                jwt = handler.ReadJwtToken(identityToken);
            }
            catch (Exception ex)
            {
                return(new IdentityTokenValidationResult
                {
                    Error = $"Error validating identity token: {ex.ToString()}"
                });
            }

            var algorithm = jwt.Header.Alg;

            // if token is unsigned, and this is allowed, skip signature validation
            if (string.Equals(algorithm, "none"))
            {
                if (_options.Policy.RequireIdentityTokenSignature)
                {
                    return(new IdentityTokenValidationResult
                    {
                        Error = $"Identity token is not singed. Signatures are required by policy"
                    });
                }
                else
                {
                    _logger.LogInformation("Identity token is not signed. This is allowed by configuration.");
                    parameters.RequireSignedTokens = false;
                }
            }
            else
            {
                // check if signature algorithm is allowed by policy
                if (!_options.Policy.ValidSignatureAlgorithms.Contains(algorithm))
                {
                    return(new IdentityTokenValidationResult
                    {
                        Error = $"Identity token uses invalid algorithm: {algorithm}"
                    });
                }
                ;
            }

            ClaimsPrincipal user;

            try
            {
                user = ValidateSignature(identityToken, handler, parameters);
            }
            catch (SecurityTokenSignatureKeyNotFoundException sigEx)
            {
                if (_options.RefreshDiscoveryOnSignatureFailure)
                {
                    _logger.LogWarning("Key for validating token signature cannot be found. Refreshing keyset.");

                    // try to refresh the key set and try again
                    await _refreshKeysAsync();

                    try
                    {
                        user = ValidateSignature(identityToken, handler, parameters);
                    }
                    catch (Exception ex)
                    {
                        return(new IdentityTokenValidationResult
                        {
                            Error = $"Error validating identity token: {ex.ToString()}"
                        });
                    }
                }
                else
                {
                    return(new IdentityTokenValidationResult
                    {
                        Error = $"Error validating identity token: {sigEx.ToString()}"
                    });
                }
            }
            catch (Exception ex)
            {
                return(new IdentityTokenValidationResult
                {
                    Error = $"Error validating identity token: {ex.ToString()}"
                });
            }

            var error = CheckRequiredClaim(user);

            if (error.IsPresent())
            {
                return(new IdentityTokenValidationResult
                {
                    Error = error
                });
            }

            return(new IdentityTokenValidationResult
            {
                User = user,
                SignatureAlgorithm = algorithm
            });
        }
Esempio n. 9
0
        public async Task DashboardLoginSuccessFull_and_TokenValidForFhirServer()
        {
            Assert.True(!string.IsNullOrWhiteSpace(_config["FhirServerUrl"]));
            Assert.True(!string.IsNullOrWhiteSpace(_config["DashboardUrl"]));
            Assert.True(!string.IsNullOrWhiteSpace(_config["DashboardUserUpn"]));
            Assert.True(!string.IsNullOrWhiteSpace(_config["DashboardUserPassword"]));

            var options      = new ChromeOptions();
            var dashboardUrl = _config["DashboardUrl"];

            // We have to make sure the website is up
            // On a fresh deployment it can take time before site is deployed
            var client = new HttpClient();
            var result = await client.GetAsync(dashboardUrl);

            int waitCount = 0;

            while ((waitCount++ < 10) && !result.IsSuccessStatusCode)
            {
                Thread.Sleep(TimeSpan.FromSeconds(30));
                result = await client.GetAsync(dashboardUrl);
            }

            Assert.True(result.IsSuccessStatusCode);

            options.AddArgument("--headless");
            options.AddArgument("--disable-gpu");
            options.AddArgument("--incognito");

            // VSTS Hosted agents set the ChromeWebDriver Env, locally that is not the case
            // https://docs.microsoft.com/en-us/azure/devops/pipelines/test/continuous-test-selenium?view=vsts#decide-how-you-will-deploy-and-test-your-app
            if (string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("ChromeWebDriver")))
            {
                Environment.SetEnvironmentVariable("ChromeWebDriver", Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));
            }

            using (var driver = new ChromeDriver(Environment.GetEnvironmentVariable("ChromeWebDriver"), options))
            {
                // TODO: This parameter has been set (too) conservatively to ensure that content
                //       loads on build machines. Investigate if one could be less sensitive to that.
                driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);

                void Advance()
                {
                    while (true)
                    {
                        try
                        {
                            var button = driver.FindElementById("idSIButton9");
                            if (button.Enabled)
                            {
                                button.Click();
                                return;
                            }
                        }
                        catch (StaleElementReferenceException)
                        {
                        }
                    }
                }

                driver.Navigate().GoToUrl(_config["DashboardUrl"]);

                driver.SwitchTo().ActiveElement().SendKeys(_config["DashboardUserUpn"]);
                Advance();

                driver.FindElementByName("passwd").SendKeys(_config["DashboardUserPassword"]);
                Advance();

                // Consent, should only be done if we can find the button
                try
                {
                    var button = driver.FindElementById("idSIButton9");
                    Advance();
                }
                catch (NoSuchElementException)
                {
                    // Nothing to do
                }

                driver.Navigate().GoToUrl($"{dashboardUrl}/Home/AboutMe");

                waitCount = 0;
                while (!driver.Url.StartsWith($"{dashboardUrl}/Home/AboutMe"))
                {
                    Thread.Sleep(TimeSpan.FromMilliseconds(5000));

                    // We may have to consent a second time since we are asking for a new audience
                    try
                    {
                        var button = driver.FindElementById("idSIButton9");
                        Advance();
                    }
                    catch (NoSuchElementException)
                    {
                        // Nothing to do
                    }

                    Assert.InRange(waitCount++, 0, 10);
                }

                var    element    = driver.FindElement(By.Id("tokenfield"));
                string elementval = element.GetAttribute("value");

                var jwtHandler = new JwtSecurityTokenHandler();

                Assert.True(jwtHandler.CanReadToken(elementval));

                var token = jwtHandler.ReadJwtToken(elementval);
                var aud   = token.Claims.Where(c => c.Type == "aud");

                Assert.Single(aud);

                var tokenAudience = aud.First().Value;

                Assert.Equal(_config["FhirServerUrl"], tokenAudience);
            }
        }
Esempio n. 10
0
        static AuthenticationTicket Unprotect(string protectedText)
        {
            Microsoft.IdentityModel.Tokens.SecurityToken validatedToken;
            if (string.IsNullOrWhiteSpace(protectedText))
            {
                throw new ArgumentNullException("protectedText");
            }
            //Fwk.Security.Identity.jwtSecurityProvider sec_provider = null;

            var tokenHandler     = new JwtSecurityTokenHandler();
            var jwtSecurityToken = tokenHandler.ReadJwtToken(protectedText);

            var secretKey          = ConfigurationManager.AppSettings["JWT_SECRET_KEY"];
            var audienceId         = ConfigurationManager.AppSettings["JWT_AUDIENCE_TOKEN"];
            var issuerToken        = ConfigurationManager.AppSettings["JWT_ISSUER_TOKEN"];
            var securityKey        = new SymmetricSecurityKey(System.Text.Encoding.Default.GetBytes(secretKey));
            var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature);

            //string audienceId = sec_provider.audienceId;
            //string symmetricKeyAsBase64 = sec_provider.audienceSecret;
            //var keyByteArray = TextEncodings.Base64Url.Decode(symmetricKeyAsBase64);

            //var securityKey = new SymmetricSecurityKey(keyByteArray);



            //TODO : CustomJwtFormat Esta lista de issuers debe ser flexible
            ///Establezco los issuers validos
            var issuers = new List <string>()
            {
                "pelsoft",
                "issuerA",
                "issuerB",
                "http://localhost:50009"
            };

            var validationParams = new TokenValidationParameters()
            {
                ValidAudience            = audienceId,
                ValidIssuers             = issuers,
                ValidateLifetime         = true,
                ValidateAudience         = true,
                ValidateIssuer           = true,
                RequireSignedTokens      = true,
                RequireExpirationTime    = true,
                ValidateIssuerSigningKey = true,
                ClockSkew = TimeSpan.Zero,
                //IssuerSigningKeys = DefaultX509Key_Public_2048
                IssuerSigningKey = signingCredentials.Key
            };

            try
            {
                var principal = tokenHandler.ValidateToken(protectedText, validationParams, out validatedToken);


                var identity = principal.Identities.First();

                // Fill out the authenticationProperties issued and expires times if the equivalent claims are in the JWT
                var authenticationProperties = new AuthenticationProperties();

                //issued
                if (validatedToken.ValidFrom != DateTime.MinValue)
                {
                    authenticationProperties.IssuedUtc = validatedToken.ValidFrom.ToUniversalTime();
                }
                //expires
                if (validatedToken.ValidTo != DateTime.MinValue)
                {
                    authenticationProperties.ExpiresUtc = validatedToken.ValidTo.ToUniversalTime();
                }

                return(new AuthenticationTicket(identity, authenticationProperties));
            }
            catch (Exception ex)
            {
                //return Task<HttpResponseMessage>.Factory.StartNew(() => new HttpResponseMessage(statusCode) { });
                //throw new UnauthorizedAccessException(ex.Message);
                var ec = new Fwk.Exceptions.FunctionalException((int)HttpStatusCode.Unauthorized, " No autorizado " + ex.Message);
                throw ec;
            }
        }
Esempio n. 11
0
        static void Main(string[] args)
        {
            // Simple create and red of a JWT token

            // This creates the JWT

            var plainTextSecurityKey = "Life is really simple, but we insist on making it complicated."; //Confucius
            var signingKey           = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(plainTextSecurityKey));
            var signingCredentials   = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);

            var securityTokenDescriptor = new SecurityTokenDescriptor()
            {
                Subject = new ClaimsIdentity(new List <Claim>()
                {
                    // These are required for bhhc gateway
                    new Claim(JwtRegisteredClaimNames.Sub, "johndoe"),          // this is the same as ClaimTypes.NameIdentifier
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),

                    // These are optional other values

                    new Claim(ClaimTypes.NameIdentifier, "*****@*****.**"),
                    new Claim(ClaimTypes.Role, "Administrator"),
                    new Claim(ClaimTypes.Role, "SuperUser"),
                    new Claim(ClaimTypes.Name, "John Doe"),
                    new Claim("BHHC.GroupID", "4103")
                }, "Custom"),
                NotBefore          = DateTime.Now,
                SigningCredentials = signingCredentials,
                Issuer             = "self",
                IssuedAt           = DateTime.Now,
                Expires            = DateTime.Now.AddHours(3),
                Audience           = "http://xbhhcwebapp.bhhc.com",
            };

            var tokenHandler          = new JwtSecurityTokenHandler();
            var plainToken            = tokenHandler.CreateToken(securityTokenDescriptor);
            var signedAndEncodedToken = tokenHandler.WriteToken(plainToken);        // The final token to added to cookie or header



            //==========================================================================
            //  This reads the JWT on the other side of the call

            //  Validating the token on the server side
            var validationParameters = new TokenValidationParameters()
            {
                ValidateAudience         = true,
                ValidAudience            = "http://xbhhcwebapp.bhhc.com",
                ValidateIssuer           = true,
                ValidIssuer              = "self",
                ValidateIssuerSigningKey = true,
                IssuerSigningKey         = signingKey,
                RequireExpirationTime    = true,
                ValidateLifetime         = true,
                ClockSkew = TimeSpan.Zero
            };

            try
            {
                SecurityToken outPlainToken = new JwtSecurityToken();
                //var tokenHandler = new JwtSecurityTokenHandler();  // declared above, would be needed if on receiving side of call.
                // validates and creates principal object
                var principal = tokenHandler.ValidateToken(signedAndEncodedToken, validationParameters, out outPlainToken);

                // 1. Read claim under principal with standard type
                var username = principal.Claims.First(c => c.Type == ClaimTypes.Name).Value;

                // 2. Read custom claim value
                int groupId = 0;
                Int32.TryParse(principal.Claims.First(c => c.Type == "BHHC.GroupID").Value, out groupId);

                // 3. Read custom claim value       throws => Message = "Sequence contains no matching element"
                // var wrongClaim = principal.Claims.First(c => c.Type == "NonExistantClaimType").Value;

                // 4. Read from the jwtToken object instead of principal
                var jwtToken = tokenHandler.ReadJwtToken(signedAndEncodedToken);

                // dates are seconds from epoch
                int expirationValue = 0;
                Int32.TryParse(jwtToken.Claims.First(c => c.Type == JwtRegisteredClaimNames.Exp).Value, out expirationValue);
                var epoch          = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
                var expirationDate = epoch.AddSeconds(expirationValue);

                // Read all claims from JWT
                foreach (var claim in principal.Claims)
                {
                    Console.Write(claim.Type + " = ");
                    Console.WriteLine(claim.Value);
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Authentication failed");
                Console.WriteLine(ex);
            }

            Console.ReadLine();
        }
Esempio n. 12
0
        private bool IsAuthorized(string tokenstring)
        {
            // return true;
            try
            {
                JwtSecurityTokenHandler tokenhandler = new JwtSecurityTokenHandler();
                if (tokenhandler.CanReadToken(tokenstring))
                {
                    JwtSecurityToken token   = tokenhandler.ReadJwtToken(tokenstring);
                    JwtPayload       payload = token.Payload;
                    if (payload.Count() > 0 && payload["Username"] != null)
                    {
                        string Username = payload["Username"].ToString();

                        //string role = payload["Role"].ToString();
                        //if (Roles != null)
                        //{
                        //    if (!Roles.Contains(role))
                        //    {
                        //        return false;
                        //    }
                        //}

                        var data = _userServices.GetuserByCustomuserName(Username).data;
                        if (data != null)
                        {
                            //Setting Userid in Session
                            //this.httpContextAccessor.HttpContext.Session.SetString("UserId", data.Id.ToString());


                            var securityKey          = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(System.Text.Encoding.UTF32.GetBytes(Username));
                            var validationParameters = new TokenValidationParameters
                            {
                                ValidateIssuerSigningKey = true,
                                IssuerSigningKey         = securityKey,
                                ValidateAudience         = false,
                                ValidateIssuer           = false,
                                ValidateActor            = false,
                                ValidateLifetime         = true,
                                ValidateTokenReplay      = false,
                                LifetimeValidator        = LifetimeValidator
                            };
                            SecurityToken validatedToken;
                            try
                            {
                                tokenhandler.ValidateToken(tokenstring, validationParameters, out validatedToken);
                            }
                            catch (Exception ex)
                            {
                                return(false);
                            }
                            return(validatedToken != null);
                        }
                        else
                        {
                            return(false);
                        }
                    }
                    else
                    {
                        return(false);
                    }
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
Esempio n. 13
0
        public async Task GivenPatientIdAndSmartAppUrl_WhenLaunchingApp_LaunchSequenceAndSignIn()
        {
            // There is no remote FHIR server. Skip test
            if (string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable($"TestEnvironmentUrl{Constants.TestEnvironmentVariableVersionSuffix}")))
            {
                return;
            }

            var options = new ChromeOptions();

            options.AddArgument("--headless");
            options.AddArgument("--disable-gpu");
            options.AddArgument("--incognito");

            // TODO: We are accepting insecure certs to make it practical to run on build systems. A valid cert should be on the build system.
            options.AcceptInsecureCertificates = true;

            FhirResponse <Patient> response = await _fixture.FhirClient.CreateAsync(Samples.GetDefaultPatient().ToPoco <Patient>());

            Assert.Equal(HttpStatusCode.Created, response.StatusCode);
            Patient patient = response.Resource;

            // VSTS Hosted agents set the ChromeWebDriver Env, locally that is not the case
            // https://docs.microsoft.com/en-us/azure/devops/pipelines/test/continuous-test-selenium?view=vsts#decide-how-you-will-deploy-and-test-your-app
            if (string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("ChromeWebDriver")))
            {
                Environment.SetEnvironmentVariable("ChromeWebDriver", Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));
            }

            using (var driver = new ChromeDriver(Environment.GetEnvironmentVariable("ChromeWebDriver"), options))
            {
                // TODO: This parameter has been set (too) conservatively to ensure that content
                //       loads on build machines. Investigate if one could be less sensitive to that.
                driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(30);

                void Advance()
                {
                    while (true)
                    {
                        try
                        {
                            var button = driver.FindElementById("idSIButton9");
                            if (button.Enabled)
                            {
                                button.Click();
                                return;
                            }
                        }
                        catch (StaleElementReferenceException)
                        {
                        }
                    }
                }

                driver.Navigate().GoToUrl(_fixture.SmartLauncherUrl);

                var patientElement = driver.FindElement(By.Id("patient"));
                patientElement.SendKeys(patient.Id);

                var launchButton = driver.FindElement(By.Id("launchButton"));
                if (launchButton.Enabled)
                {
                    launchButton.Click();
                }

                var testUserName     = TestUsers.AdminUser.UserId;
                var testUserPassword = TestUsers.AdminUser.Password;

                // Launcher opens a new tab, switch to it
                driver.SwitchTo().Window(driver.WindowHandles[1]);

                int waitCount = 0;
                while (!driver.Url.StartsWith($"https://login.microsoftonline.com"))
                {
                    Thread.Sleep(TimeSpan.FromMilliseconds(1000));
                    Assert.InRange(waitCount++, 0, 10);
                }

                driver.FindElementByName("loginfmt").SendKeys(testUserName);
                Advance();

                // We need to add some delay before we start entering the password (to make sure
                // the element is available and we do not miss sending some keys).
                Thread.Sleep(TimeSpan.FromMilliseconds(1000));

                driver.FindElementByName("passwd").SendKeys(testUserPassword);
                Advance();

                // Consent, should only be done if we can find the button
                try
                {
                    // Sleep in case a light box is shown.
                    Thread.Sleep(TimeSpan.FromMilliseconds(1000));
                    var button = driver.FindElementById("idSIButton9");
                    Advance();
                }
                catch (NoSuchElementException)
                {
                    // Nothing to do, we are assuming that we are at the SMART App screen.
                }

                var tokenResponseElement = driver.FindElement(By.Id("tokenresponsefield"));
                var tokenResponseText    = tokenResponseElement.GetAttribute("value");

                // It can take some time for the token to appear, we will wait
                waitCount = 0;
                while (string.IsNullOrWhiteSpace(tokenResponseText))
                {
                    Thread.Sleep(TimeSpan.FromMilliseconds(1000));
                    tokenResponseText = tokenResponseElement.GetAttribute("value");
                    Assert.InRange(waitCount++, 0, 10);
                }

                // Check the token response, should have right audience
                var tokenResponse = JObject.Parse(tokenResponseElement.GetAttribute("value"));
                var jwtHandler    = new JwtSecurityTokenHandler();
                Assert.True(jwtHandler.CanReadToken(tokenResponse["access_token"].ToString()));
                var token = jwtHandler.ReadJwtToken(tokenResponse["access_token"].ToString());
                var aud   = token.Claims.Where(c => c.Type == "aud").ToList();
                Assert.Single(aud);
                var tokenAudience = aud.First().Value;
                Assert.Equal(Environment.GetEnvironmentVariable("TestEnvironmentUrl"), tokenAudience);

                // Check the patient
                var patientResponseElement = driver.FindElement(By.Id("patientfield"));
                var patientResource        = JObject.Parse(patientResponseElement.GetAttribute("value"));
                Assert.Equal(patient.Id, patientResource["id"].ToString());
            }
        }
Esempio n. 14
0
 public JwtSecurityToken Decode(string token)
 {
     return(tokenHandler.ReadJwtToken(token));
 }
Esempio n. 15
0
        public async Task <IActionResult> OnGetCallbackAsync(string returnUrl = null, string remoteError = null)
        {
            if (remoteError != null)
            {
                ErrorMessage = $"Error from external provider: {remoteError}";
                return(RedirectToPage("./Login", new { ReturnUrl = returnUrl }));
            }
            var info = await _signInManager.GetExternalLoginInfoAsync();

            if (info == null)
            {
                ErrorMessage = "Error loading external login information.";
                return(RedirectToPage("./Login", new { ReturnUrl = returnUrl }));
            }

            // Sign in the user with this external login provider if the user already has a login.
            var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent : false, bypassTwoFactor : true);

            if (result.Succeeded)
            {
                _logger.LogInformation("{Name} logged in with {LoginProvider} provider.", info.Principal.Identity.Name, info.LoginProvider);
                var idToken = info.AuthenticationTokens
                              .Select(i => i.Value)
                              .SingleOrDefault();

                var handler = new JwtSecurityTokenHandler();
                var jwt     = handler.ReadJwtToken(idToken);

                var user = await _userManager.FindByNameAsync(jwt.Subject);

                var createResult = await _userManager.AddClaimsAsync(user, new List <Claim>
                {
                    new Claim(JwtRegisteredClaimNames.Sub, jwt.Subject),
                    new Claim(JwtRegisteredClaimNames.GivenName, jwt.Payload[JwtRegisteredClaimNames.GivenName].ToString()),
                    new Claim(JwtRegisteredClaimNames.FamilyName, jwt.Payload[JwtRegisteredClaimNames.FamilyName].ToString()),
                    new Claim("name", jwt.Payload["name"].ToString()),
                    new Claim(LtiClaims.MessageType, jwt.Payload[LtiClaims.MessageType].ToString()),
                    new Claim(LtiClaims.DeploymentId, jwt.Payload[LtiClaims.DeploymentId].ToString()),
                    new Claim(LtiClaims.TargetLinkUri, jwt.Payload[LtiClaims.TargetLinkUri].ToString()),
                    new Claim(LtiClaims.ResourceLink, JsonConvert.SerializeObject(jwt.Payload[LtiClaims.ResourceLink])),
                    new Claim(LtiClaims.Roles, JsonConvert.SerializeObject(jwt.Payload[LtiClaims.Roles])),
                    new Claim(LtiClaims.Context, JsonConvert.SerializeObject(jwt.Payload[LtiClaims.Context])),
                    new Claim(LtiClaims.Lis, JsonConvert.SerializeObject(jwt.Payload[LtiClaims.Lis])),
                    new Claim(LtiClaims.LaunchPresentation, JsonConvert.SerializeObject(jwt.Payload[LtiClaims.LaunchPresentation])),
                    new Claim("http://www.brightspace.com", JsonConvert.SerializeObject(jwt.Payload["http://www.brightspace.com"])),
                    new Claim(LtiClaims.Platform, JsonConvert.SerializeObject(jwt.Payload[LtiClaims.Platform])),
                    new Claim(LtiClaims.Version, JsonConvert.SerializeObject(jwt.Payload[LtiClaims.Version])),
                });

                if (createResult.Succeeded)
                {
                    var properties = new AuthenticationProperties
                    {
                        IsPersistent = true,
                    };
                    properties.StoreTokens(info.AuthenticationTokens);
                    await _signInManager.SignInAsync(user, properties, info.LoginProvider);

                    return(LocalRedirect(returnUrl));
                }

                return(LocalRedirect(returnUrl));
            }
            if (result.IsLockedOut)
            {
                return(RedirectToPage("./Lockout"));
            }
            else
            {
                // If the user does not have an account, then ask the user to create an account.
                ReturnUrl           = returnUrl;
                ProviderDisplayName = info.ProviderDisplayName;

                var idToken = info.AuthenticationTokens
                              .Select(i => i.Value)
                              .SingleOrDefault();
                if (string.IsNullOrEmpty(idToken))
                {
                    return(RedirectToPage("./Lockout"));
                }

                var handler = new JwtSecurityTokenHandler();
                var jwt     = handler.ReadJwtToken(idToken);

                var user = new IdentityUser
                {
                    UserName = jwt.Subject
                };

                user.Email = jwt.Payload[JwtRegisteredClaimNames.Email].ToString();

                var createResult = await _userManager.CreateAsync(user);

                if (createResult.Succeeded)
                {
                    createResult = await _userManager.AddLoginAsync(user, info);

                    if (createResult.Succeeded)
                    {
                        createResult = await _userManager.AddClaimsAsync(user, new List <Claim>
                        {
                            new Claim(JwtRegisteredClaimNames.Sub, jwt.Subject),
                            new Claim(JwtRegisteredClaimNames.GivenName, jwt.Payload[JwtRegisteredClaimNames.GivenName].ToString()),
                            new Claim(JwtRegisteredClaimNames.FamilyName, jwt.Payload[JwtRegisteredClaimNames.FamilyName].ToString()),
                            new Claim("name", jwt.Payload["name"].ToString()),
                            new Claim(LtiClaims.MessageType, jwt.Payload[LtiClaims.MessageType].ToString()),
                            new Claim(LtiClaims.DeploymentId, jwt.Payload[LtiClaims.DeploymentId].ToString()),
                            new Claim(LtiClaims.TargetLinkUri, jwt.Payload[LtiClaims.TargetLinkUri].ToString()),
                            new Claim(LtiClaims.ResourceLink, JsonConvert.SerializeObject(jwt.Payload[LtiClaims.ResourceLink])),
                            new Claim(LtiClaims.Roles, JsonConvert.SerializeObject(jwt.Payload[LtiClaims.Roles])),
                            new Claim(LtiClaims.Context, JsonConvert.SerializeObject(jwt.Payload[LtiClaims.Context])),
                            new Claim(LtiClaims.Lis, JsonConvert.SerializeObject(jwt.Payload[LtiClaims.Lis])),
                            new Claim(LtiClaims.LaunchPresentation, JsonConvert.SerializeObject(jwt.Payload[LtiClaims.LaunchPresentation])),
                            new Claim("http://www.brightspace.com", JsonConvert.SerializeObject(jwt.Payload["http://www.brightspace.com"])),
                            new Claim(LtiClaims.Platform, JsonConvert.SerializeObject(jwt.Payload[LtiClaims.Platform])),
                            new Claim(LtiClaims.Version, JsonConvert.SerializeObject(jwt.Payload[LtiClaims.Version])),
                        });

                        if (createResult.Succeeded)
                        {
                            var properties = new AuthenticationProperties
                            {
                                IsPersistent = false,
                            };
                            properties.StoreTokens(info.AuthenticationTokens);
                            await _signInManager.SignInAsync(user, properties, info.LoginProvider);

                            return(LocalRedirect(returnUrl));
                        }
                    }
                }

                foreach (var error in createResult.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }

                return(Page());
            }
        }
        private List <Claim> ExtractClaims(string token)
        {
            var tokenHandler = new JwtSecurityTokenHandler();

            return(tokenHandler.ReadJwtToken(token).Claims.ToList());
        }
        // IEnumerable<DataFile>
        public IEnumerable <DataFile> GetDataFiles([FromBody] DataFile GetData, [FromQuery] string nameFile = null)
        {
            ResponseErr     res         = new ResponseErr();
            DataFile        data        = new DataFile();
            var             db          = new ConMySQL();
            List <DataFile> list_result = new List <DataFile>();

            try
            {
                Request.Headers.TryGetValue("Authorization", out var token);
                token = ((string)token).Replace("Bearer ", "");
                var handler = new JwtSecurityTokenHandler();
                JwtSecurityToken decodedValue = handler.ReadJwtToken(token);
                List <Claim>     claimsList   = decodedValue.Claims.ToList();
                var id = claimsList.Find(x => x.Type == "unique_name").Value;

                // Console.WriteLine(id);

                Console.WriteLine(GetData.Path);
                // int id = 23;
                // string sql = $"SELECT * FROM DataFile";
                // string sql = string.Format("SELECT * FROM DataFile WHERE Path = '{0}'and IdUser = '******'", datafile.Path, id);
                if (GetData.Path != null && nameFile == null)
                {
                    string sql = string.Format("SELECT * FROM DataFile WHERE Path = '{0}' and Share = '{1}'", GetData.Path, id);
                    Console.WriteLine(sql);
                    DataTable SqlDataSetA = db.getData(sql);
                    foreach (DataRow dr in SqlDataSetA.Rows)
                    {
                        DataFile obj = new DataFile();
                        obj.Id       = Convert.ToInt32(dr["id"]);
                        obj.NameFile = dr["namefile"].ToString();
                        obj.Path     = dr["path"].ToString();
                        obj.Type     = dr["type"].ToString();
                        obj.wwwPath  = dr["wwwpath"].ToString();
                        obj.IdUser   = Convert.ToInt32(dr["iduser"]);
                        list_result.Add(obj);
                    }
                }
                else if (GetData.Path == null && nameFile == null)
                {
                    string sql = string.Format("SELECT * FROM DataFile WHERE Share = '{0}'", id);
                    Console.WriteLine(sql);
                    DataTable SqlDataSet = db.getData(sql);
                    foreach (DataRow dr in SqlDataSet.Rows)
                    {
                        DataFile obj = new DataFile();
                        obj.Id       = Convert.ToInt32(dr["id"]);
                        obj.NameFile = dr["namefile"].ToString();
                        obj.Path     = dr["path"].ToString();
                        obj.Type     = dr["type"].ToString();
                        obj.wwwPath  = dr["wwwpath"].ToString();
                        obj.IdUser   = Convert.ToInt32(dr["iduser"]);
                        list_result.Add(obj);
                    }
                }
                else if (nameFile != null)
                {
                    string sql = string.Format("SELECT * FROM DataFile WHERE Path = '{0}' and Share = '{1}' and NameFile = '{2}'", GetData.Path, id, nameFile);
                    Console.WriteLine(sql);
                    DataTable SqlDataSetA = db.getData(sql);
                    foreach (DataRow dr in SqlDataSetA.Rows)
                    {
                        DataFile obj = new DataFile();
                        obj.Id       = Convert.ToInt32(dr["id"]);
                        obj.NameFile = dr["namefile"].ToString();
                        obj.Path     = dr["path"].ToString();
                        obj.Type     = dr["type"].ToString();
                        obj.wwwPath  = dr["wwwpath"].ToString();
                        obj.IdUser   = Convert.ToInt32(dr["iduser"]);
                        list_result.Add(obj);
                    }
                }
            }
            catch (Exception ex)
            {
                res.msg      = ex.Message;
                res.listdata = list_result;
                Console.WriteLine(ex.Message);
                // return BadRequest();
            }

            // Console.WriteLine(JsonConvert.SerializeObject(list_result, Formatting.Indented));

            return(list_result);
        }
Esempio n. 18
0
        public static async Task <HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequestMessage req,
            TraceWriter log)
        {
            log.Info("C# HTTP trigger function processed a request.");

            if (req.Method == HttpMethod.Get)
            {
                var client = new OAuth2Client(new Uri(ConfigurationManager.AppSettings["OneLoginUrl"]));

                string url = client.CreateAuthorizeUrl(
                    clientId: ConfigurationManager.AppSettings["OneLoginClientId"],
                    redirectUri: ConfigurationManager.AppSettings["RedirectUri"],
                    responseType: "id_token",
                    responseMode: "form_post",
                    scope: "openid",
                    nonce: Guid.NewGuid().ToString());

                log.Info("getting token from " + url);

                var response = req.CreateResponse(HttpStatusCode.Redirect);
                response.Headers.Location = new Uri(url);
                return(response);
            }
            else if (req.Method == HttpMethod.Post)
            {
                log.Info("token posted");

                var data = await req.Content.ReadAsStringAsync();

                log.Info("token " + data);

                var token = data.Substring(9);

                //todo validation
                //var parameters = new TokenValidationParameters
                //{
                //    key
                //};

                var tokenHandler = new JwtSecurityTokenHandler();

                var unvalidatedJwt = tokenHandler.ReadJwtToken(token);

                //SecurityToken validated;
                //tokenHandler.ValidateToken(token, parameters, out validated);

                //log.Info("token issuer" + validated.Issuer);

                //var jwt = validated as JwtSecurityToken;

                //log.Info("jwt " + jwt.Payload);

                var tokenHelper = new TokenHelper();

                var valid = tokenHelper.ValidateToken(token);

                if (valid)
                {
                    var response = req.CreateResponse(HttpStatusCode.Redirect);
                    response.Headers.Location = new Uri(ConfigurationManager.AppSettings["TokenRedirect"] + token);
                    return(response);
                    //return req.CreateResponse(HttpStatusCode.OK, unvalidatedJwt, "application/json");
                }
                else
                {
                    return(req.CreateResponse(HttpStatusCode.Forbidden));
                }
            }

            return(req.CreateResponse(HttpStatusCode.OK, "invalid"));
        }
Esempio n. 19
0
        /// <summary>
        /// Decoda o token
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public Task <JwtSecurityToken> DecodeJwtToken(string accessToken)
        {
            var token = _handler.ReadJwtToken(accessToken);

            return(Task.FromResult(token));
        }
        public static IdentityBuilder AddAuthentication <TUser>(this IServiceCollection services,
                                                                IConfiguration configuration,
                                                                Action <IdentityOptions> setupAction)
            where TUser : class
        {
            // Services used by identity

            var authenticationBuilder = services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = IdentityConstants.ApplicationScheme;
                options.DefaultChallengeScheme    = IdentityConstants.ApplicationScheme;
                options.DefaultSignInScheme       = IdentityConstants.ExternalScheme;
            });
            // doesn't work here either.
            //----------------------------------

            /*
             * services.AddOptions<OpenIdConnectOptions>()
             *         .Configure<IOIDCPipelineStore, IHttpContextAccessor>((options, oidcPipelineStore, accessor) =>
             *         {
             *             options.ProtocolValidator = new MyOpenIdConnectProtocolValidator(oidcPipelineStore, accessor)
             *             {
             *                 RequireTimeStampInNonce = false,
             *                 RequireStateValidation = false,
             *                 RequireNonce = true,
             *                 NonceLifetime = TimeSpan.FromMinutes(15)
             *             };
             *         });
             */
            var section = configuration.GetSection("openIdConnect");
            var openIdConnectSchemeRecordSchemeRecords = new List <OpenIdConnectSchemeRecord>();

            section.Bind(openIdConnectSchemeRecordSchemeRecords);
            foreach (var record in openIdConnectSchemeRecordSchemeRecords)
            {
                var scheme = record.Scheme;
                services.AddOptions <OpenIdConnectOptions>(scheme)
                .Configure <IOIDCPipeLineKey, IOIDCPipelineStore>(
                    (options, oidcPipeLineKey, oidcPipelineStore) =>
                {
                    options.ProtocolValidator = new MyOpenIdConnectProtocolValidator(oidcPipeLineKey, oidcPipelineStore)
                    {
                        RequireTimeStampInNonce = false,
                        RequireStateValidation  = false,
                        RequireNonce            = true,
                        NonceLifetime           = TimeSpan.FromMinutes(15)
                    };
                });


                authenticationBuilder.AddOpenIdConnect(scheme, scheme, options =>
                {
                    options.Authority            = record.Authority;
                    options.CallbackPath         = record.CallbackPath;
                    options.RequireHttpsMetadata = false;
                    if (!string.IsNullOrEmpty(record.ResponseType))
                    {
                        options.ResponseType = record.ResponseType;
                    }
                    options.GetClaimsFromUserInfoEndpoint = record.GetClaimsFromUserInfoEndpoint;
                    options.ClientId     = record.ClientId;
                    options.ClientSecret = record.ClientSecret;
                    options.SaveTokens   = true;
                    options.TokenValidationParameters.ValidateAudience = false;
                    options.Events.OnMessageReceived = async context =>
                    {
                    };
                    options.Events.OnTokenValidated = async context =>
                    {
                        var pipeLineStore = context.HttpContext.RequestServices.GetRequiredService <IOIDCPipelineStore>();

                        OpenIdConnectMessage oidcMessage = null;
                        if (context.Options.ResponseType == "id_token")
                        {
                            oidcMessage = context.ProtocolMessage;
                        }
                        else
                        {
                            oidcMessage = context.TokenEndpointResponse;
                        }

                        var userState = context.ProtocolMessage.Parameters["state"].Split('.')[0];

                        var header  = new JwtHeader();
                        var handler = new JwtSecurityTokenHandler();
                        var idToken = handler.ReadJwtToken(oidcMessage.IdToken);
                        var claims  = idToken.Claims.ToList();

                        var stored = await pipeLineStore.GetOriginalIdTokenRequestAsync(userState);

                        DownstreamAuthorizeResponse idTokenResponse = new DownstreamAuthorizeResponse
                        {
                            Request       = stored,
                            AccessToken   = oidcMessage.AccessToken,
                            ExpiresAt     = oidcMessage.ExpiresIn,
                            IdToken       = oidcMessage.IdToken,
                            RefreshToken  = oidcMessage.RefreshToken,
                            TokenType     = oidcMessage.TokenType,
                            LoginProvider = scheme
                        };
                        await pipeLineStore.StoreDownstreamIdTokenResponseAsync(userState, idTokenResponse);
                    };
                    options.Events.OnRedirectToIdentityProvider = async context =>
                    {
                        var oidcPipelineKey   = context.HttpContext.RequestServices.GetRequiredService <IOIDCPipeLineKey>();
                        string key            = oidcPipelineKey.GetOIDCPipeLineKey();
                        var pipeLineStore     = context.HttpContext.RequestServices.GetRequiredService <IOIDCPipelineStore>();
                        var stored            = await pipeLineStore.GetOriginalIdTokenRequestAsync(key);
                        var clientSecretStore = context.HttpContext.RequestServices.GetRequiredService <IOIDCPipelineClientStore>();

                        if (stored != null)
                        {
                            context.ProtocolMessage.ClientId = stored.ClientId;
                            context.Options.ClientId         = stored.ClientId;
                            context.Options.ClientSecret     = await clientSecretStore.FetchClientSecretAsync(scheme,
                                                                                                              stored.ClientId);
                            context.ProtocolMessage.State = $"{key}.";
                        }

                        context.Options.Authority = context.Options.Authority;
                        if (record.AdditionalProtocolScopes != null && record.AdditionalProtocolScopes.Any())
                        {
                            string additionalScopes = "";
                            foreach (var item in record.AdditionalProtocolScopes)
                            {
                                additionalScopes += $" {item}";
                            }
                            context.ProtocolMessage.Scope += additionalScopes;
                        }
                        if (context.HttpContext.User.Identity.IsAuthenticated)
                        {
                            // assuming a relogin trigger, so we will make the user relogin on the IDP
                            context.ProtocolMessage.Prompt = "login";
                        }
                        var allowedParams = await clientSecretStore.FetchAllowedProtocolParamatersAsync(scheme);

                        foreach (var allowedParam in allowedParams)
                        {
                            var item = stored.Raw[allowedParam];
                            if (item != null)
                            {
                                if (string.Compare(allowedParam, "state", true) == 0)
                                {
                                    context.ProtocolMessage.SetParameter(allowedParam, $"{key}.{item}");
                                }
                                else
                                {
                                    context.ProtocolMessage.SetParameter(allowedParam, item);
                                }
                            }
                        }

                        /*
                         * if (context.ProtocolMessage.RequestType == OpenIdConnectRequestType.Authentication)
                         * {
                         *  context.ProtocolMessage.AcrValues = "v1=google";
                         * }
                         */
                    };
                    options.Events.OnRemoteFailure = context =>
                    {
                        context.Response.Redirect("/");
                        context.HandleResponse();
                        return(Task.CompletedTask);
                    };
                });
            }


            return(new IdentityBuilder(typeof(TUser), services));
        }
Esempio n. 21
0
        public async Task <HttpResponseMessage> GetUxoLogs(string traceId)
        {
            try
            {
                if (string.IsNullOrEmpty(traceId))
                {
                    throw new Exception($"Invalid traceId {traceId}");
                }


                string token         = "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6IkJCOENlRlZxeWFHckdOdWVoSklpTDRkZmp6dyIsImtpZCI6IkJCOENlRlZxeWFHckdOdWVoSklpTDRkZmp6dyJ9.eyJhdWQiOiJkYjY2MmRjMS0wY2ZlLTRlMWMtYTg0My0xOWE2OGU2NWJlNTgiLCJpc3MiOiJodHRwczovL3N0cy53aW5kb3dzLm5ldC83MmY5ODhiZi04NmYxLTQxYWYtOTFhYi0yZDdjZDAxMWRiNDcvIiwiaWF0IjoxNTc0MTg4ODYyLCJuYmYiOjE1NzQxODg4NjIsImV4cCI6MTU3NDE5Mjc2MiwiYWlvIjoiQVZRQXEvOE5BQUFBbmpyTlpDVVFWNEFaeVg0dlk1aHVwKzBHVTRKcUJxSm5qMGNqQnJsVHllejNXWXRRalNQc2hLRHgvU3NWK0hFaGdGV2s0RUdyUCtZQnRqMXpTaEd0VG8zcFpGS0ZOMUVtTWFVNG8veVI0OGs9IiwiYW1yIjpbInB3ZCIsIm1mYSJdLCJmYW1pbHlfbmFtZSI6IlBvZHVyaSIsImdpdmVuX25hbWUiOiJTYWljaGFyYW4iLCJpcGFkZHIiOiIxNjcuMjIwLjI0LjExMSIsIm5hbWUiOiJTYWljaGFyYW4gUG9kdXJpIiwibm9uY2UiOiJiZmUxMWM3Mi0yODZkLTQ5ZjgtOWEwMi02NzMxOTEzNDY3YTIiLCJvaWQiOiI5Mzk5Yzk1YS03YjhlLTQwNzktODM5MS1lYTEyMjM3ZTg2ZDkiLCJvbnByZW1fc2lkIjoiUy0xLTUtMjEtMjEyNzUyMTE4NC0xNjA0MDEyOTIwLTE4ODc5Mjc1MjctMzI4MzczOTgiLCJyaCI6IkkiLCJzdWIiOiJZWVh4d29FWUg4cG9yRVZxTW5rY3ZyUDJBczlCd2R4UEhxb0E5LTR0UTF3IiwidGlkIjoiNzJmOTg4YmYtODZmMS00MWFmLTkxYWItMmQ3Y2QwMTFkYjQ3IiwidW5pcXVlX25hbWUiOiJzYXBvZHVyaUBtaWNyb3NvZnQuY29tIiwidXBuIjoic2Fwb2R1cmlAbWljcm9zb2Z0LmNvbSIsInV0aSI6ImxHbmF2Yjh3ZkVpWEQ4Qk02QkVCQUEiLCJ2ZXIiOiIxLjAifQ.GmgoMwnBYFFe1VnJ3Usqeh9p6GVjHZ1JgyhJWe7fuzMNXsxZE9A7l4tWH_4HQUTRwUrgpBd54e_glDN1QIVw8xRfjLUA8ATHsBG_ctpyTK5RmYIK3E58JKPPJgr7PxS3tSlZhRGWFiNBYo-K9qrQtdTUq2Uky-JEEMZapFBOIBzrW6Ut5xivUmGD8lEligk5Z6tsZm3Vc-pAZiGnNturp0lSgonMJ-ijpY7oMqB2SyMYlkuguBedpFbHY4Og5BIZG-kUKM0nUZomQl3RAqGn09W6DWC8-DISEbicZ761WtWebQ-cCNDyoBFFjFOFX6l-PPTLaY3w-cK_MBdxG8F7qw&state=412d483e-5f55-4674-84f0-d247ddfe663f&session_state=e55787ff-0b9e-4e2d-9969-b943ffa0ee14";
                var    jwtHandler    = new JwtSecurityTokenHandler();
                var    readableToken = jwtHandler.ReadJwtToken(token);
                var    claims        = readableToken.Claims;


                string oid                        = "9399c95a-7b8e-4079-8391-ea12237e86d9";
                string clientId                   = "db662dc1-0cfe-4e1c-a843-19a68e65be58";
                string redirectUrl                = "https://microsoft/kustoclient";
                var    userIdentifier             = new UserIdentifier(oid, UserIdentifierType.UniqueId);
                string authority                  = "https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db47";
                AuthenticationContext authContext = new AuthenticationContext(authority);
                AuthenticationResult  authResult  = await authContext.AcquireTokenAsync(DatabaseConstants.Uxo_Connection, clientId, new Uri(redirectUrl), new PlatformParameters(PromptBehavior.Never), userIdentifier);

                Console.WriteLine(authResult.AccessToken);


                var kustoConnectionStringBuilder = new KustoConnectionStringBuilder(DatabaseConstants.Uxo_Connection)
                {
                    FederatedSecurity = true,
                    InitialCatalog    = "NetDefaultDB",
                    Authority         = authority,
                    UserToken         = authResult.AccessToken
                };

                var queryProvider = KustoClientFactory.CreateCslQueryProvider(kustoConnectionStringBuilder);

                var UxoRequestResult = await DatabaseQueryRunner.RunQuery(DatabaseConstants.Uxo_Connection, DatabaseConstants.Uxo_Database, GetQuery("UxoRequest", traceId), queryProvider);

                var UxoConnectionResult = await DatabaseQueryRunner.RunQuery(DatabaseConstants.Uxo_Connection, DatabaseConstants.Uxo_Database, GetQuery("UxoConnection", traceId), queryProvider);

                var UxoTraceResult = await DatabaseQueryRunner.RunQuery(DatabaseConstants.Uxo_Connection, DatabaseConstants.Uxo_Database, GetQuery("UxoTrace", traceId), queryProvider);

                var UxoWebSocketMessageResult = await DatabaseQueryRunner.RunQuery(DatabaseConstants.Uxo_Connection, DatabaseConstants.Uxo_Database, GetQuery("UxoWebSocketMessage", traceId), queryProvider);

                var UxoEventResult = await DatabaseQueryRunner.RunQuery(DatabaseConstants.Uxo_Connection, DatabaseConstants.Uxo_Database, GetQuery("UxoEvent", traceId), queryProvider);

                var result1 = new List <DatabaseResult>()
                {
                    UxoRequestResult, UxoConnectionResult, UxoTraceResult, UxoWebSocketMessageResult, UxoEventResult
                };
                return(new HttpResponseMessage()
                {
                    Content = new StringContent(JsonConvert.SerializeObject(result1))
                });
            }
            catch (Exception e)
            {
                Console.Write(e);
                return(new HttpResponseMessage()
                {
                    Content = new StringContent(e.Message),
                    StatusCode = System.Net.HttpStatusCode.InternalServerError
                });
            }
        }
Esempio n. 22
0
        //get the id from the token
        public int GetIdFromToken(string token)
        {
            var tokenBody = _handler.ReadJwtToken(token);

            return(int.Parse((tokenBody.Claims.Where(c => c.Type == ClaimTypes.NameIdentifier)).First().Value));
        }
Esempio n. 23
0
        private JwtSecurityToken ParseAccessToken(string tokenString)
        {
            var token = _tokenHandler.ReadJwtToken(tokenString);

            return(token);
        }
        public async Task <SkillResponse> FunctionHandler(SkillRequest input, ILambdaContext context)
        {
            ILambdaLogger log = context.Logger;

            log.LogLine($"Skill Request Object:" + JsonConvert.SerializeObject(input));
            //APLSupport.Add();

            var accessToken = input.Context.System.User.AccessToken;

            var handler = new JwtSecurityTokenHandler();
            var token   = handler.ReadJwtToken(accessToken);

            var name = token.Payload["firstname"].ToString();

            string  user_name = "";
            Session session   = input.Session;

            try
            {
                if (session.Attributes == null)
                {
                    session.Attributes = new Dictionary <string, object>();
                }

                Type requestType = input.GetRequestType();
                if (input.GetRequestType() == typeof(LaunchRequest))
                {
                    //    var sentences = "Smooth as an android's bottom, eh, Data? About four years." +
                    //"I got tired of hearing how young I looked. " +
                    //"Captain, why are we out here chasing comets? " +
                    //"Fate protects fools, little children and ships named Enterprise."+
                    //"I got tired of hearing how young I looked. " +
                    //"Captain, why are we out here chasing comets? " +
                    //"Fate protects fools, little children and ships named Enterprise."+
                    //"I got tired of hearing how young I looked. " +
                    //"Captain, why are we out here chasing comets? " +
                    //"Fate protects fools, little children and ships named Enterprise."+
                    //"I got tired of hearing how young I looked. " +
                    //"Captain, why are we out here chasing comets? " +
                    //"Fate protects fools, little children and ships named Enterprise.";
                    //var speech = new Speech(new PlainText(sentences));
                    //var mainLayout = new Layout(
                    //    new Container(
                    //        new Image
                    //        {
                    //            Width = "100vw",
                    //            Height = "100vh",
                    //            Position = new APLValue<string>("absolute"),
                    //            Scale = new APLValue<Scale?>(Scale.BestFill),
                    //            Source = new APLValue<string>(bgUrl)
                    //        },


                    //        new ScrollView(
                    //            new Text(sentences)
                    //            {
                    //                PaddingLeft = 40,
                    //                PaddingRight = 40,
                    //                PaddingBottom = 40,
                    //                FontSize = "40dp",
                    //                TextAlign = "Center",
                    //                Id = "talker",
                    //                Content = APLValue.To<string>("${payload.script.properties.text}"),
                    //                Speech = APLValue.To<string>("${payload.script.properties.speech}")
                    //            }
                    //        )
                    //        { Width = "100vw", Height = "100vh" }
                    //    )
                    //);
                    //mainLayout.Parameters = new List<Parameter>();
                    //mainLayout.Parameters.Add(new Parameter("payload"));

                    //var response = ResponseBuilder.Empty();
                    //response.Response.ShouldEndSession = false;

                    //var directive = new RenderDocumentDirective
                    //{
                    //    Token = "randomToken",
                    //    Document = new APLDocument
                    //    {
                    //        MainTemplate = mainLayout
                    //    },
                    //    DataSources = new Dictionary<string, APLDataSource>
                    //    {
                    //        {
                    //            "script",new ObjectDataSource
                    //            {
                    //                Properties = new Dictionary<string, object>
                    //                {
                    //                    { "ssml", speech.ToXml()}
                    //                },
                    //                Transformers = new List<APLTransformer>{
                    //                    APLTransformer.SsmlToText(
                    //                        "ssml",
                    //                        "text"),
                    //                    APLTransformer.SsmlToSpeech(
                    //                        "ssml",
                    //                        "speech")
                    //                }
                    //            }
                    //        }
                    //    }
                    //};


                    //response.Response.Directives.Add(directive);
                    //var speakItem = new SpeakItem
                    //{
                    //    ComponentId = "talker",
                    //    HighlightMode = new APLValue<HighlightMode?>(HighlightMode.Line)
                    //};
                    //response.Response.Directives.Add(new ExecuteCommandsDirective("randomToken", speakItem));
                    //return response;



                    session.Attributes["user_name"] = name;
                    var xml = await new Ssml().Say("Take a \n deep breath")
                              .Say("<audio src =\"soundbank://soundlibrary/transportation/amzn_sfx_car_accelerate_01\" />")
                              .Say("then continue.").ForAlexa()
                              .ToStringAsync();
                    var d = new SsmlOutputSpeech
                    {
                        Ssml = $"<speak>Welcome to Ride Hailer<audio src =\"https://bestilldemo.azurewebsites.net/images/audio10.mp3\" />You can order a ride,or request a fare estimate.Which will it be ?</speak>"
                    };
                    string   next = $"Welcome {name}, \n You can ask me about any country";
                    Reprompt rp   = new Reprompt(next);



                    var rt = input.Context.System.Device.IsInterfaceSupported("Display");
                    if (rt)
                    {
                        //var shape = input.Context.Viewport?.Shape;
                        //var response = ResponseBuilder.AskWithCard(next, "Welcome", next, rp);


                        //session.Attributes.Add("LastIntent", input.Request.Intent.Name);
                        //PlainTextOutputSpeech speech = new PlainTextOutputSpeech(msg);
                        //var response = ResponseBuilder.Ask(next, new Reprompt(""), session);

                        //var response = ResponseBuilder.Empty();
                        //response.Response.ShouldEndSession = false;

                        var response = ResponseBuilder.Ask(next, rp, session);
                        //var dr = new Template().BuildAPLDirective(next, null,"Sylvester Assistant", "Welcome");
                        var dr = new Template().BuildScrollingSequenceWithVoiceDirective(next, null, "Sylvester Assistant", "Welcome");

                        //var dr = new Template().BuildItemListDirective(next, null, "Sylvester Assistant", "Welcome");
                        //var dr = new Template().BuildDataListDirective(next, null,"Sylvester Assistant", "Welcome");
                        //var dr = BuildAPLDirective(next);
                        response.Response.Directives.Add(dr);
                        //var speakItem = new SpeakList
                        //{
                        //    ComponentId = "mySequence",
                        //    Start = new APLValue<int>(0),
                        //    Count = new APLValue<int>(next.Split(",").Length),
                        //    MinimumDwellTime = new APLValue<int?>(1000),
                        //    Align = new APLValue<ItemAlignment?>(ItemAlignment.Center)
                        //};
                        //response.Response.Directives.Add(new ExecuteCommandsDirective("randomToken", speakItem));
                        return(response);
                    }
                    else
                    {
                        return(ResponseBuilder.Ask(next, rp, session));
                    }
                }
                else if (input.GetRequestType() == typeof(SessionEndedRequest))
                {
                    user_name = (string)session.Attributes["user_name"];
                    var speech   = $"Goodbye {user_name} and thanks for playing!";
                    var response = ResponseBuilder.Tell(speech);
                    var dr       = new Template().BuildAPLDirective(speech, null, "Sylvester Assistant", "Welcome");
                    response.Response.Directives.Add(dr);
                    return(response);
                }
                else if (input.GetRequestType() == typeof(IntentRequest))
                {
                    var intentRequest = (IntentRequest)input.Request;
                    switch (intentRequest.Intent.Name)
                    {
                    case "AMAZON.CancelIntent":
                    case "AMAZON.StopIntent":
                        user_name = (string)session.Attributes["user_name"];
                        return(ResponseBuilder.Tell($"Goodbye {user_name} and thanks for playing!"));

                    case "AMAZON.HelpIntent":
                    {
                        Reprompt rp = new Reprompt("What's next?");
                        return(ResponseBuilder.Ask("Here's some help. What's next?", rp, session));
                    }

                    case "AudioPlayer.PlaybackNearlyFinished":
                    {
                        Reprompt rp = new Reprompt("What's next?");
                        return(ResponseBuilder.Ask("Here's some help. What's next?", rp, session));
                    }

                    case "MusicIntent":
                    {
                        var query  = intentRequest.Intent.Slots["searchQuery"].Value;
                        var result = await _client.SearchDeezer(query, context);

                        if (result == null)
                        {
                            string   msg = $"Could not get the music you are looking for. Please ask again.";
                            Reprompt er  = new Reprompt(msg);
                            return(ResponseBuilder.Ask(msg, er, session));
                        }
                        var response = ResponseBuilder.Empty();

                        var playlist = AddPlayListDirective(result);
                        session.Attributes["playlist"] = JsonConvert.SerializeObject(playlist);
                        session.Attributes["playlist_current_index"] = 0;
                        response.Response.Directives.Add(playlist[0]);
                        return(response);
                    }

                    case "AMAZON.YesIntent":
                    {
                        var lastIntent = (string)session.Attributes["last_intent"];
                        switch (lastIntent)
                        {
                        case "CountryIntent":
                        {
                            var country = (string)session.Attributes["country"];
                            var anthem  = await _client.SearchDeezer($"{country} national anthem", context);

                            if (anthem == null)
                            {
                                string   msg = $"Something went wrong. Please ask again.";
                                Reprompt er  = new Reprompt(msg);
                                return(ResponseBuilder.Ask(msg, er, session));
                            }

                            //var progressiveResponse = new ProgressiveResponse(input);
                            //progressiveResponse.SendSpeech("With Pleasure! just hold on a second");


                            //string audioUrl = anthem.data[0].preview;
                            //string audioToken = anthem.data[0].title_short;

                            //var response = ResponseBuilder.AudioPlayerPlay(PlayBehavior.ReplaceAll, audioUrl, audioToken);
                            //var dr = BuildAudioAPLDirective(anthem.data[0].album.cover_xl);
                            var response = ResponseBuilder.Empty();
                            response.Response.Directives.Add(AddAudioDirective(anthem));
                            return(response);
                        }

                        default:
                        {
                            string   msg = $"You are trying to trick me. I know i didn't ask you anything";
                            Reprompt er  = new Reprompt(msg);
                            return(ResponseBuilder.Ask(msg, er, session));
                        }
                        }
                    }

                    case "AMAZON.NoIntent":
                    {
                        var    rnd = new Random();
                        var    i   = rnd.Next(0, 2);
                        string msg = "";
                        if (i == 0)
                        {
                            msg = "Remember you can still play a guessing game with me by saying New Game";
                        }
                        else
                        {
                            msg = "You can ask me about any country by saying Tell me about the contry. example Tell me about Nigeria";
                        }

                        Reprompt er       = new Reprompt(msg);
                        var      response = ResponseBuilder.Ask(msg, er, session);
                        var      dr       = new Template().BuildAPLDirective(msg, null, "Sylvester Assistant", "Welcome");
                        response.Response.Directives.Add(dr);
                        return(response);
                    }

                    case "NewGameIntent":
                    {
                        //session.Attributes["num_guesses"] = 0;
                        //session.Attributes["last_intent"] = "NewGameIntent";
                        //Random rnd = new Random();
                        //Int32 magicNumber = rnd.Next(1, 10);
                        //session.Attributes["magic_number"] = magicNumber;

                        //string next = "Guess a number betwen 1 and 10";
                        //Reprompt rp = new Reprompt(next);
                        //var response = ResponseBuilder.Ask(next, rp, session);
                        //var dr = BuildAPLDirective(next);
                        //response.Response.Directives.Add(dr);
                        //return response;

                        var resp     = ResponseBuilder.Empty();
                        var audioUrl = "https://djejflde2khrv.cloudfront.net/broadcasts/desktop/win20200706.mp3";

                        var audioPlayer = new AudioPlayerPlayDirective()
                        {
                            PlayBehavior = PlayBehavior.Enqueue,
                            AudioItem    = new AudioItem()
                            {
                                Stream = new AudioItemStream()
                                {
                                    Url   = audioUrl,
                                    Token = "Today's Devotional"
                                },
                                Metadata = new AudioItemMetadata
                                {
                                    Title    = "Today's Devotional",
                                    Subtitle = "hello",
                                    Art      = new AudioItemSources
                                    {
                                        Sources = new List <AudioItemSource>
                                        {
                                            new AudioItemSource
                                            {
                                                Url = "https://i.ibb.co/5cWztFH/brown-on-seashore-near-mountain-1007657.jpg"
                                            }
                                        }
                                    },
                                    BackgroundImage = new AudioItemSources
                                    {
                                        Sources = new List <AudioItemSource>
                                        {
                                            new AudioItemSource
                                            {
                                                Url = "https://i.ibb.co/5cWztFH/brown-on-seashore-near-mountain-1007657.jpg"
                                            }
                                        }
                                    },
                                },
                            }
                        };


                        resp.Response.Directives.Add(audioPlayer);
                        return(resp);
                    }

                    case "NewRespIntent":
                    {
                        // check answer
                        session.Attributes["last_intent"] = "NewRespIntent";
                        string userString = intentRequest.Intent.Slots["Value"].Value;
                        Int32  userInt    = 0;
                        Int32.TryParse(userString, out userInt);
                        bool   correct  = (userInt == (Int32)(long)session.Attributes["magic_number"]);
                        Int32  numTries = (Int32)(long)session.Attributes["num_guesses"] + 1;
                        string speech   = "";
                        if (correct)
                        {
                            speech = "Correct! You guessed it in " + numTries.ToString() + " tries. Say new game to play again, or stop to exit. ";
                            session.Attributes["num_guesses"] = 0;
                        }
                        else
                        {
                            speech = "Nope, guess again.";
                            session.Attributes["num_guesses"] = numTries;
                        }
                        Reprompt rp       = new Reprompt("speech");
                        var      response = ResponseBuilder.Ask(speech, rp, session);
                        var      dr       = new Template().BuildAPLDirective(speech, null, "Sylvester Assistant", "Welcome");
                        response.Response.Directives.Add(dr);
                        return(response);
                    }

                    case "CountryIntent":
                    {
                        session.Attributes["last_intent"] = "CountryIntent";
                        string countryString = intentRequest.Intent.Slots["Country"].Value;

                        if (string.IsNullOrEmpty(countryString))
                        {
                            var      msg      = "I'm sorry, but I didn't understand the country you were asking for. Please ask again.";
                            Reprompt er       = new Reprompt(msg);
                            var      response = ResponseBuilder.Ask(msg, er, session);
                            var      dr       = new Template().BuildAPLDirective(msg, null, "Sylvester Assistant", "Welcome");
                            response.Response.Directives.Add(dr);
                            return(response);
                        }

                        var countryInfo = await _client.GetCountryInfo(countryString, context);

                        if (countryInfo == null)
                        {
                            string   msg      = $"I cannot recorganize {countryString} as a country. Please ask again.";
                            Reprompt er       = new Reprompt(msg);
                            var      response = ResponseBuilder.Ask(msg, er, session);
                            var      dr       = new Template().BuildAPLDirective(msg, null, "Sylvester Assistant", "Welcome");
                            response.Response.Directives.Add(dr);
                            return(response);
                        }
                        session.Attributes["country"] = countryInfo.demonym;
                        string   next = $"{countryInfo.name} is in {countryInfo.subregion}. The capital is {countryInfo.capital} and the population is {countryInfo.population}. {countryInfo.demonym} native language is {countryInfo.languages[0].name} and their currency is called {countryInfo.currencies[0].name}. Would you like me to play {countryInfo.demonym} national anthem?";
                        Reprompt rp   = new Reprompt(next);
                        var      resp = ResponseBuilder.Ask(next, rp, session);
                        var      dre  = new Template().BuildAPLDirective(next, null, "Sylvester Assistant", "Welcome");
                        resp.Response.Directives.Add(dre);
                        return(resp);
                    }

                    case "QuietTimeIntent":
                    {
                        string   msg      = "Okay thanks";
                        Reprompt er       = new Reprompt(msg);
                        var      response = ResponseBuilder.Ask(msg, er, session);
                        var      dr       = new Template().BuildAPLDirective(msg, null, "Sylvester Assistant", "Welcome");
                        response.Response.Directives.Add(dr);
                        return(response);
                    }

                    case "AMAZON.FallbackIntent":
                    {
                        string   msg      = "Sylvester Assistant does not support that. You can ask me about any country. example, Tell me about Nigeria";
                        Reprompt er       = new Reprompt(msg);
                        var      response = ResponseBuilder.Ask(msg, er, session);
                        var      dr       = new Template().BuildAPLDirective(msg, null, "Sylvester Assistant", "Welcome");
                        response.Response.Directives.Add(dr);
                        return(response);
                    }

                    default:
                    {
                        log.LogLine($"Unknown intent: " + intentRequest.Intent.Name);
                        string   speech   = "I didn't understand - try again?";
                        Reprompt rp       = new Reprompt(speech);
                        var      response = ResponseBuilder.Ask(speech, rp, session);
                        var      dr       = new Template().BuildAPLDirective(speech, null, "Sylvester Assistant", "Welcome");
                        response.Response.Directives.Add(dr);
                        return(response);
                    }
                    }
                }
                else if (input.GetRequestType() == typeof(AudioPlayerRequest))
                {
                    var audioRequest = (AudioPlayerRequest)input.Request;
                    switch (audioRequest.AudioRequestType)
                    {
                    case AudioRequestType.PlaybackNearlyFinished:
                    {
                        var response = ResponseBuilder.Empty();

                        var jsonStr  = (string)session.Attributes["playlist"];
                        var playlist = JsonConvert.DeserializeObject <List <AudioPlayerPlayDirective> >(jsonStr);
                        var index    = (int)session.Attributes["playlist_current_index"];

                        if (playlist.Count == index)
                        {
                            return(response);
                        }
                        response.Response.Directives.Add(playlist[index + 1]);
                        session.Attributes["playlist_current_index"] = index + 1;
                        return(response);
                    }

                    default:
                    {
                        string   speech   = "Something went wrong! Please try again!";
                        Reprompt rp       = new Reprompt(speech);
                        var      response = ResponseBuilder.Ask(speech, rp, session);
                        var      dr       = BuildAPLDirective(speech);
                        response.Response.Directives.Add(dr);
                        return(response);
                    }
                    }
                }
                user_name = (string)session.Attributes["user_name"];
                return(ResponseBuilder.Tell($"Goodbye {user_name} and thanks for playing!"));
            }
            catch (Exception ex)
            {
                string   msg      = "Something went wrong. Please ask again";
                Reprompt er       = new Reprompt(msg);
                var      response = ResponseBuilder.Ask(msg, er, session);
                var      dr       = new Template().BuildAPLDirective(msg, null, "Sylvester Assistant", "Welcome");
                response.Response.Directives.Add(dr);
                return(response);
            }
        }
Esempio n. 25
0
        public async Task <IActionResult> CreateTicket(TicketCreationInput info)
        {
            var sys = await _dbHandler.GetSystemAsync(info.System);

            if (sys == null)
            {
                return(BadRequest(new GeneralMessage()
                {
                    Message = "Invalid system name"
                }));
            }

            var cat = await _dbHandler.GetCategoryAsync(info.CategoryName, sys);

            if (cat == null)
            {
                return(BadRequest(new GeneralMessage()
                {
                    Message = "Invalid category"
                }));
            }

            TicketCreationTemplate template = new TicketCreationTemplate();

            template.Category  = cat;
            template.Details   = info.Details;
            template.Reference = info.Reference;
            template.Summary   = info.Summary;
            template.Title     = info.Title;

            if (info.Details == null)
            {
                template.Details = info.Summary;
            }

            // Get user who wants remove user
            var re          = Request;
            var headers     = re.Headers;
            var tokenString = headers["Authorization"];

            var handler = new JwtSecurityTokenHandler();
            var token   = handler.ReadJwtToken(tokenString[0].Split(' ')[1]);

            var claims        = token.Claims;
            var usernameClaim = claims.Where(x => x.Type == ClaimTypes.Name).FirstOrDefault();
            var user          = await _dbHandler.GetUserAsync(usernameClaim.Value);

            template.CreatorUser = user;

            var respond = await _dbHandler.CreateTicketAsync(template);

            if (respond.MessageType == MessageType.NOK)
            {
                return(BadRequest(new GeneralMessage()
                {
                    Message = respond.MessageText
                }));
            }
            return(Ok(new GeneralMessage()
            {
                Message = respond.MessageText
            }));
        }
        /// <summary>
        /// Validates the specified identity token.
        /// </summary>
        /// <param name="identityToken">The identity token.</param>
        /// <returns>The validation result</returns>
        public async Task <AccessTokenValidationResult> ValidateAsync(string accessToken, bool forceIntrospection = false, string introspectionScope = null, string introspectionSecret = null)
        {
            _logger.LogTrace("Validate Access Token");
            if (forceIntrospection || _options.Policy.ForceIntrospectionForAccessToken)
            {
                if (string.IsNullOrEmpty(introspectionScope))
                {
                    throw new ArgumentNullException("introspectionScope");
                }
                if (string.IsNullOrEmpty(introspectionSecret))
                {
                    throw new ArgumentNullException("introspectionSecret");
                }
            }

            var handler = new JwtSecurityTokenHandler();

            handler.InboundClaimTypeMap.Clear();

            // setup general validation parameters
            var parameters = new TokenValidationParameters
            {
                ValidIssuer   = _options.ProviderInformation.IssuerName,
                ValidAudience = string.Format("{0}/resources", _options.Authority)
            };

            // read the token signing algorithm
            JwtSecurityToken jwt;

            try
            {
                jwt = handler.ReadJwtToken(accessToken);
            }
            catch
            {
                jwt = null;
                //Ignore - this could be a refrence token.
            }

            ClaimsPrincipal claims;

            if (jwt == null || _options.Policy.ForceIntrospectionForAccessToken || forceIntrospection) //Either not valid or not jwt... Check introspection.
            {
                _logger.LogTrace("Preforming online validation of access token.");
                var client      = new IntrospectionClient(string.Format("{0}/connect/introspect", _options.Authority));
                var introResult = await client.SendAsync(new IntrospectionRequest()
                {
                    ClientId      = introspectionScope,
                    ClientSecret  = introspectionSecret,
                    Token         = accessToken,
                    TokenTypeHint = OidcConstants.TokenTypes.AccessToken
                }).ConfigureAwait(false);

                if (introResult.IsError)
                {
                    if (introResult.HttpStatusCode == System.Net.HttpStatusCode.Unauthorized)
                    {
                        _logger.LogError("Introspection reported an error {0}, scope or secret is not correct.", introResult.Error);
                        return(new AccessTokenValidationResult()
                        {
                            Error = "The scope and secret to introspect is incorrect."
                        });
                    }
                    _logger.LogError("Introspection reported an error {0}", introResult.Error);
                    return(new AccessTokenValidationResult()
                    {
                        Error = "Access token or supplied scope binding is invalid."
                    });
                }
                if (!introResult.IsActive)
                {
                    _logger.LogError("Introspection reported the token for the scope {0}, is not valid.", introspectionScope);
                    return(new AccessTokenValidationResult()
                    {
                        Error = "Invalid token or scope."
                    });
                }



                var claimsId = new ClaimsIdentity(introResult.Claims, "introspection");
                claims = new ClaimsPrincipal(claimsId);

                //double check that we actually have the scope requested.
                if (!claims.Claims.Any(x => x.Type == "scope" && x.Value == introspectionScope))
                {
                    return(new AccessTokenValidationResult
                    {
                        Error = $"Access token is not authorized for scope {introspectionScope}"
                    });
                }


                //Should we go ahead and validate the JWT and then use that as the principal (if we are wanting all of the original claims)? Preformance impacts of two validations may not be nice.

                return(new AccessTokenValidationResult()
                {
                    AccessTokenPrincipal = claims,
                    ValidatedByIntrospection = true
                });
            }
            else
            {
                //Valid jwt format - verify it.
                _logger.LogTrace("Preforming offline validation of access token.");
                var algorithm = jwt.Header.Alg;

                // if token is unsigned, and this is allowed, skip signature validation
                if (string.Equals(algorithm, "none"))
                {
                    if (_options.Policy.RequireAccessTokenSignature)
                    {
                        return(new AccessTokenValidationResult
                        {
                            Error = $"Identity token is not singed. Signatures are required by policy"
                        });
                    }
                    else
                    {
                        _logger.LogInformation("Identity token is not signed. This is allowed by configuration.");
                        parameters.RequireSignedTokens = false;
                    }
                }
                else
                {
                    // check if signature algorithm is allowed by policy
                    if (!_options.Policy.ValidSignatureAlgorithms.Contains(algorithm))
                    {
                        return(new AccessTokenValidationResult
                        {
                            Error = $"Identity token uses invalid algorithm: {algorithm}"
                        });
                    }
                    ;
                }


                try
                {
                    claims = ValidateSignature(accessToken, handler, parameters);
                }
                catch (SecurityTokenSignatureKeyNotFoundException sigEx)
                {
                    if (_options.RefreshDiscoveryOnSignatureFailure)
                    {
                        _logger.LogWarning("Key for validating token signature cannot be found. Refreshing keyset.");

                        // try to refresh the key set and try again
                        await _refreshKeysAsync().ConfigureAwait(false);

                        try
                        {
                            claims = ValidateSignature(accessToken, handler, parameters);
                        }
                        catch (Exception ex)
                        {
                            return(new AccessTokenValidationResult
                            {
                                Error = $"Error validating access token: {ex.ToString()}"
                            });
                        }
                    }
                    else
                    {
                        return(new AccessTokenValidationResult
                        {
                            Error = $"Error validating access token: {sigEx.ToString()}"
                        });
                    }
                }
                catch (Exception ex)
                {
                    return(new AccessTokenValidationResult
                    {
                        Error = $"Error validating access token: {ex.ToString()}"
                    });
                }

                //Check if we have the scope specified - if applicable.
                if (!string.IsNullOrEmpty(introspectionScope))
                {
                    if (!claims.Claims.Any(x => x.Type == "scope" && x.Value == introspectionScope))
                    {
                        return(new AccessTokenValidationResult
                        {
                            Error = $"Access token is not authorized for scope {introspectionScope}"
                        });
                    }
                }

                return(new AccessTokenValidationResult()
                {
                    AccessTokenPrincipal = claims,
                    AccessTokenSignatureAlgorithm = algorithm,
                    ValidatedByIntrospection = false
                });
            }
        }
Esempio n. 27
0
        public static void AddAuthentication_JWTSetup(this IServiceCollection services)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }

            //读取配置文件
            var symmetricKeyAsBase64 = AppSecretConfig.Audience_Secret_String;
            var keyByteArray         = Encoding.ASCII.GetBytes(symmetricKeyAsBase64);
            var signingKey           = new SymmetricSecurityKey(keyByteArray);
            var Issuer   = Appsettings.App(new string[] { "Audience", "Issuer" });
            var Audience = Appsettings.App(new string[] { "Audience", "Audience" });

            var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);

            // 令牌验证参数
            var tokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,  //是否验证SecurityKey
                IssuerSigningKey         = signingKey,
                ValidateIssuer           = true,  //是否验证Issuer
                ValidIssuer           = Issuer,   //发行人
                ValidateAudience      = true,     //是否验证Audience
                ValidAudience         = Audience, //订阅人
                ValidateLifetime      = true,     //是否验证失效时间
                ClockSkew             = TimeSpan.FromSeconds(30),
                RequireExpirationTime = true,
            };

            // 开启Bearer认证
            services.AddAuthentication(o =>
            {
                o.DefaultScheme          = JwtBearerDefaults.AuthenticationScheme;
                o.DefaultChallengeScheme = nameof(ApiResponseHandler);
                o.DefaultForbidScheme    = nameof(ApiResponseHandler);
            })
            // 添加JwtBearer服务
            .AddJwtBearer(o =>
            {
                o.TokenValidationParameters = tokenValidationParameters;
                o.Events = new JwtBearerEvents
                {
                    OnChallenge = context =>
                    {
                        context.Response.Headers.Add("Token-Error", context.ErrorDescription);
                        return(Task.CompletedTask);
                    },
                    OnAuthenticationFailed = context =>
                    {
                        var jwtHandler = new JwtSecurityTokenHandler();
                        var token      = context.Request.Headers["Authorization"].ToString().Replace("Bearer ", "");

                        if (!token.IsNullOrEmpty() && jwtHandler.CanReadToken(token))
                        {
                            var jwtToken = jwtHandler.ReadJwtToken(token);

                            if (jwtToken.Issuer != Issuer)
                            {
                                context.Response.Headers.Add("Token-Error-Iss", "issuer is wrong!");
                            }

                            if (jwtToken.Audiences.FirstOrDefault() != Audience)
                            {
                                context.Response.Headers.Add("Token-Error-Aud", "Audience is wrong!");
                            }
                        }

                        // 如果过期,则把<是否过期>添加到,返回头信息中
                        if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
                        {
                            context.Response.Headers.Add("Token-Expired", "true");
                        }
                        return(Task.CompletedTask);
                    }
                };
            })
            .AddScheme <AuthenticationSchemeOptions, ApiResponseHandler>(nameof(ApiResponseHandler), o => { });
        }
Esempio n. 28
0
        /// <summary>
        /// Build and send the deep linking response.
        /// </summary>
        /// <returns></returns>
        public async Task <IActionResult> OnPostAssignActivities()
        {
            var handler = new JwtSecurityTokenHandler();

            Token      = handler.ReadJwtToken(IdToken);
            LtiRequest = new LtiDeepLinkingRequest(Token.Payload);

            var response = new LtiDeepLinkingResponse
            {
                Data         = LtiRequest.DeepLinkingSettings.Data,
                DeploymentId = LtiRequest.DeploymentId
            };

            var contentItems     = new List <ContentItem>();
            var customParameters = LtiRequest.Custom;

            foreach (var activity in Activities)
            {
                if (activity.Selected)
                {
                    var contentItem = new LtiLinkItem
                    {
                        Title  = activity.Title,
                        Text   = activity.Description,
                        Url    = Url.Page("./Tool", null, null, Request.Scheme),
                        Custom = new Dictionary <string, string>
                        {
                            { "activity_id", activity.Id.ToString() }
                        }
                    };

                    if (customParameters != null)
                    {
                        foreach (var keyValue in LtiRequest.Custom)
                        {
                            contentItem.Custom.TryAdd(keyValue.Key, keyValue.Value);
                        }
                    }

                    if (activity.IsVideo)
                    {
                        contentItem.Custom.TryAdd("videoId", activity.Id.ToString());
                    }

                    contentItems.Add(contentItem);
                }
            }

            response.ContentItems = contentItems.ToArray();
            response.AddClaim(new Claim(JwtRegisteredClaimNames.Iss, LtiRequest.Aud[0]));
            response.AddClaim(new Claim(JwtRegisteredClaimNames.Aud, LtiRequest.Iss));
            response.AddClaim(new Claim(JwtRegisteredClaimNames.Sub, LtiRequest.Sub));
            response.AddClaim(new Claim(JwtRegisteredClaimNames.Iat, EpochTime.GetIntDate(DateTime.UtcNow).ToString()));
            response.AddClaim(new Claim(JwtRegisteredClaimNames.Nbf, EpochTime.GetIntDate(DateTime.UtcNow.AddSeconds(-5)).ToString()));
            response.AddClaim(new Claim(JwtRegisteredClaimNames.Exp, EpochTime.GetIntDate(DateTime.UtcNow.AddMinutes(5)).ToString()));
            response.AddClaim(new Claim(JwtRegisteredClaimNames.Nonce, IdentityModel.CryptoRandom.CreateUniqueId(8)));

            var platform = await _context.GetPlatformByIssuerAsync(LtiRequest.Iss);

            var credentials = PemHelper.SigningCredentialsFromPemString(platform.PrivateKey);
            var jwt         = handler.WriteToken(new JwtSecurityToken(new JwtHeader(credentials), response));

            return(Post("id_token", jwt, LtiRequest.DeepLinkingSettings.DeepLinkReturnUrl));
        }
Esempio n. 29
0
        /// <summary>
        /// 使用RefreshToken获取新的JwtToken信息
        /// </summary>
        /// <param name="refreshToken">刷新Token字符串</param>
        /// <returns>JwtToken信息</returns>
        public virtual async Task <JsonWebToken> RefreshToken(string refreshToken)
        {
            Check.NotNull(refreshToken, nameof(refreshToken));
            TokenValidationParameters parameters = new TokenValidationParameters()
            {
                ValidIssuer      = _jwtOptions.Issuer ?? "osharp identity",
                ValidAudience    = _jwtOptions.Audience ?? "osharp client",
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtOptions.Secret))
            };
            JwtSecurityToken jwtSecurityToken = _tokenHandler.ReadJwtToken(refreshToken);
            string           clientId         = jwtSecurityToken.Claims.FirstOrDefault(m => m.Type == "clientId")?.Value;

            if (clientId == null)
            {
                throw new OsharpException("RefreshToken 中不包含 ClientId 声明");
            }
            string userId = jwtSecurityToken.Claims.FirstOrDefault(m => m.Type == "nameid")?.Value;

            if (userId == null)
            {
                throw new OsharpException("RefreshToken 的数据中无法找到 UserId 声明");
            }

            RequestClientType?clientType = jwtSecurityToken.Claims.FirstOrDefault(m => m.Type == "clientType")?.Value.CastTo <RequestClientType>()
                                           ?? RequestClientType.Browser;

            UserManager <TUser> userManager       = _provider.GetService <UserManager <TUser> >();
            RefreshToken        existRefreshToken = await userManager.GetRefreshToken(userId, clientId);

            if (existRefreshToken == null || existRefreshToken.Value != refreshToken || existRefreshToken.EndUtcTime <= DateTime.UtcNow)
            {
                if (existRefreshToken != null && existRefreshToken.EndUtcTime <= DateTime.UtcNow)
                {
                    //删除过期的Token
                    await _provider.ExecuteScopedWorkAsync(async provider =>
                    {
                        userManager = provider.GetService <UserManager <TUser> >();
                        var result  = await userManager.RemoveRefreshToken(userId, clientId);
                        if (result.Succeeded)
                        {
                            IUnitOfWork unitOfWork = provider.GetUnitOfWork <TUser, TUserKey>();
                            unitOfWork.Commit();
                        }

                        return(result);
                    },
                                                           false);
                }
                throw new OsharpException("RefreshToken 不存在或已过期");
            }

            ClaimsPrincipal principal = _tokenHandler.ValidateToken(refreshToken, parameters, out _);

            string userName = principal.Claims.FirstOrDefault(m => m.Type == ClaimTypes.Name)?.Value;

            if (userName == null)
            {
                throw new OsharpException("RefreshToken 的数据中无法找到 UserName 声明");
            }

            JsonWebToken token = await CreateToken(userId, userName, clientType.Value, existRefreshToken);

            return(token);
        }
Esempio n. 30
0
        public string ProxyToken(string token, string to)
        {
            var jwtSecurityToken = _jwtSecurityTokenHandler.ReadJwtToken(token);

            return(ProxyToken(jwtSecurityToken, to));
        }