コード例 #1
0
ファイル: Function.cs プロジェクト: guitarrapc/dotnet-lab
        public IActionResult ReplyResetPassword(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req,
            ExecutionContext context,
            ILogger log)
        {
            log.LogInformation($"{nameof(ReplyResetPassword)}: C# HTTP trigger function processed a request.");
            var redirectUri = new Uri($"{req.Scheme}://{req.Host.Value}/{azureAdB2COptions.RedirectPathProfile}");

#if DEBUG
            log.LogInformation($"Environment information");
            LogParams("", null, "", "", "", context, log);
#endif

            // get user info from `id_token`
            var idTokens = req.Form.Where(x => x.Key == "id_token").Select(x => x.Value).FirstOrDefault();
            if (!idTokens.Any())
            {
                return(new UnauthorizedResult());
            }
            var payload = JwtPayload.Base64UrlDeserialize(idTokens.First().Split('.').Skip(1).FirstOrDefault());
            if (payload == null)
            {
                return(new BadRequestResult());
            }

            return(new OkObjectResult(new
            {
                message = "successfully reset password."
            }));
        }
コード例 #2
0
        private bool IsCorrectRoleInToken(HttpContext httpContext)
        {
            try
            {
                var token = _authService.ReadCookie(httpContext, _appSettings.CookieTokenName, true);

                if (token != null)
                {
                    var jwtPayload = JwtPayload.Base64UrlDeserialize(token.Split('.')[1]);

                    var roles = JsonConvert.DeserializeObject <ScopesInToken>(jwtPayload.SerializeToJson());

                    for (int i = 0; i < _appSettings.AcceptUserRole.Length; i++)
                    {
                        if (roles.Scopes.Contains <string>(_appSettings.AcceptUserRole[i]))
                        {
                            return(true);
                        }
                    }
                }
            }
            catch { };

            return(false);
        }
        public void JwtPayload_Claims()
        {
            List <string> errors     = new List <string>();
            var           jwtPayload = new JwtPayload();

            // multiple audiences
            foreach (string aud in IdentityUtilities.DefaultAudiences)
            {
                jwtPayload.AddClaim(new Claim(JwtRegisteredClaimNames.Aud, aud));
            }

            string encodedPayload      = jwtPayload.Base64UrlEncode();
            var    deserializedPayload = JwtPayload.Base64UrlDeserialize(encodedPayload);

            if (!IdentityComparer.AreEqual(jwtPayload, deserializedPayload))
            {
                errors.Add("!IdentityComparer.AreEqual(jwtPayload, deserializedPayload)");
            }

            if (!IdentityComparer.AreEqual <IEnumerable <string> >(jwtPayload.Aud, IdentityUtilities.DefaultAudiences))
            {
                errors.Add("!IdentityComparer.AreEqual<IEnumerable<string>>(jwtPayload.Aud, IdentityUtilities.DefaultAudiences)");
            }

            TestUtilities.AssertFailIfErrors(MethodInfo.GetCurrentMethod().Name, errors);
        }
コード例 #4
0
        private async void ByOAuth2()
        {
            MyCredential myCredential = new MyCredential()
            {
                authURL     = Authority,
                ClientId    = ClientId,
                RedirectUri = RedirectUri,
                Resource    = ResourceUri
            };

            Authenticator authenticator = new Authenticator()
            {
                Credential = myCredential
            };
            string accessCode = await authenticator.GetAccessCode();

            if (!string.IsNullOrEmpty(accessCode))
            {
                string json = await authenticator.GetAccessToken(accessCode);

                AccessTokenInfo info = JsonConvert.DeserializeObject <AccessTokenInfo>(json);
                ResponseStr = json.Replace(",\"", ",\r\n\"");
                string[] jwt     = info.AccessToken.Split('.');
                string   payload = jwt.Length == 3 ? jwt[1] : "";
                if (!string.IsNullOrEmpty(payload))
                {
                    JwtPayload jwtPayload = JwtPayload.Base64UrlDeserialize(payload);
                    this.JsonWebTokenStr = jwtPayload.SerializeToJson().Replace(",\"", ",\r\n\"");
                    SetControl(jwtPayload);
                }
            }
        }
コード例 #5
0
        public string GetPayLoadValue(string payLoadString, string key)
        {
            var    payLoad = JwtPayload.Base64UrlDeserialize(payLoadString);
            object valueObject;

            payLoad.TryGetValue(key, out valueObject);
            return(valueObject?.ToString());
        }
