Azure Mobile Services token validation in Web API and MVC - c#

I have a Xamarin mobile app that uses the Azure Mobile Services SDK to authenticate a user against social providers. I get the token and attach it to http request hitting my Web API ASP.NET application (that I'm deploying as an Azure Cloud Service) as a bearer token.
I need to validate the bearer token and get a ClaimsIdentity to work with in my ApiController. Do I need to use the Mobile Service .NET Backend nuget packages for this? How can I?
EDIT:
Created an empty ASP.NET application Added a Web API controller
Installed Mobile Services .NET Backend nuget package
Set appsettings values for keys MS_MobileServiceName, MS_MasterKey,
MS_ApplicationKey from values in Azure Management Console
Set [AuthorizeLevel(AuthorizationLevel.User)] on my HttpGet operation
in my ApiController
Cast User to ServiceUser
Create http request with bearer token from Google Auth thru Azure
Mobile Service SDK
User is null!

Use attributes such as
[AuthorizeLevel(AuthorizationLevel.Anonymous)]
[AuthorizeLevel(AuthorizationLevel.User)]
On the methods in your API to validate depending on which role you want.
Then use
var currentUser = User as ServiceUser;
to get the current user in the method, if the AuthorizationLevel is not Anonymous.
And setup your AppSettings as necessary. Change the MasterKey and ApplicationKey if you are testing the MobileService on localhost.
<appSettings>
<!-- Use these settings for local development. After publishing to
Mobile Services, these settings will be overridden by the values specified
in the portal. -->
<add key="MS_MobileServiceName" value="[NAME HERE]" />
<add key="MS_MasterKey" value="[INSERT HERE]" />
<add key="MS_ApplicationKey" value="[INSERT HERE]" />
<add key="MS_MicrosoftClientID" value="Overridden by portal settings" />
<add key="MS_MicrosoftClientSecret" value="Overridden by portal settings" />
<add key="MS_FacebookAppID" value="Overridden by portal settings" />
<add key="MS_FacebookAppSecret" value="Overridden by portal settings" />
<add key="MS_GoogleClientID" value="Overridden by portal settings" />
<add key="MS_GoogleClientSecret" value="Overridden by portal settings" />
<add key="MS_TwitterConsumerKey" value="Overridden by portal settings" />
<add key="MS_TwitterConsumerSecret" value="Overridden by portal settings" />
<add key="MS_AadClientID" value="Overridden by portal settings" />
<add key="MS_AadTenants" value="Overridden by portal settings" />
<!-- When using this setting, be sure to also set the Notification Hubs connection
string named "MS_NotificationHubConnectionString". -->
<add key="MS_NotificationHubName" value="Overridden by portal settings" />
<add key="Microsoft.ServiceBus.ConnectionString" value="Endpoint=sb://[your namespace].servicebus.windows.net;SharedSecretIssuer=owner;SharedSecretValue=[your secret]" />
</appSettings>

Related

Windows authentication doesn't work after deploy on iis

I have a problem with this simple piece of code:
public void OnAuthorization(AuthorizationFilterContext context)
{
ClaimsPrincipal user = _httpContextAccessor.HttpContext.User;
ClaimsIdentity identity = user.Identity as ClaimsIdentity;
string userName = identity.Name; //!!!
_logger.Trace("windows user `{0}` is trying to access the system", userName);
var admins = _configurationRoot.GetSection(ConfigDescription.Admins).Get<List<string>>();
if (!admins.Contains(userName))
{
_logger.Trace("Permission denied.");
context.Result = new RedirectResult("/error/unauthorized", false);
}
}
When I launch my asp net app via IIS Express in Visual Studio everything works fine. My logs in this case:
2021-12-25 22:02:53.1783 TRACE windows user `Domain\username` is trying to access the system.
But userName is always empty after publishing on remote IIS.
2021-12-25 19:11:55.2524 TRACE windows user `` is trying to access the system.
2021-12-25 19:11:55.2524 TRACE Permission denied.
I was trying open website from localhost and via domain name, also added it into Trusted Sites, nothing helped.
web.config :
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<location path="." inheritInChildApplications="false">
<system.webServer>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath="dotnet" forwardWindowsAuthToken="true" arguments=".\BlaBla.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="inprocess" />
</system.webServer>
</location>
</configuration>
Anonymous Authentication is enabled on IIS
Because if not, I can't open even error/unauthorized page like this:
To enable windows authentication in IIS need to make sure the followings
Enable Windows Authentication in IIS
Enable Windows Authentication in IIS web application
1. Enable Windows Authentication in IIS
we need to enable Windows Authentication in “Windows features” (Run command : optionalfeatures . Win + R → optionalfeatures)
2. Enable Windows Authentication in IIS web application
Then we need to Enable windows authentication for applications. Can be done in web.config as below or in IIS
web.config
<system.webServer>
<security>
<authentication>
<windowsAuthentication enabled="true" />
<anonymousAuthentication enabled="false" />
</authentication>
</security>
</system.webServer>
IIS
Select the application in left node and select "Authentication" in feature view
Enable Windows Authentication and Disable anonymous Authentication.
More information
IIS Windows Authentication
Windows Authentication in ASP.NET Core

Embedding PowerBI Dash Board/Report into Web application

I am trying to embed power BI Dash Board report into Web application.
1) I have configured the application using this Microsoft link and their sample application from github https://learn.microsoft.com/en-us/power-bi/developer/embed-sample-for-your-organization.
2) I have also tried configuring using this documentation https://bitbucket.org/omnistream/powerbi-api-example\
I am accessing the end point with my company email id /password . below is the details. i have admin rights on dash board report and I have power BI pro user account.
Post End point: https://login.microsoftonline.com/common/oauth2/token
Request Header :
User-Agent: Fiddler
Host: login.windows.net
content-Type: application/x-www-form-urlencoded
Content-Length: xxx
with request body :
grant_type=password&scope=openid&username=myUserName#mycompany.com&password=MyPassword&client_id=XXXXX&resource=https://analysis.windows.net/powerbi/api&client_secret=XXXXX
it throws below error:
error_description=AADSTS70002: Error validating credentials. AADSTS50126: Invalid username or password
Trace ID: c13c59dc-79e2-4169-bae2-06c402310100
Correlation ID: a747a226-362a-45aa-956a-122629fa9863
Timestamp: 2018-08-06 21:27:59Z
Do i need to configure or create Master Power BI account separately ?
or if my company network interfering with Post request to mask the user id/password, is there any tool which can help me to trace this network issue?
Even after Bypassing the company proxy for credentials it was not working.
finally, I logged the ticket with Microsoft and able make it work for only one of the option i.e. Native application. Below is the step
1) Download 'App owns data ' application from here. And Register your power Bi application in Azure Portal as "Native application" for Application Type. Visit the link #1 in question for details about configuring PowerBI application web page embedding.
2) Open project and import all required Dll using NUget package manager.
3) configure cloud.config with these values in project.
<appSettings>
<add key="authorityUrl" value="https://login.microsoftonline.com/common/oauth2/authorize/" />
<add key="resourceUrl" value="https://analysis.windows.net/powerbi/api" />
<add key="apiUrl" value="https://api.powerbi.com/" />
<add key="embedUrlBase" value="https://app.powerbi.com/v1.0/myorg/" />
</appSettings>
4) Configure your web.config file with these values in project.
<appSettings file="Cloud.config">
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
<add key="applicationId" value="xxxxxxx-xxxx-xxxx-xxxx-xxxxxx" /> <!--For PowerBI Native application ID-->
<add key="workspaceId" value="xxxxxxx-xxxx-xxxx-xxxx-xxxxxx" />
<!-- The id of the report to embed. If empty, will use the first report in group -->
<add key="reportId" value="xxxxxxx-xxxx-xxxx-xxxx-xxxxxx" />
<!-- Note: Do NOT leave your credentials on code. Save them in secure place. -->
<add key="pbiUsername" value="XXXXXXXXX#yourcompany.com" />
<add key="pbiPassword" value="xxxxxxxx" />
</appSettings>
5) Publish your report on power BI site , create dash board , fill the report id and work space id in above web.config setting.
6) Execute the application. it should work for Embed report, dashboard and Tile types.

