I want to use MsGraph in B2C, but I get a corrs error when getting an access token - api

I have an SPA that uses B2C as its certification.
not AD, im using B2C.
Now I want to display user information on the SPA,
so I want to use MsGraphAPI to get data from B2C.
Therefore, we are trying to obtain an access token using credential flow.
The code is as follows
requestUri = "https://login.microsoftonline.com/{tenandId}/oauth2/v2.0/token";
var params = new URLSearchParams();
params.append("grant_type","client_credentials");
params.append("client_id","XXXX");
params.append("client_secret","ZZZZ");
params.append("scope","https://graph.microsoft.com/.default");
const response = fetch(requestUri, {
method:"POST",
body:params
});
At this time, the developer tool shows a corrs error.
The following error.
access to fetch "https://login.microsoftonline.com/{tenandId}/oauth2/v2.0/token" from origin "http://localhost:3000" has been blocked by CORS policy.
How can I resolve this?
SPA is available at http://localhost:3000.
Is the localhost no good?

The purpose of authenticating is to get user information. You can insert any attribute into the token, and then parse the id_token to display the users profile information in your application. Calling MS Graph API for this seems counter intuitive.
Next, you shouldnt be using client_credentials in your SPA, those are secret credentails, and should only be used by your server. By exposing those credentials in your SPA, any user could extract them and use them to read your entire directroy store. This is why you are getting a CORS error, it's never supposed to be running on the client browser.

Related

Azure ADB2C multiple Web APIs authentication

My scenario is related to the authentication of two or more web APIs from the same MVC Web App in which ADB2C is configured.
I have created two web apis in Azure ADB2C and granted permissions of both the web apis into ADB2C MVC web app. However whenever I tried to obtain the access token, it is giving me the access token for one web api but not giving the access token for the second one.
I want to know whether this scenario is possible in ADB2C or not?
Thanks.
One access token could be used to access by one resource(web api) . If you want another resource's access token , you can use refresh token(if exists) to get the new token :
https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow#refresh-the-access-token
If using MSAL.NET ,after initial token acquisition , you can invoke AcquireTokenSilent, asking for the api scopes you need :
// Retrieve the token with the specified scopes
var scope = AzureAdB2COptions.ApiScopes.Split(' ');
string signedInUserID = HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;
IConfidentialClientApplication cca =
ConfidentialClientApplicationBuilder.Create(AzureAdB2COptions.ClientId)
.WithRedirectUri(AzureAdB2COptions.RedirectUri)
.WithClientSecret(AzureAdB2COptions.ClientSecret)
.WithB2CAuthority(AzureAdB2COptions.Authority)
.Build();
new MSALStaticCache(signedInUserID, this.HttpContext).EnablePersistence(cca.UserTokenCache);
var accounts = await cca.GetAccountsAsync();
AuthenticationResult result = await cca.AcquireTokenSilent(scope, accounts.FirstOrDefault())
.ExecuteAsync();
MSAL will look up the cache and return any cached token which match with the requirement. If such access tokens are expired or no suitable access tokens are present, but there is an associated refresh token, MSAL will automatically use that to get a new access token and return it transparently.
You can click here for code sample .

Authorization between nuxtjs and the backend API

I have a Vuejs application created using Nuxtjs. I am also using Django as the backend server, and I made an API to interact with the backend server (Django) and front-end app (Vuejs/Nuxtjs). And any API related fetch are done in the AsyncData function of the page to render the data on the server-side using axios. Also, I am using json web token authentication, and the API generates a jwt token after successful login which is stored in the cookie. So on the backend, it will always check for the request's authorization header for the token. If the request is from a logged in user (authorized token) then return authenticated json data, or else return non authenticated data.
The problem:
When the user navigates to the app, I would like to check if the user is authenticated. If the user is authenticated, render the authenticated page. If not then display non authenticated page.
My thoughts:
When the fetch is done from the App on the AsyncData function, I would check whether there is any value for the cookie. If there is then send the token with the request's authorization header. But, since the page will be rendered on the server first, and not on the client side (where the cookie actually is) it will never find the token for the authorization.
How can I check if the user is already logged in or not so that I can get authenticated and non authenticated data respectively from the API?
Update
When I successfully log in (post authorized email and password), I get a json response back with the token, which I set in the cookie like this:
this.$cookie.set('my_auth_token', this.token, {expires: 15})
How can I retrieve client side cookie and into the nuxt server for server side rendering?
Cookies are exposed in the (Express) Nuxt server through middleware.
Specifically, they can be read from the req.headers.cookie property. You can see an example implementation of this in the Nuxt documentation.
Regarding your implementation: fetching the privileged data from your API using Node would seem to be the ideal way to delegate session handling to that single service (rather than both) and provide SSR for your users.
If you've chosen to instead implement your session handling on the Django service then you'll need to "forward" your cookies by passing them into your axios request headers.
I did something similar using Firebase authentication. There is an example project on Github as well as a blog entry outlining the important files and configuration used in the application.