コード例 #6
0
        public LiveIDAccountInfo getAccountInfo()
        {
            var payload = JwtPayload.Base64UrlDeserialize(this.id_token.Split('.')[1]);
            var json    = payload.SerializeToJson();
            LiveIDAccountInfo account_info = Newtonsoft.Json.JsonConvert.DeserializeObject <LiveIDAccountInfo>(json);

            return(account_info);
        }
コード例 #7
0
        private string GetUserIdFromJwt()
        {
            Request.Headers.TryGetValue(HeaderNames.Authorization, out var authorization);
            var token = authorization.First();

            token = token.Replace("Bearer ", "");
            string[] jwtArray = token.Split('.');

            var payload = JwtPayload.Base64UrlDeserialize(jwtArray[1]);

            return(payload.Sub);
        }
コード例 #8
0
        /// <summary>
        /// Builds a claims identity.
        /// </summary>
        /// <param name="request">The incoming <see cref="HttpRequest" />.</param>
        /// <returns>A populated <see cref="ClaimsIdentity" />.</returns>
        public Task <ClaimsIdentity> BuildClaimsIdentityAsync(HttpRequest request)
        {
            ClaimsIdentity result = null;

            if (request.Headers.ContainsKey("X-MS-CLIENT-PRINCIPAL"))
            {
                var payload = JwtPayload.Base64UrlDeserialize(request.Headers["X-MS-CLIENT-PRINCIPAL"]);
                var claims  = payload.Claims.Where(x => x.Type == "claims").Select(x => ConvertToClaim(x.Value)).ToList();

                result = new ClaimsIdentity(claims, "azuread", "name", "roles");
            }

            return(Task.FromResult(result));
        }
コード例 #9
0
ファイル: JwtPayloadTest.cs プロジェクト: zbjlala/netcoreRSA
        private void RunEncodingVariation(List <Claim> claims, Dictionary <string, object> values, CompareContext context)
        {
            var jwtPayload1 = new JwtPayload(claims);
            var jwtPayload2 = new JwtPayload();

            foreach (var kv in values)
            {
                jwtPayload2[kv.Key] = kv.Value;
            }

            IdentityComparer.AreEqual(jwtPayload1, jwtPayload2, context);

            jwtPayload1 = JwtPayload.Base64UrlDeserialize(jwtPayload1.Base64UrlEncode());
            jwtPayload2 = JwtPayload.Base64UrlDeserialize(jwtPayload2.Base64UrlEncode());
            IdentityComparer.AreEqual(jwtPayload1, jwtPayload2, context);
        }
