コード例 #1
0
        public Task Validate(ValidateUserAndPasswordContext context)
        {
            if (context.User == User && context.Password == Password)
            {
                var claims = new[]
                {
                    new Claim(ClaimTypes.NameIdentifier, context.User, ClaimValueTypes.String, context.Options.ClaimsIssuer),
                    new Claim(ClaimTypes.Name, context.User, ClaimValueTypes.String, context.Options.ClaimsIssuer)
                };

                context.Principal = new ClaimsPrincipal(new ClaimsIdentity(claims, context.Scheme.Name));
                context.Success();
            }

            return(Task.CompletedTask);
        }
コード例 #2
0
        protected override async Task <AuthenticateResult> HandleAuthenticateAsync()
        {
            string authorizationHeader = Request.Headers["Authorization"];

            if (string.IsNullOrEmpty(authorizationHeader))
            {
                return(AuthenticateResult.NoResult());
            }

            string basicPrefix = "Basic";

            if (!authorizationHeader.StartsWith(basicPrefix))
            {
                AuthenticateResult.NoResult();
            }

            string encodedCredentials = authorizationHeader.Substring(basicPrefix.Length).Trim();

            if (string.IsNullOrEmpty(encodedCredentials))
            {
                return(AuthenticateResult.Fail("No credentials"));
            }

            string decodedCredentials = Encoding.UTF8.GetString(Convert.FromBase64String(encodedCredentials));

            string[] userAndPassword = decodedCredentials.Split(':');

            var user     = userAndPassword[0];
            var password = userAndPassword[1];

            var context = new ValidateUserAndPasswordContext(Context, Scheme, Options)
            {
                User     = user,
                Password = password
            };

            await Options.Validate(context);

            if (context.Result != null)
            {
                var ticket = new AuthenticationTicket(context.Principal, Scheme.Name);
                return(AuthenticateResult.Success(ticket));
            }

            return(AuthenticateResult.NoResult());
        }