C# .net MVC, set path to Google Application Credentials JSON file

I've just got this Google Sample Project to work on my VS2015,
However, after I published to "IIS" and host it, when I opened the link, the web page kept showing this message as the picture showed
I added the key to the web.config, but still doesn't work, just wondering if anyone had done this before, I really need help, thank you!
Edit: Here is my code
Web.Config
<appSettings>
<!-- Set to your Google project id as shown on the Google Developers Console -->
<add key="GoogleCloudSamples:ProjectId" value="gdtest-1332" />
<add key="GOOGLE_APPLICATION_CREDENTIALS" value="D:\ProjectCloud\gdtest-12323.json" />
<!--
Set to either mysql or datastore.
If using mysql, update the connectionString far below, and then run Update-Database in the
Package Manager Console.
-->
<add key="GoogleCloudSamples:BookStore" value="datastore" />
<!-- Set to your Google Cloud Storage bucket -->
<add key="GoogleCloudSamples:BucketName" value="cloudstoragetestbillez" />
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
Programmatically set an environment variable at runtime as such:
string credential_path = #"C:\..\key.json";
System.Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", credential_path);
I'm not an expert with IIS but it won't seem to pick up on environment variable set in your desktop environment.
Restarting the Visual Studio 2017 did it for me for Console Application.
Console.WriteLine(System.Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS"));
From google documention it seems it is env var and not web.config.
If you are using a service account credential, set the environment variable GOOGLE_APPLICATION_CREDENTIALS to the path to the JSON credential file you downloaded.
With command prompt:
set GOOGLE_APPLICATION_CREDENTIALS=[PATH_JSON]
You don´t need setting credentials on code
Google says:
After creating a service account, you have two choices for providing the credentials to your application. You can either set the GOOGLE_APPLICATION_CREDENTIALS environment variable explicitly, or you can pass the path to the service account key in code.

how to redirect from folder in a web server

i have two different applications, one is a website project running on the the server root, the second is a web application project in a folder, both projects have their configuration files, and i am putting the link in the configuration file of the website project
i am trying to redirect users from the website project to the web application project, whenever i use this:
<add key="CoronaPortalAddress" value="http://localhost/coronaportal/Security/ApplicantSignIn1.aspx?applicationType=" />
<add key="CoronaPortalSignInPage" value="http://localhost/coronaportal/Security/SignIn.aspx" />
<add key="CoronaPortalTimeTablePage" value="http://localhost/coronaportal/Conona Schools_ Trust Council_ApplicantTestScores/TimeTable1.aspx" />
<add key="CoronaPortalResultsPage" value="http://localhost/coronaportal/ParentReportLogin.aspx" />
users will be redirected, though on the url it will showing localhost, so i change it to:
<add key="CoronaPortalAddress" value="http://www.shodsystems.com/coronaportal/Security/ApplicantSignIn1.aspx?applicationType=" />
<add key="CoronaPortalSignInPage" value="http://www.shodsystems.com/coronaportal/Security/SignIn.aspx" />
<add key="CoronaPortalTimeTablePage" value="http://www.shodsystems.com/coronaportal/Conona Schools_ Trust Council_ApplicantTestScores/TimeTable1.aspx" />
<add key="CoronaPortalResultsPage" value="http://www.shodsystems.comcoronaportal/ParentReportLogin.aspx" />
now it throwing error:
It is an error to use a section registered as allowDefinition='MachineToApplication' beyond application level. This error can be caused by a virtual directory not being configured as an application in IIS
i tried to google this, but couldnt fix it, any assistance would be appreciated.

Xamarin : debugging application with local instance on Azure Mobile App Service

I'm using Xamarin.Forms application with Azure Mobile App as backend service.
How can I debug with local instance of the service?
Tried following, but returns error :
public const string applicationURL = #"http://192.168.0.4:59996/";
public const string gatewayURL = #"";
public const string applicationKey = #"Overridden by portal settings";
public static MobileServiceClient client = new MobileServiceClient (
Constants.applicationURL, Constants.gatewayURL,
Constants.applicationKey);
Error thrown is :
System.Net.WebException: Error: ConnectFailure (Connection refused) ---> System.Net.Sockets.SocketException: Connection refused
Following are the keys in Mobile App service:
<add key="MS_MobileServiceName" value="XXXMobileApp" />
<add key="MS_ApplicationKey" value="Overridden by portal settings" />
<add key="MS_MasterKey" value="Overridden by portal settings" />
<add key="MS_SigningKey" value="Overridden by portal settings" />
<add key="EMA_MicroserviceID" value="XXXMobileApp" />
<add key="EMA_RuntimeUrl" value="https://groupa2edxxx.azurewebsites.net" />
<add key="EMA_Secret" value="Overridden by portal settings" />
How should I define the client in Xamarin?
PS: The local host service is running in debug mode.
My issue was that the localhost IISExpress was not accessible from any other device. Had to configure IISExpress based on following article:
https://azure.microsoft.com/en-us/documentation/articles/mobile-services-dotnet-backend-how-to-configure-iis-express/
I'm still facing an error but this could be unrelated to this question. (More update on this later perhaps)
Microsoft.WindowsAzure.MobileServices.MobileServiceInvalidOperationException: The request could not be completed. (Unauthorized)

Categories