using IdentityServer4.Services;
using IdentityServer4.Stores;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Teknik.IdentityServer.Security;
using Teknik.IdentityServer.ViewModels;
using Teknik.Logging;
using Microsoft.Extensions.Logging;
using Teknik.Configuration;
namespace Teknik.IdentityServer.Controllers
{
///
/// This sample controller allows a user to revoke grants given to clients
///
[Authorize(AuthenticationSchemes = "Identity.Application")]
public class GrantsController : DefaultController
{
private readonly IIdentityServerInteractionService _interaction;
private readonly IClientStore _clients;
private readonly IResourceStore _resources;
public GrantsController(
ILogger logger,
Config config,
IIdentityServerInteractionService interaction,
IClientStore clients,
IResourceStore resources) : base(logger, config)
{
_interaction = interaction;
_clients = clients;
_resources = resources;
}
///
/// Show list of grants
///
[HttpGet]
public async Task Index()
{
ViewBag.Title = "Granted Applications";
return View("Index", await BuildViewModelAsync());
}
///
/// Handle postback to revoke a client
///
[HttpPost]
[ValidateAntiForgeryToken]
public async Task Revoke(string clientId)
{
await _interaction.RevokeUserConsentAsync(clientId);
return RedirectToAction("Index");
}
private async Task BuildViewModelAsync()
{
var grants = await _interaction.GetAllUserGrantsAsync();
var list = new List();
foreach(var grant in grants)
{
var client = await _clients.FindClientByIdAsync(grant.ClientId);
if (client != null)
{
var resources = await _resources.FindResourcesByScopeAsync(grant.Scopes);
var item = new GrantViewModel()
{
ClientId = client.ClientId,
ClientName = client.ClientName ?? client.ClientId,
ClientLogoUrl = client.LogoUri,
ClientUrl = client.ClientUri,
Created = grant.CreationTime,
Expires = grant.Expiration,
IdentityGrantNames = resources.IdentityResources.Select(x => x.DisplayName ?? x.Name).ToArray(),
ApiGrantNames = resources.ApiResources.Select(x => x.DisplayName ?? x.Name).ToArray()
};
list.Add(item);
}
}
return new GrantsViewModel
{
Grants = list
};
}
}
}