Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@JeremyLikness
Created May 14, 2020 04:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JeremyLikness/fcb62c9e6b55f3ead624e354998f003a to your computer and use it in GitHub Desktop.
Save JeremyLikness/fcb62c9e6b55f3ead624e354998f003a to your computer and use it in GitHub Desktop.
Cosmos token controllerr
using System.Threading.Tasks;
using IConfiguration = Microsoft.Extensions.Configuration.IConfiguration;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.Cosmos;
using BlazorCosmosWasm.Shared;
using Microsoft.AspNetCore.Identity;
using BlazorCosmosWasm.Server.Models;
namespace BlazorCosmosWasm.Server.Controllers
{
[Authorize]
[Route("api/[controller]")]
[ApiController]
public class CosmosController : ControllerBase
{
private readonly UserManager<ApplicationUser> Manager;
public CosmosController(IConfiguration config, UserManager<ApplicationUser> manager)
{
Config = config;
Manager = manager;
Client = config.CreateCosmosClientFromConfig();
}
private CosmosClient Client { get; }
public IConfiguration Config { get; set; }
[HttpGet]
public async Task<IActionResult> Get()
{
var user = await User.GetEmailAsync(Manager);
if (user == null)
{
return NotFound();
}
var db = Client.GetDatabase(BlogContext.DatabaseName);
var container = db.GetContainer(nameof(BlogContext));
var cosmosUser = db.GetUser(user);
var permissionId = $"Permission-{user}-blogs";
await cosmosUser.UpsertPermissionAsync(new PermissionProperties(
id: permissionId,
permissionMode: PermissionMode.Read,
container: container));
var token = await cosmosUser.GetPermission(permissionId).ReadAsync();
return Ok(
new CosmosCredentials
{
EndPoint = Client.Endpoint.ToString(),
Key = token.Resource.Token
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment