IdentityServer4 icon indicating copy to clipboard operation
IdentityServer4 copied to clipboard

Using protected APIs of IdentityServer4 by JWT access_token

Open siddharthashw opened this issue 9 years ago • 6 comments

Hello,

I am new to IdentityServer and i have followed all the guide as per IdentityServer4 I am creating a OAuth server for my team. And I want to use IdentityServer4 for that. My problem is how I can used some protected APIs of my OAuth server.

OAuth Server Project

Client.cs:-

`public static IEnumerable<Client> Clients()
    {
        return new List<Client>
            {
                new Client
                {
                    ClientId = "mvc",
                    ClientName = "MVC Client",
                    AllowedGrantTypes = GrantTypes.HybridAndClientCredentials,
                    AllowAccessTokensViaBrowser = true,
                    // where to redirect to after login
                    RedirectUris = { "http://localhost:64154/signin-oidc" },
                    // where to redirect to after logout
                    PostLogoutRedirectUris = { "http://localhost:64154/" },
                    AllowedScopes = new List<string>
                    {
                        IdentityServerConstants.StandardScopes.Email,
                        IdentityServerConstants.StandardScopes.OpenId,
                        IdentityServerConstants.StandardScopes.Profile,
                        "name"
                    },
                    //RequireClientSecret = false,
                    ClientSecrets = new List<Secret>
                    {
                        new Secret("superSecretPassword".Sha256())
                    },
                    //AccessTokenType = AccessTokenType.Reference,
                    AllowOfflineAccess = true
                }
    }`

Startup.cs:-

public void ConfigureServices(IServiceCollection services)
    {
        services.AddApplicationInsightsTelemetry(Configuration);
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

        services.AddMvc();
        var cert = new X509Certificate2(Path.Combine(_env.ContentRootPath, "idsvr3test.pfx"),"idsrv3test");
        // Add application services.
        services.AddTransient<IEmailSender, AuthMessageSender>();
        services.AddTransient<ISmsSender, AuthMessageSender>();
         services.AddIdentityServer()
            .AddSigningCredential(cert)
            .AddInMemoryIdentityResources(Config.GetIdentityResources())
            .AddInMemoryApiResources(Config.GetApiResources())
            .AddInMemoryClients(Config.Clients())
            .AddAspNetIdentity<ApplicationUser>();

    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        //InitializeDatabase(app);
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        app.UseApplicationInsightsRequestTelemetry();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
            app.UseBrowserLink();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseApplicationInsightsExceptionTelemetry();

        app.UseStaticFiles();

        app.UseIdentity();

        app.UseIdentityServer();
        // Add external authentication middleware below. To configure them please see http://go.microsoft.com/fwlink/?LinkID=532715

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }`

OAuthSomeController:-

`private readonly UserManager<ApplicationUser> _userManager;
    public OAuthSomeController(UserManager<ApplicationUser> userManager)
    {
        _userManager = userManager;
    }
    [Authorize]
    [Route("Home/UserDetails/{userId}")]
    public async Task<IActionResult> UserDetails(string userId)
    {
        var user = await _userManager.FindByIdAsync(userId);
        return Ok(user);
    }`

Client Project:

startup.cs:-

`app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationScheme = "Cookies"
        });

        JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
        app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
        {
            AuthenticationScheme = "oidc",
            SignInScheme = "Cookies",

            Authority = "http://localhost:5000/",
            RequireHttpsMetadata = false,

            ClientId = "mvc",
            ClientSecret = "superSecretPassword",

            ResponseType = "code id_token",
            Scope = { "openid", "offline_access", "email", "profile" },

            GetClaimsFromUserInfoEndpoint = true,
            SaveTokens = true,

        });`

RequestController:-

`   [Authorize]
    public async Task<IActionResult> GetAuthorize()
    {
            var accessToken = await HttpContext.Authentication.GetTokenAsync("access_token");
           client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);
            var userId = "1521f55d-251d-4214-aaa1-bacf190ea433";
            var userUrl = "http://localhost:5000/Home/UserDetails/" + userId;
            var userDetailsResult = client.GetAsync(userUrl).Result;
            if (userDetailsResult.IsSuccessStatusCode)
            {
                var result = userDetailsResult.Content.ReadAsStringAsync().Result;
            }
}`

When I can this GetAuthorize API from Client project it goes to my Oauth project and get the authenication. Then I try to call a protected API using access token as bearer using authorization header field result contain the login view page as string.

Suggest the way to use the APIs of OAuth server using access token Thank in-advance.

siddharthashw avatar Jan 16 '17 07:01 siddharthashw

@leastprivilege and @brockallen Do you have any idea how to use this??

siddharthashw avatar Jan 18 '17 10:01 siddharthashw

Have you followed the quickstarts? https://identityserver4.readthedocs.io/en/release/quickstarts/5_hybrid_and_api_access.html

brockallen avatar Jan 18 '17 20:01 brockallen

Got the way we need to add UseIdentityServerAuthentication in Configure (startup.cs) in OAuth Server Project

app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
        {
            Authority = appSetting.PromactOAuthUrl,
            RequireHttpsMetadata = false,
            ApiName = "user.info",
            AllowedScopes = { "openid", "offline_access", "email", "profile", "slack_user_id", "user.read" },
            ApiSecret = "***********",
        });`

Thank for advice

siddharthashw avatar Jan 19 '17 04:01 siddharthashw

So you're all set now?

brockallen avatar Jan 21 '17 11:01 brockallen

Yes @brockallen , once again thanks 👍

siddharthashw avatar Jan 22 '17 07:01 siddharthashw

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

lock[bot] avatar Jan 15 '20 03:01 lock[bot]