There are not much examples available about ASP.NET Core and acquiring access token. I found good and pretty big sample by Microsoft Patterns & Practices called multitenant-saas-guidance, Based on this I wrote my simple “boiler plate” ASP.NET Core solution that authenticates against Azure Active Directory and asks current user data using Microsoft Graph.
The following diagram from Azure Active Directory documentation illustrates the situation.
Sample solution. My solution at GitHub. My “boiler plate” solution is available at GitHub repository AspNetCoreBearerTokenAuth. You can take it, configure it and run it wherever you like. Also you can use it as starting point for your own application.
To have a bearer token the application must catch access token and put it in token cache for later use. This is the code that is not generated by Visual Studio tools automatically and writing it from scratch very good understanding of Azure AD authentication is needed.
Storing access token
To store access token the token cache is used. My solution uses SQL Server based distributed cache so this solution can also be used in cloud environments. Tokens are cached by special class called TokenCache. Sample application inherits DistributedTokenCache class from this. DistributedTokenCache is needed because is works like a bridge between SQL storage and TokenCache. It is all configured in Startup class of sample application. This is where solving the puzzle starts.
TokenService and AuthEvent classes do the actual work. When access code is received then AuthorizationCodeReceived event in AuthEvent is fired. In this event the token service is called to retrieve access token. Access token is put to token cache for later use. This is the additional work needed on application level to be able to acquire bearer tokens.
Here is AuthorizationCodeReceived event of AuthEvents class.
public override async Task AuthorizationCodeReceived(AuthorizationCodeReceivedContext context)
{
var principal = context.Ticket.Principal;
var request = context.HttpContext.Request;
var currentUri = UriHelper.BuildAbsolute(request.Scheme, request.Host, request.PathBase, request.Path);
var tokenService = (ITokenService)context.HttpContext.RequestServices.GetService(typeof(ITokenService));
try
{
await tokenService.RequestTokenAsync(
principal,
context.ProtocolMessage.Code,
currentUri,
_azureAdConfig.GraphResourceId)
.ConfigureAwait(false);
}
catch
{
await tokenService.ClearCacheAsync(principal).ConfigureAwait(false);
throw;
}
}
Here is RequestTokenAsync method of TokenService class.
public async Task<AuthenticationResult> RequestTokenAsync(
ClaimsPrincipal claimsPrincipal,
string authorizationCode,
string redirectUri,
string resource)
{
try
{
var userId = claimsPrincipal.GetObjectIdentifierValue();
var issuerValue = claimsPrincipal.GetIssuerValue();
var authenticationContext = await CreateAuthenticationContext(claimsPrincipal)
.ConfigureAwait(false);
var authenticationResult = await authenticationContext.AcquireTokenByAuthorizationCodeAsync(
authorizationCode,
new Uri(redirectUri),
new ClientCredential(_adOptions.ClientId, _adOptions.ClientSecret),
resource)
.ConfigureAwait(false);
return authenticationResult;
}
catch (Exception)
{
throw;
}
}
Getting bearer token
If controller action needs bearer token then ITokenService must be injected to controller.
[Authorize]
public class HomeController : Controller
{
private readonly ITokenService _tokenService;
public HomeController(ITokenService tokenService)
{
_tokenService = tokenService;
}
// Controller actions follow
}
Bearer token can be asked only for authenticated user. With anonymous user it’s possible only to ask token for application level permissions but this case is not covered here.
Here is the sample controller action to query current user’s information from Azure Active Directory.
public async Task<IActionResult> MyInformation()
{
var token = await _tokenService.GetBearerToken(User);
var authDelegate = new DelegateAuthenticationProvider(
(requestMessage) =>
{
var authHeader = new AuthenticationHeaderValue("bearer", token);
requestMessage.Headers.Authorization = authHeader;
return Task.FromResult(0);
});
var client = new GraphServiceClient(authDelegate);
var me = await client.Me.Request().GetAsync();
var collection = GraphObjectToCollection(me);
return View(collection);
}
Here bearer token is given to authetication provider delegate that is used by Microsoft Graph client to authenticate user.
Wrapping up
Azure AD is powerful and flexible solution for online authentication and authorization. It also supports bearer token authentication scenarios between applications and services. Current ASP.NET Core tooling doesn’t generate code for bearer token scenarios and therefore developers must write some code by theirselves. Solution offered here is simple enough to get connected to external services using bearer token authentication. For real scenarios more care of exceptions and special cases is needed and it’s good idea to check how Microsoft has implemented bearer token authentication.
View Comments (2)
This website, you can find lots of slot machines from leading developers.
Players can experience traditional machines as well as new-generation slots with vivid animation and exciting features.
Even if you're new or an experienced player, there’s always a slot to match your mood.
casino slots
All slot machines are available round the clock and compatible with desktop computers and tablets alike.
You don’t need to install anything, so you can start playing instantly.
Platform layout is intuitive, making it quick to find your favorite slot.
Join the fun, and dive into the excitement of spinning reels!
Now add a phone quantity and voice mail and, in fact, to dam your number whenever you name them again. Tip 3 - use your mobile phone and/or block your number when contacting anybody by way of telephone. In some States, they may also get the make, mannequin and report the number of the automotive you drive. This implies no airline ticket to see a dying relative, no rent, so they don't get thrown out and be homeless tomorrow, and no train ticket to return back quickly to see you this weekend. We went on a socially-distanced stroll for our first date, and then continued to see one another all through the pandemic. Second, could the unethical person to make use of the data to information you after which play in your feelings set you up for a scam. It may simply be that the one who wants a fast relationship with the attractive woman he met on-line, and uses this data to make her feel that they've many issues in widespread. The second set of suggestions is designed specifically for extroverts who could also be pining for that certain introvert in their lives.
Here I supply two units of 5 dating ideas. When you first meet someone online, we're most concerned about two issues. Don’t: Sound too Needy - We're positive that almost all girls think that listing every potential thing that they want in a man is an effective factor as it can weed out the ones that do not qualify, but guess what, you’re additionally scaring away everyone else by sounding a bit too needy. These will always be good advice. So you will have to interact with individuals in some unspecified time in the future. 5 - if people have your present deal with, they can also rapidly get details about the worth of any property you own and a list of your relatives and other associates. The truth is, take away him from your cell phone’s deal with book and from your Facebook friends’ listing too. Join a bowling league, a yoga group, a book membership. Safety Dating Tip 4 - virtual latamdate review telephone quantity and voicemail. This most often occurs in instances the place you used your cellular phone as a contact number for a utility bill or if you apply for credit score. Do not get caught to provide private data if you end up caught in a web based or cellphone conversation with somebody you have by no means met.
Also take notes on what your online contacts learn about you, you should suspect you're being manipulated, in the event that they seem to know far more about you than you know about them, comments like "You can be shocked by what I find out about you." shouldn't be taken flippantly. Some people deem a love train like that to be very romantic. And whereas it might not all the time be clear immediately if somebody is an introvert or extrovert, let's pretend at this point, you've got already determined that about your potential hunka-burning love for the time being, shall we? You love your mattress, your books, your lap high. Four - your cell or unlisted phone quantity in itself might lead to an actual match to your handle. Give compliments sparingly - One factor that may turn potential dates off faster than the whole lot else is in the occasion that they feel that you are not being straightforward with them.While you give a large number of compliments to a person, additionally subconsciously they will rapidly really feel, and suspect that you have an ulterior motive.Try not to commit that error!
By approaching dating with an open mind, empathy, and a willingness to speak and understand, people can navigate the fashionable relationship panorama with confidence and style, paving the way for connections which can be each rewarding and enduring. If you are feeling stuck in a rut, swapping your old pics for some recent ones is a fast manner to provide your profile a lift. Nobody likes a profile that sounds as if the writer is tailoring his or her character to what other individuals want to listen to. Sometimes, individuals might need unfavorable opinions or judgments about virtual relationships. As we conclude, it's clear that the Golden Rule is greater than only a moral guideline; it's a practical strategy to fostering healthier, extra fulfilling relationships. Consider shifting your approach from amount to quality. If you understand your age, can this record drop to 3 or much less. Doesn't a lot matter, so lengthy as the trade of concepts is the main car by which you get to know someone. We alternate emails and she sends me a photograph. Safety Dating Tip 5 - make an inventory of what you wish to share.