Click here to Skip to main content
15,881,715 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
I'm working with an very old VB.net application trying to layer in SSO auth using OWIN and KeyCloak. This is all new to me. The approach I'm taking is to create a C# app to sit in between KeyCloak and my VB app. I've been able to get my C# app to open the login screen of KeyCloak, authenticate and return to the C# app or even the VB app. This seems fine.

However, I need the id_token and username to pass to the VB app. When using Fiddler I can see KeyCloak is generating a post back to my return page with the id_token in tow. However, it is on another thread and gets redirected to the original page but without the id_token. I must be missing something. I've seen code where there are notifications wired and I think they should grab the token and user info, but I don't know how to get the notifications to work. There is no explicit documentation to tell me what to do.

Am I supposed to have a listener to catch the post from KeyCloak? If so can some one show me how to create one?

Note: I've found some Microsoft code using OWIN and Azure and MVC that bring back user info. However, I point this same code to KeyCloak it authenticates but no user info is returned.

Any help will be greatly appreciated.

-Thanks

In my Startup.cs file I have the following (I've tried many different variations to no avail):

C#
public void ConfigureAuth(IAppBuilder app)
{
    app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

    app.UseCookieAuthentication(new CookieAuthenticationOptions());
    app.UseOpenIdConnectAuthentication(
    new OpenIdConnectAuthenticationOptions
        {
            // Sets the ClientId, authority, RedirectUri as obtained from web.config
            ClientId = _clientId,
            ClientSecret = _clientSecret,
            RequireHttpsMetadata = false,
            Authority = _authority,
            RedirectUri = _redirectUri,
            // PostLogoutRedirectUri is the page that users will be redirected to after sign-out. In this case, it is using the home page
            PostLogoutRedirectUri = _redirectUri,
            Scope = OpenIdConnectScope.OpenIdProfile,
            // ResponseType is set to request the id_token - which contains basic information about the signed-in user
            ResponseType = OpenIdConnectResponseType.IdToken,
            // ValidateIssuer set to false to allow personal and work accounts from any organization to sign in to your application
            // To only allow users from a single organizations, set ValidateIssuer to true and 'tenant' setting in web.config to the tenant name
            // To allow users from only a list of specific organizations, set ValidateIssuer to true and use ValidIssuers parameter
            TokenValidationParameters = new TokenValidationParameters()
            {
                ValidateIssuer = true
            },
            // OpenIdConnectAuthenticationNotifications configures OWIN to send notification of failed authentications to OnAuthenticationFailed method
            Notifications = new OpenIdConnectAuthenticationNotifications
            {
                AuthenticationFailed = OnAuthenticationFailed,
                SecurityTokenReceived = OnSecurityTokenReceived
            }
        }
    );
}


What I have tried:

I've also tried things like this:

public void ConfigureAuth(IAppBuilder app)
{
    app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

    app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
    app.UseCookieAuthentication(new CookieAuthenticationOptions());

    app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
    {
        ClientId = _clientId,
        ClientSecret = _clientSecret,
        Authority = _authority,
        RequireHttpsMetadata = false,
        RedirectUri = _redirectUri,
        ResponseType = OpenIdConnectResponseType.CodeIdToken,
        Scope = OpenIdConnectScope.OpenIdProfile,
        //MetadataAddress = $"{_authority}/.well-known/openid-configuration",
        TokenValidationParameters = new TokenValidationParameters { NameClaimType = "name" },
        Notifications = new OpenIdConnectAuthenticationNotifications
        {
            AuthorizationCodeReceived = async n =>
            {
                var client = new HttpClient();

                var tokenResponse = await client.RequestAuthorizationCodeTokenAsync(new AuthorizationCodeTokenRequest
                {
                    Address = $"{ _authority}/protocol/openid-connect/token",
                    ClientId = _clientId,
                    ClientSecret = _clientSecret,
                    Code = n.Code,
                    RedirectUri = _redirectUri,
                });

                if (tokenResponse.IsError)
                {
                    throw new Exception(tokenResponse.Error);
                }

                var response = await client.GetUserInfoAsync(new UserInfoRequest
                {
                    //Address = disco.UserInfoEndpoint,
                    Token = tokenResponse.IdentityToken,
                    Address = $"{ _authority}/protocol/openid-connect/userinfo",
                    ClientId = _clientId,
                    ClientSecret = _clientSecret,
                    //Code = n.Code,
                    //RedirectUri = _redirectUri
                });

                if (response.IsError)
                {
                    throw new Exception(response.Error);
                }

                var claims = response.Claims;

                n.AuthenticationTicket.Identity.AddClaims(claims);
            },
        },
    });
}
Posted
Updated 21-Jul-21 8:23am

1 solution

Quote:
This is all new to me ... Am I supposed to have a listener to catch the post from KeyCloak? If so can some one show me how to create one?

Note: I've found some Microsoft code using OWIN and Azure and MVC that bring back user info. However, I point this same code to KeyCloak it authenticates but no user info is returned.
KeyCloak has an active support forum: [^]: that's probably a good place to ask this KeyCloak specific question.
 
Share this answer
 
Comments
ehwash 25-Sep-20 9:02am    
I was able to get the data I was looking for on my own... to a point. which leads me to my next question I will ask in another thread. The KeyCloak site offered no answers.
Harshal Agarwal 21-Jul-21 14:26pm    
Hi, were you able to integrate keycloak? If so, could you please guide how did you achieve it? I am trying to integrate keycloak with my ASP.Net application.
ehwash 18-Oct-21 16:56pm    
Sorry, it's been a while since I've been on this site. I moved away from OWIN and was able to get KeyCloak to work. I used KeyCloak as and IDP and got endpoints for the tokens. Then used FLURL to consume those endpoints and read the claims. Hope this helps.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900