protected override async Task <AuthenticationTicket> AuthenticateCoreAsync()
        {
            // Bearer token authentication override
            if (Options.EnableBearerTokenAuth)
            {
                // Try to authenticate via bearer token auth
                if (Request.Headers.ContainsKey(Constants.BearerTokenHeader))
                {
                    var bearerAuthArr = Request.Headers[Constants.BearerTokenHeader].Trim().Split(new[] { ' ' }, 2);
                    if ((bearerAuthArr.Length == 2) && bearerAuthArr[0].ToLowerInvariant() == "bearer")
                    {
                        try
                        {
                            var authResponse = new TokenResponse(bearerAuthArr[1], null, null);
                            var kcIdentity   = await KeycloakIdentity.ConvertFromTokenResponseAsync(Options, authResponse);

                            var identity = await kcIdentity.ToClaimsIdentityAsync();

                            SignInAsAuthentication(identity, null, Options.SignInAsAuthenticationType);
                            return(new AuthenticationTicket(identity, new AuthenticationProperties()));
                        }
                        catch (Exception)
                        {
                            // ignored
                        }
                    }
                }

                // If bearer token auth is forced, skip standard auth
                if (Options.ForceBearerTokenAuth)
                {
                    return(null);
                }
            }

            return(null);
        }
예제 #2
0
        public static async Task <ClaimsIdentity> GetKeycloakIdentityAsync(string username, string password)
        {
            if (Options == null)
            {
                throw new ArgumentNullException("options");
            }
            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            {
                throw new InvalidCredentialException("username or password is empty.");
            }
            var uriManager = await OidcDataManager.GetCachedContextAsync(Options);

            var response = SendHttpPostRequest(uriManager.GetTokenEndpoint(), uriManager.BuildROPCAccessTokenEndpointContent(username, password));

            var result = await response.Content.ReadAsStringAsync();

            var tokenrespones = new TokenResponse(result);

            var claimidentity = await KeycloakIdentity.ConvertFromTokenResponseAsync(Options, tokenrespones);

            var identity = await claimidentity.ToClaimsIdentityAsync();

            return(new ClaimsIdentity(identity.Claims, Options.SignInAsAuthenticationSchema, identity.NameClaimType, identity.RoleClaimType));
        }