Using protected APIs of IdentityServer4 by JWT access_token
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.
@leastprivilege and @brockallen Do you have any idea how to use this??
Have you followed the quickstarts? https://identityserver4.readthedocs.io/en/release/quickstarts/5_hybrid_and_api_access.html
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
So you're all set now?
Yes @brockallen , once again thanks 👍
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.