2
votes

I have 3 projects

1) Identity Server. It's netcoreapp1.1 and identityserver4. Its URL is http://localhost:9000

Here is my configuration for the client app.

new Client
            {
                ClientId = "customer.api",
                ClientName = "Customer services",
                AllowedGrantTypes = GrantTypes.HybridAndClientCredentials,
                RequireConsent = false,
                AllowAccessTokensViaBrowser = true,

                RedirectUris = validClientUris.CustomerClientUris
                    .Select(baseUri => baseUri + "signin-oidc")
                    .ToList(),
                PostLogoutRedirectUris = validClientUris.CustomerClientUris.ToList(),

                ClientSecrets = new List<Secret>
                {
                    new Secret("testsecret".Sha256())
                },
                AllowedScopes = new List<string>
                {
                    IdentityServerConstants.StandardScopes.OpenId,
                    IdentityServerConstants.StandardScopes.Profile,
                    IdentityServerConstants.StandardScopes.Email,
                    IdentityServerConstants.StandardScopes.OfflineAccess,
                    HydraScopes.CustomerPrivateLinesVNApi, //"customerprivatelinesvn.api"                       
                },
                AllowOfflineAccess = true,
                AlwaysIncludeUserClaimsInIdToken = true,
                AllowedCorsOrigins = validClientUris.CustomerClientUris
            });

2) REST API project. It's ASP.NET Core 2.0. Its URL is http://localhost:60001

Here is ConfigureServices of Startup class

public void ConfigureServices(IServiceCollection services)
    {
        services
            .AddCustomerManagementCoreServices()
            .AddRavenStoreServices(Configuration);

        services.AddCors();

        services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme) // "Bearer"
            .AddIdentityServerAuthentication(options =>
            {
                options.Authority = "http://localhost:9000/";
                options.ApiName = "customerprivatelinesvn.api";
                options.RequireHttpsMetadata = false;
            });

        services.AddMvc(setupAction =>
        {
            setupAction.ReturnHttpNotAcceptable = true;                
        });

        services.AddApiVersioning(setupAction =>
        {
            setupAction.ReportApiVersions = true;
        });            
    }

3) Angular web application. Its URL is http://localhost:60002

I use the Angular template of Visual Studio 2017 as below. enter image description here

Here is ConfigureServices of Startup class of Angular web

public void ConfigureServices(IServiceCollection services)
    {
        JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();            

        services.AddAuthentication(options =>
        {
            options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; // "Cookies"
            options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme; // "OpenIdConnect"
            options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; // "Cookies"
        })
        .AddCookie()
        .AddOpenIdConnect(options =>
        {
            Configuration.GetSection("OpenIdConnect").Bind(options);                
        });

        services.AddMvc();
    }

And here is the configuration of OpenIdConnect

"OpenIdConnect": {
"Authority": "http://localhost:9000/",
"RequireHttpsMetadata": false,
"ClientId": "customer.api",
"ClientSecret": "testsecret",
"Scope": [ "customerprivatelinesvn.api", "offline_access" ],      
"PostLogoutRedirectUri": "http://localhost:60002",
"CallbackPath": "/signin-oidc",
"ResponseType": "code id_token token",
"GetClaimsFromUserInfoEndpoint": true,
"SaveTokens":  true}

With configurations above, when user browses to Angular web (http://localhost:60002), it will redirect to the login page of Identity Server. After user inputs username/password, it will return to Angular app with authenticated information stored in cookies (http://localhost:60002).

I believe that the access token is stored in the cookies as well. Because I can see it in Fiddler at localhost:60002/signin-oidc.

enter image description here

enter image description here

enter image description here

I have some questions

1) How can I get access token from cookies so that I can add it to the request header to be able to call REST API on Angular components?

2) Can we store access token to Local Storage instead of Cookies? And how to store?

3) How can I store and use refresh token to get new access token when access token expired?

Thank you very much.

Best regards,

Kevin

1
It's easy to get access token. I can resolve it now. - Kevin Hoang
I have the same problem. Couldn't solve this, Kevin... - Caio Ladislau

1 Answers

1
votes

We can call HttpContext.GetTokenAsync() in the view

@if (User.Identity.IsAuthenticated)
{
    <input id="access_token" type="hidden" value="@ViewContext.HttpContext.GetTokenAsync("access_token").Result" />    
}

Or we can store the access token in LocalStorage

@section scripts {
    <script src="~/dist/main-client.js" asp-append-version="true"></script>
    <script>
        var key = "My_app_Access_Token";
        var accessToken = document.getElementById("access_token");
        localStorage.setItem(key, accessToken.value);
    </script>
}