Replace basic authentication with Azure AD authentication in Web API - azure-active-directory

I have a Web API that used basic authorization to access the Web API from front end. So we used to pass Authorization header from Frontend Application that contains user login and password in encrypted form and sent to WEB API, where we read authorization header and fetch user login details(UserName, Password) and validate user credentials from Active directory.
Now we are implementing Azure AD integration and we are not able to send user password in Authorization header. So API fails to validate user credentials and it break the flow. Also I am getting httpcontext.current.user as null.see below code
public class UserdataController : ApiController
{
private readonly KMMContext db = new KMMContext(HttpContext.Current?.User?.Identity?.Name ?? "");

You'll need to use MSAL.
A good starting point is here https://learn.microsoft.com/en-us/azure/active-directory/develop/scenario-protected-web-api-overview
Some examples can also be found here. This one is for a javascript/nodejs client since it was not mentioned which frontend framework was used.
https://github.com/Azure-Samples/active-directory-javascript-nodejs-webapi-v2
Basically your WebAPI will now be receiving a JWT token instead of the user credentials.

Related

How to redirect on backend for Angular application using Itfoxtec to access app through Azure Active Directory

I am new to using ITfoxtec for Azure Active Directory SAML logins. I read the StackOverflow entry for Nuget ITfoxtec SAML & Angular (and other similar entries for CORS issues), but I still do not understand how to adapt the GitHub Angular example from https://github.com/ITfoxtec/ITfoxtec.Identity.Saml2 to my needs. When running the ITfoxtec GitHub example, the Login method of the AuthController.cs file is immediately executed when I launch the test Angular application, and brings up the Azure Active Directory login prompt.
For my application, I need to click a "Login using Azure Active Directory" button on the Angular front end to call a backend method that can then redirect to another method to attempt login.
.NetCore C# code:
SSOController.cs file:
// This method is called by an Angular front end button when the user wishes to log in via Azure Active Directory SSO
[AllowAnonymous]
[Route("AzureAuth")]
[HttpGet]
public IActionResult AzureAuth(string returnUrl = null)
{
var binding = new Saml2RedirectBinding();
Saml2Configuration config = GetSamlConfig();
binding.SetRelayStateQuery(new Dictionary<string, string> { { relayStateReturnUrl, returnUrl ?? Url.Content("https://localhost:44397/api/sso/AssertionConsumerService") } });
//return binding.Bind(new Saml2AuthnRequest(config)).ToActionResult();
// This gives a CORS error, so we have do ensure that we do the redirection at the backend
// so we try redirecting with "RedirectToAction"
return RedirectToAction("https://localhost:44397/api/sso/AssertionConsumerService");
}
My AssertionConsumerService() method (located in Dev at "https://localhost:44397/api/sso/AssertionConsumerService"), which I need to be redirected to:
[Route("AssertionConsumerService")]
[HttpPost]
public async Task<IActionResult> AssertionConsumerService(HttpRequestMessage request)
{
// After user enters AAD SSO information, redirect should point to here.
// This API endpoint is hit if I test from Azure Enterprise Application SSO testing with the redirect API set to this method.
// I do not understand how to do backend redirects from AzureAuth() method to this method, and ensure that the HTTP request data is correct.
}
Just a follow up to my own question. For logging in directly from the Angular front end, I am having success with using "#azure/msal-angular". Once the end user clicks the "Log in with Azure Active Directory" button and is authenticated back to the frontend, I forward the authentication details to the backend for authorization checks.
I am still using ITfoxtec at the backend to process what can be directly sent from the "Azure Enterprise Applications > Set up single sign on > Test single sign-on with ..." for testing purposes. With the Azure "App registrations > Authentication > Platform Configuration" set to "Single-Page Application", I am making good progress in development and testing.
Sounds like you got a solution.
You can load the Angular application before login if it is hosted a place in the ASP.NET application that do not require the user to be authenticated. Then you can start the login process your selv and validate if the user is authenticated.

Generate Access Token for SPFX SSO Azure AD using C# without prompting user(Automate)

I have developed SPFX application with Azure AD SSO is enabled. It is also connecting to web api using bearer token generated using ADAL OAuth2 implicit flow along with SPFX SSO access token. This is working fine.
I want to test the webapi using Postman. Currently i am copying bearer token from developer tool of browser and send it in header to connect webapi.
I want to automate the above 2 steps, so that i can do automate user testing scenario.
1.Generate AZURE AD SSO access token from C#/postman by passing user credentials. (Postman/React/C#)
2.Generate bearer token using Access Token generated from step-1.(Postman/React/C#).
I want to automate the above steps using Postman/C#/angular/react.
Kindly provide me the detailed steps to achieve the above scenario for testing.
Suresh Rajamani
I have tested in my environment.
Open Postman --> Create a new request --> Go to Authorization --> Select Type as OAuth 2.0 --> Under Configure New Token, fill the details :
Token Name : give the token name
Grant Type : Implicit
Callback URL : redirect uri of your app registration
Auth URL : https://login.microsoftonline.com/common/oauth2/v2.0/authorize
Client ID : Client ID of your app registration
Scope : add scope as per the permissions required. For ex: https://graph.microsoft.com/mail.read, for reading mails
Client Authentication : send as Basic Auth Header
Click on Get New Access Token and login with user credentials and give consent. A new Bearer Token will be generated
Click on Use Token. Now we can make any requests using that token.

IdentityServer4 - Calling API from IProfileService implementation

I'm working on an MVC web project which is using IdentityServer4 to authenticate users, the web app then uses an access token provided to a user by IdentityServer (authorization code flow) to call an API. The IdentityServer has been configured to use Azure AD as an external identity provider, which is the primary mechanism for users to login. That's all working great.
Once authenticated, I need to query the web app's database to determine:
If the user account is authorised to login
Retrieve claims about the user specific to the application
The IdentityServer docs (http://docs.identityserver.io/en/latest/reference/profileservice.html) suggest implementing the IProfileService interface for this, which I've done. I want the ProfileService to call the web app's API to retrieve the information about the user to avoid forcing the IdentityServer to need to know about/directly access the database. My problem however, is that calling the API though needs an access token.
Is it possible to retrieve the token for the current user inside the ProfileService's IsActiveAsync / GetProfileDataAsync methods? I can't find solid documentation that identifies if the token is even generated at that point. I'm also a total noob when it comes to authentication/authorization, it's a massive topic!
I had the idea of using the client credentials flow inside the ProfileService to call the API, just to populate that initial token. However, I don't know whether or not that's an absolutely terrible idea... or if there are any better concepts someone could refer me to that I could investigate.
Can anyone point me in the right direction?
Have a look at ITokenCreationService that is part of identityserver4. You can inject that service into your IProfileService implementation and then create a new bearer token with any claims you like.
For example:
protected readonly ITokenCreationService _tokenCreationService;
...
var token = new Token
{
AccessTokenType = AccessTokenType.Jwt,
Issuer = "https://my.identityserver.com",
Lifetime = (int)TimeSpan.FromMinutes(5).TotalSeconds,
Claims = GetClaimsNeededForApiCall()
};
string myToken = await _tokenCreationService.CreateTokenAsync(token);
...
This is not possible to retrieve the access_token for a user within ProfileService.
The profile service is called whenever IdentityServer needs to return claims about a user. This means if you try to generate a token for the user within ProfileService it will call the ProfileService again.

How to get user info with a valid Bearer Token?

At work we are making an SPFx Web Part React client app that deploys to SharePoint as a Web Part. Our back-end is a ASP.NET Core 2.2 Web API that is secured using Azure Portal's built in Authentication feature. The front-end is using AadHttpClient that magically handles the authentication by taking the context of the current page (SharePoint) that has the user already logged in. Doing so, silent authentication occurs and the API call is successfully made with authentication successfully passed. The AadHttpClient is supposed to magically bundle up the token in the request header that gets sent to the back-end Web API. I still need to debug the live development app and see how to retrieve the Bearer Token in the back-end Web API. These are my next probable steps?
Would I just probably use 'string bearerToken = Request.Headers.....;' or 'string bearerToken = Request.Headers["KeyValue"]' to get the token itself?
Assuming I can get this Bearer Token, how can I check the caller's user information? Is it just var userName = User.Identity.Name;? Or would I or could I use the token and some how make a call to Microsoft Graph API to view the user's info?
If you are using ASP.NET Core and using default authentication then things are bit easier. From documentation you can see that several tokens are injected in the request header based on Identity provider so in your case you have to look for following headers which Azure AD injects. These headers would contain ID Token which you would need to verify the claims and get user information.
X-MS-TOKEN-AAD-ID-TOKEN
X-MS-TOKEN-AAD-ACCESS-TOKEN
X-MS-TOKEN-AAD-EXPIRES-ON
X-MS-TOKEN-AAD-REFRESH-TOKEN
Ideally all the claims are injected automatically in ClaimsPrincipal
you can find more here
Official Docs
How To extract Token

how to integrate regular username/password login with 3rd party social login for a Spring Boot + Angular single page web app?

I have a Angular + Spring boot single page web app. The server also acts as an Auth Server which issues tokens for the angular app to use to make Restful API calls.
My old login flow uses a grant_type=password POST call to the /oauth/token endpoint to get a Bearer token. And all further API calls on behalf of the user will include the Bearer token as the "Authorization" http header.
Now I need to integrate social login (facebook, twitter, etc.), which means I don't have username/password to generate tokens so I'm not sure how to make it work.
I have been using the following two tutorials as my template:
Spring Security and Angular JS
Spring Boot and OAuth
In the first tutorial's oauth-vanilla example, the username passwork login flow brings up the authorization page. But I'd like to have the traditional username/password form login experience (log user in directly instead of showing the Authorization page).
In the second tutorial, after facebook login, I'd like to use the facebook id to look up my internal user database and create a new user if not exist and logs him in as the user. And use the internal db user's identity and authorities to authorize future API calls to my API server.
I have a stripped down sample at at
https://github.com/dingquan/spring-angular-oauth
I can make POST calls to /oauth/token endpoint and use the returned token to make further api calls to my protected /api/blogs endpoint. But I haven't figure out how to make the following things work:
Username/password login that will create a session cookie so I don't need to send the Authorization bearer token for future API calls to the resource endpoint
After facebook login (the facebook login link is under the username/password login form), calls to my endpoint still fails with 401 error (I have a "test" button that makes a get call to /api/blogs, you can click on it to see the behavior). So what am I missing to make the API call succeed?
=== UPDATE ===
Just to clarify. Here are the goals I'm trying to achieve:
multiple ways of authentication (traditional username/password, third party oauth login such as facebook, possibly cellphone number + SMS code in the future)
we do need our own user model backed by DB to store other user attributes, pure social login is not enough
social login needs to be implicit. Meaning user should not be required to create a user account in our system manually once they login through a 3rd party (facebook, etc.). We're not just grabbing users' social profile data to pre-populate the registration form. We want to create new DB users automatically behind the scene if no existing db user is associated with the given external social account. i.e. if user is logged in through facebook, they don't need to enter username/password. Authentication through facebook will automatically log the user into our system as well and user should be able to access restricted resources after facebook login.
There's some confusion that I might be asking people to put their facebook username/password in a login form hosted by my app and I'll login facebook on behalf of the user. That's not what I was asking for.
You don't need such a complicated configuration. Add #EnableOAuth2Sso to your MainConfiguration and set appropriate application properties.
Here is what I have done in order to use Facebook as a authorization server.
a) Remove clientId and authServer from UserServiceImpl. Otherwise you'll be forced to configure an authorization server that is not needed.
b) Remove AuthorizationServerConfiguration completely.
c) Add #EnableWebSecurity and #EnableOAuth2Sso to your MainConfiguration.
d) Change MainConfiguration::configure to
http
.logout().logoutSuccessUrl("/").permitAll().and()
.authorizeRequests().antMatchers("/", "/login", "/home.html").permitAll()
.anyRequest().authenticated()
.and().csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
e) Delete everything else except nested class AuthenticationSecurity from MainConfiguration.
f) Change ResourceServerConfiguration::configure(HttpSecurity) to
http.antMatcher("/api/**").authorizeRequests().anyRequest().authenticated();
f) Remove attribute tokenStore and method ResourceServerConfiguration::configure(ResourceServerSecurityConfigurer) from ResourceServerConfiguration.
g) Remove configuration block security and facebook from application.yml. Instead add this
security:
oauth2:
client:
client-id: <CLIENT_ID>
token-name: oauth_token
authentication-scheme: query
client-authentication-scheme: form
access-token-uri: https://graph.facebook.com/oauth/access_token
user-authorization-uri: https://www.facebook.com/dialog/oauth
resource:
user-info-uri: https://graph.facebook.com/me
client-id: <CLIENT_ID>
client-secret: <CLIENT_SECRET>
token-type: code
h) In index.html change login to login.
i) Replace the content of hello.js with this one.
But I'd like to have the traditional username/password form login experience (log user in directly instead of showing the Authorization page).
I would never use a site that requires my credentials without redirecting me to the origin! I don't know you and you are under suspicion being a phishing site.
You should really reconsider your decision.
Btw, I created a pull request with these changes.

Resources