コード例 #10
0
        public static bool TokenPayload(string token, Guid userId)
        {
            object obString;

            var splitToken        = token.Split(' ');
            var splitToPayload    = splitToken[1].Split('.');
            var tokenDeserialized = JwtPayload.Base64UrlDeserialize(splitToPayload[1]).TryGetValue("unique_name", out obString);
            var tokenPayloadGuid  = Guid.Parse(obString.ToString());

            if (userId == tokenPayloadGuid)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
コード例 #11
0
        public static bool AdminPayload(string token)
        {
            object obString;

            var splitToken        = token.Split(' ');
            var splitToPayload    = splitToken[1].Split('.');
            var tokenDeserialized = JwtPayload.Base64UrlDeserialize(splitToPayload[1]).TryGetValue("http://schemas.microsoft.com/ws/2008/06/identity/claims/role", out obString);
            var role = obString.ToString();

            if (role == "admin")
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
コード例 #12
0
ファイル: JwtPayloadTest.cs プロジェクト: zbjlala/netcoreRSA
        public void JwtPayloadUnicodeMapping()
        {
            string       issuer         = "a\\b";
            List <Claim> claims         = new List <Claim>();
            JwtPayload   unicodePayload = new JwtPayload("a\u005Cb", "", claims, null, null);
            string       json           = unicodePayload.SerializeToJson();
            JwtPayload   payload        = new JwtPayload(issuer, "", claims, null, null);
            string       json2          = payload.SerializeToJson();

            Assert.Equal(json, json2);

            JwtPayload retrievePayload = JwtPayload.Deserialize(json);

            Assert.Equal(retrievePayload.Iss, issuer);

            json  = unicodePayload.Base64UrlEncode();
            json2 = payload.Base64UrlEncode();
            Assert.Equal(json, json2);

            retrievePayload = JwtPayload.Base64UrlDeserialize(json);
            Assert.Equal(retrievePayload.Iss, issuer);
        }
コード例 #13
0
        public IActionResult VerifyToken([FromHeader(Name = HEADER_AUTH)] string token)
        {
            IActionResult response = Unauthorized();

            var headerKeys = string.Empty;

            foreach (var key in Request.Headers.Keys)
            {
                headerKeys += key.ToString() + ", ";
            }
            headerKeys = headerKeys.Substring(0, headerKeys.Length - 2);

            if (Request.Headers.Keys.Contains(HEADER_AUTH))
            {
                var reqHeader = Request.Headers.FirstOrDefault(h => h.Key == HEADER_AUTH);
                if (reqHeader.Value != string.Empty && reqHeader.Value != "null")
                {
                    try
                    {
                        if (ModelState.IsValid) // ModelState อาจจะไม่จำเป็นต้องใช้ หรือใช้ไม่ได้กับ API
                        {
                            try
                            {
                                var handler     = new JwtSecurityTokenHandler();
                                var jwtSecToken = handler.ReadToken(token) as JwtSecurityToken;

                                string[] jwtArray   = token.Split('.');
                                var      jwtHeader  = JwtHeader.Base64UrlDeserialize(jwtArray[0]);
                                var      jwtPayload = JwtPayload.Base64UrlDeserialize(jwtArray[1]);

                                Jwt.Algorithm jwtAlg;

                                if (jwtHeader.Alg == "HS256")
                                {
                                    jwtAlg = Jwt.Algorithm.HS256;
                                }
                                else if (jwtHeader.Alg == "RS256")
                                {
                                    jwtAlg = Jwt.Algorithm.RS256;
                                }
                                else if (jwtHeader.Alg == "ES256")
                                {
                                    jwtAlg = Jwt.Algorithm.ES256;
                                }
                                else
                                {
                                    jwtAlg = Jwt.Algorithm.HS256;
                                }

                                var tokenHandler = new JwtSecurityTokenHandler();
                                try
                                {
                                    var claimPrincipal = tokenHandler.ValidateToken(token, new TokenValidationParameters
                                    {
                                        ValidIssuer              = _config["Jwt:Issuer"],
                                        ValidAudience            = _config["Jwt:Audience"],
                                        ValidateIssuer           = true,
                                        ValidateAudience         = true,
                                        ValidateLifetime         = true,
                                        ValidateIssuerSigningKey = true,
                                        ClockSkew        = TimeSpan.Zero,
                                        IssuerSigningKey = Jwt.GetSecurityKey(jwtAlg, _config, _azObj)
                                    }, out var parsedToken);

                                    var isAuthen = claimPrincipal.Identity.IsAuthenticated;

                                    if (isAuthen)
                                    {
                                        var result = "valid";
                                        return(Ok(new { result, token }));
                                    }
                                    else
                                    {
                                        response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.Invalid_AccessToken, "Unauthorized, AccessToken (" + token + ") is invalid (Can Not Authenticated).");
                                    }
                                }
                                catch (Exception ex)
                                {
                                    response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.Invalid_AccessToken, "Unauthorized, AccessToken (" + token + ") is invalid (>> " + ex.Message + ").");
                                }
                            }
                            catch (Exception ex)
                            {
                                response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.Invalid_AccessToken, "Unauthorized, AccessToken (" + token + ") is invalid (> " + ex.Message + ").");
                            }
                        }
                        else // ModelState อาจจะไม่จำเป็นต้องใช้ หรือใช้ไม่ได้กับ API
                        {
                            response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.ExceptionalOccured, "Unauthorized, Input Model ('" + headerKeys + "') is invalid.");
                        }
                    }
                    catch (Exception ex)
                    {
                        response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.ExceptionalOccured, "Unauthorized, Exception occurred (" + ex.Message + " - " + ex.Source + " - " + ex.StackTrace + " - " + ex.InnerException + " - " + ex.HelpLink + ").");
                    }
                }
                else
                {
                    response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.Invalid_AccessToken, "Unauthorized, AccessToken is empty");
                }
            }
            else
            {
                response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.ExceptionalOccured, "Unauthorized, Input Model is invalid (There is no Auth-Jwt).");
            }

            return(response);
        }