How do I read Passport.js user info on client side?

My app is using Angular2 for the front-end, served by a separate (cross domain) backend server running express and using passport.js for Google Oauth authentication.
When a user is authenticated by the server using Passport (through google oauth), their user data is loaded from the database and included in the credentials, which is used to determine which backend API routes they are authorized to use. (It's based off this tutorial on scotch.io that I'm sure everyone has seen: https://scotch.io/tutorials/easy-node-authentication-setup-and-local )
I want to access this user object in my front-end as well to enable route-guards that depend on a user's access level (defined in their user object on the server).
From this question it seems the data is sent via a JWT and is readable on the front-end, just not changeable, which is fine: https://www.reddit.com/r/Angular2/comments/4ud0ac/ng2_secure_connection_front_to_back/
How do I access and read that token on the client? All I can find is the 'connect.sid' session cookie set by express. The payload of the cookie doesn't fit a standard JWT as it only has 2 sections, not 3.
You are probably not using JWT but cookie-based sessions if you followed the tutorial. The cookie only contains a session ID which your server uses to identify the session from the session store, and using this information you probably dig up something from the database in deserializeUser. That is then available to you in req.user in the backend.
You could of course add the user data to the response of every request but if you really are using cookie-based sessions sending the user object with every response likely makes little sense. You could eg. just add a route that will return the relevant parts of req.user:
app.get('/users', function(req, res) {
res.json({ username : req.user.username });
);

User authentication and login flow with Ember and JSON web tokens

I'm trying to figure out how is best to do authentication and login flow with Ember. I'll also add that this is the first web app I've built so it's all a bit new to me.
I have an Express.js backend with protected endpoints using JWTs (I'm using Passport, express-jwt and jsonwebtoken for that) and that all works.
On the client-side, I'm using Ember
Simple Auth with the JWT authenticator. I have the login flow working (I'm using the login-controller-mixin) and correctly see the isAuthenticated flag in the inspector after a successful login.
The thing I'm struggling with is what to do after login: once a user logs in and gets the token, should I make a subsequent call to get the user details, e.g. GET /me, so that I can then have a representative user model client side? These details would then let me transition to the appropriate route.
See this example in the repo for an example of how to add a property to the session that provides access to the current user.

OWIN/OAuth2 3rd party login: Authentication from Client App, Authorization from Web API

I am trying to create a Web API that allows the API's clients (native mobile apps) to login using a 3rd party cloud storage provider. I'm using the following general flow from Microsoft:
Here is what I am trying to achieve:
I am using the default ASP.NET Web API Visual Studio template with external authentication, along with the OWin.Security.Providers Nuget package for Dropbox login functionality, and the existing built-in login functionality for Google (Drive) and Microsoft (OneDrive).
The issue I'm having is that the built-in functionality all seems to do the authentication and authorization as part of one flow. For example, if I set up the following in Startup.Auth.cs:
DropboxAuthenticationOptions dropboxAuthOptions = new DropboxAuthenticationOptions
{
AppKey = _dropboxAppKey,
AppSecret = _dropboxAppSecret
};
app.UseDropboxAuthentication(dropboxAuthOptions);
... and navigate to this url from my web browser:
http://<api_base_url>/api/Account/ExternalLogin?provider=Dropbox&response_type=token&client_id=self&redirect_uri=<api_base_url>
I am successfully redirected to Dropbox to login:
https://www.dropbox.com/1/oauth2/authorize?response_type=code&client_id=<id>&redirect_uri=<redirect_uri>
... and then after I grant access, am redirected back to:
http://<api_base_url>/Help#access_token=<access_token>&token_type=bearer&expires_in=1209600
... as you can see the token is part of that, so could be extracted. The problem is that the client needs to be the one navigating to Dropbox and returning the authorization code back up to the Web API, and the Web API would send the authorization code back to the third party to get the token which would then be returned to the client... as shown in the diagram above. I need the ExternalLogin action in the AccountController to somehow retrieve the Dropbox url and return that to the client (it would just be a json response), but I don't see a way to retrieve that (it just returns a ChallengeResult, and the actual Dropbox url is buried somewhere). Also, I think I need a way to separately request the token from the third party based on the authorization code.
This post seems a little similar to what I am trying to do:
Registering Web API 2 external logins from multiple API clients with OWIN Identity
... but the solution there seems to require the client to be an MVC application, which is not necessarily the case for me. I want to keep this as simple as possible on the client side, follow the flow from my diagram above, but also not reinvent the wheel (reuse as much as possible of what already exists in the OWIN/OAuth2 implementation). Ideally I don't want the client to have to reference any of the OWIN/OAuth libraries since all I really need the client to do is access an external url provided by the API (Dropbox in my example), have the user input their credentials and give permission, and send the resulting authorization code back up to the api.
Conceptually this doesn't sound that hard but I have no idea how to implement it and still use as much of the existing OAuth code as possible. Please help!
To be clear, the sample I mentioned in the link you posted CAN be used with any OAuth2 client, using any supported flow (implicit, code or custom). When communicating with your own authorization server, you can of course use the implicit flow if you want to use JS or mobile apps: you just have to build an authorization request using response_type=token and extract the access token from the URI fragment on the JS side.
http://localhost:55985/connect/authorize?client_id=myClient&redirect_uri=http%3a%2f%2flocalhost%3a56854%2f&response_type=token
For reference, here's the sample: https://github.com/aspnet-security/AspNet.Security.OpenIdConnect.Server/tree/dev/samples/Mvc/Mvc.Server
In case you'd prefer a simpler approach (that would involve no custom OAuth2 authorization server), here's another option using the OAuth2 bearer authentication middleware and implementing a custom IAuthenticationTokenProvider to manually validate the opaque token issued by Dropbox. Unlike the mentioned sample (that acts like an authorization proxy server between Dropbox and the MVC client app), the JS app is directly registered with Dropbox.
You'll have to make a request against the Dropbox profile endpoint (https://api.dropbox.com/1/account/info) with the received token to validate it and build an adequate ClaimsIdentity instance for each request received by your API. Here's a sample (but please don't use it as-is, it hasn't been tested):
public sealed class DropboxAccessTokenProvider : AuthenticationTokenProvider {
public override async Task ReceiveAsync(AuthenticationTokenReceiveContext context) {
using (var client = new HttpClient()) {
var request = new HttpRequestMessage(HttpMethod.Get, "https://api.dropbox.com/1/account/info");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", context.Token);
var response = await client.SendAsync(request);
if (response.StatusCode != HttpStatusCode.OK) {
return;
}
var payload = JObject.Parse(await response.Content.ReadAsStringAsync());
var identity = new ClaimsIdentity("Dropbox");
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, payload.Value<string>("uid")));
context.SetTicket(new AuthenticationTicket(identity, new AuthenticationProperties()));
}
}
}
You can easily plug it via the AccessTokenProvider property:
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions {
AccessTokenProvider = new DropboxAccessTokenProvider()
});
It has its own downsides: it requires caching to avoid flooding the Dropbox endpoint and is not the right way to go if you want to accept tokens issued by different providers (e.g Dropbox, Microsoft, Google, Facebook).
Not to mention that if offers a very low security level: since you can't verify the audience of the access token (i.e the party the token was issued to), you can't ensure that the access token was issued to a client application you fully trust, which allows any third party developer to use his own Dropbox tokens with your API without having to request user's consent.
This is - obviously - a major security concern and that's why you SHOULD prefer the approach used in the linked sample. You can read more about confused deputy attacks on this thread: https://stackoverflow.com/a/17439317/542757.
Good luck, and don't hesitate if you still need help.