I am creating an Aurelia web project that will consume an API. The API is housed as an Azure Mobile Service. I know I need to add the X-ZUMO Auth header to the request. But, when I instantiate my http client, that header never makes it to the request headers according to the browser dev tools.When I run this in my application, I am presented with a login screen I presume because the X-ZUMO header is not present so the app doesn't have permissions to run. I am running this using gulp which is setting up a local instance of the web application for me. I also tried the external IP address.
Here is my class:
import {HttpClient} from 'aurelia-http-client';
export class WebApi
{
static inject = [HttpClient];
constructor(http)
{
this.http = http;
this.baseUrl = 'https://myProject.azure-mobile.net/';
this.zumoHeader = 'X-ZUMO-APPLICATION';
this.zumoKey = 'zumoKey';
this.client = new HttpClient()
.configure(x => {
x.withBaseUrl(this.baseUrl);
x.withHeader(this.zumoHeader, this.zumoKey);
});
}
// requests will go here
testGet()
{
this.client.jsonp('api/logs?application_id=sessionID&__count=20')
.then(response =>
{
alert(response);
});
}
}
Turns out, you can't use the jsonp method in this instance. The get method(if you're making a get request) is the only way the headers will get added.
After this, I had to make sure the server could handle CORS as well.
import {HttpClient} from 'aurelia-http-client';
export class WebApi
{
static inject = [HttpClient];
constructor(http)
{
this.http = http;
this.baseUrl = 'https://myProject.azure-mobile.net/';
this.zumoHeader = 'X-ZUMO-APPLICATION';
this.zumoKey = 'zumoKey';
this.client = new HttpClient()
.configure(x => {
x.withBaseUrl(this.baseUrl);
x.withHeader(this.zumoHeader, this.zumoKey);
});
}
// requests will go here
testGet()
{
this.client.get('api/logs?application_id=sessionID&__count=20')
.then(response =>
{
alert(response);
});
}
}
Related
I need to retrieve a customer connected to the storefront backend side to reward him in different ways.
I created a plugin that extends the plugin.class of the plugins system.
It fetches the customer on the store api using the route store-api/account/customer then it sends to my backend its identifier. I also resolve the shop_url of the admin api with window.location.protocol and window.location.hostname...
This seems to me not secured or accurate (the domain can be different from the sales channel to the admin api) and I would like to know if it would be possible to fetch a secured unique customer's token that would allow me to resolve both the shop_url and the customer's identifier.
I cannot find anything in the documentation that would help me securing that part of my app.
Thanks.
(Edit)
Here is my actual code to fetch the customer inside the plugin:
import Plugin from 'src/plugin-system/plugin.class';
import StoreApiClient from 'src/service/store-api-client.service';
const storeClient = new StoreApiClient();
const handleUser = (data, request) => {
let unsecuredUserId = null;
if (request.status === 200) {
try {
const user = JSON.parse(data);
unsecuredUserId = user.id || null;
} catch (e) {}
}
doSomethingWith(unsecuredUserId);
}
export default class SaylPlugin extends Plugin {
init() {
storeClient.get('store-api/account/customer', handleUser);
}
}
You have access to the customer object in the twig template, given the user is currently logged-in. Using this fact you can pass customer data to your plugin using data attributes. The plugin base offers automatic parsing of options based on the naming convention.
{% set myPluginData = {
customerId: context.customer.id
} %}
<div data-my-custom-plugin="true"
data-my-custom-plugin-options="{{ myPluginData|json_encode }}">
</div>
class MyCustomPlugin extends Plugin {
init() {
if (this.options.customerId) {
// do something when the customer is logged in
}
}
// ...
}
PluginManager.register('MyCustomPlugin', MyCustomPlugin, '[data-my-custom-plugin]');
I finally found a way to get the things more secured.
My new plugin code:
import Plugin from 'src/plugin-system/plugin.class';
import StoreApiClient from 'src/service/store-api-client.service';
const storeClient = new StoreApiClient();
const handleContext = (data, request) => {
if (request.status === 200) {
try {
const context = JSON.parse(data);
if (context instanceof Object) {
resolveCustomerBackendSide(
context.token,
context.salesChannel.id
);
}
} catch (e) {
console.error(e);
}
}
}
export default class SaylPlugin extends Plugin {
init() {
storeClient.get('store-api/context', handleContext);
}
}
With this context I can resolve the admin api credentials backend side using the sales channel identifier that I save during the app registration process (you will have to allow sales_channel read in the app's manifest). Therefore I fetch the sales channel backend side to retrieve the sw-access-key header and I can finally fetch the store-api backend side to retrieve the customer in a secured way (the token that you get after fetching the store-api/context can be used as sw-context-token header.
I have many services that all need to know the tenant ID from the request (kept in JWT auth token). The request is either GRPC (jwt stored in MetaData) or Graphql (jwt stored in context.headers.authorization).
I would like to be able to force myself not to forget to pass this tenant id when using the services. Ideally I dont want to even have to constantly write the same code to get the info from the request and pass it through. However the only ways I've managed to do it was using:
#Inject(REQUEST) for grpc in the service constructor. This doesn't work for the graphql requests. The only other way I saw was to only return service methods AFTER providing the data, which looks ugly as hell:
class MyService {
private _actions: {
myMethod1() { ... }
}
withTenantDetails(details) {
this._details = details;
return this._actions;
}
}
If I can somehow get the execution context within MyService that would be a good option, and make this easy using:
const getTenantId = (context: ExecutionContext) => {
if (context.getType() === 'rpc') {
logger.debug('received rpc request');
const request = context.switchToRpc().getContext();
const token = request.context.get("x-authorization");
return {
token,
id: parseTokenTenantInfo(token)
};
}
else if (context.getType<GqlContextType>() === 'graphql') {
logger.debug('received graphql request');
const gqlContext = GqlExecutionContext.create(context);
const request = gqlContext.getContext().request;
const token = request.get('Authorization');
return {
token,
id: parseTokenTenantInfo(token)
};
}
else {
throw new Error(`Unknown context type receiving in tenant param decorator`)
}
}
But I can't find any way to get the executioncontext across to the service without also having to remember to pass it every time.
It's possible to inject Request into injectable service.
For that, the Service will be Scope.Request, and no more Singleton, so a new instance will be created for each request. It's an important consideration, to avoid creating too many resources for performance reason.
It's possible to explicit this scope with :
#Injectable({ scope: Scope.REQUEST })
app.service.ts :
#Injectable({ scope: Scope.REQUEST })
export class AppService {
tenantId: string;
constructor(#Inject(REQUEST) private request: Request) {
// because of #Inject(REQUEST),
// this service becomes REQUEST SCOPED
// and no more SINGLETON
// so this will be executed for each request
this.tenantId = getTenantIdFromRequest(this.request);
}
getData(): Data {
// some logic here
return {
tenantId: this.tenantId,
//...
};
}
}
// this is for example...
const getTenantIdFromRequest = (request: Request): string => {
return request?.header('tenant_id');
};
Note that, instead of decode a JWT token in order to retrieve TENANT_ID for each request, and maybe for other service (one per service), an other approach could be to decode JWT one single time, and then add it in Request object.
It could be done with a global Guard, same as authorization guard examples of official docs.
Here just a simple example : (could be merged with a Auth Guard)
#Injectable()
export class TenantIdGuard implements CanActivate {
canActivate(
context: ExecutionContext,
): boolean | Promise<boolean> | Observable<boolean> {
const request = context.switchToHttp().getRequest();
request['tenantId'] = getTenantIdFromRequest(request);
return true; // or any other validation
}
}
For GraphQL applications, we should inject CONTEXT in place of REQUEST :
constructor(#Inject(CONTEXT) private context) {}
You have to set either request inside context, or directly TENANT_ID inside context in order to retrieve it after inside service.
Trying to protect my azure function with a function key (AuthorizationLevel.Function)
My azure function uses signalR.
If I use AuthorizationLevel.Function on negotiate and my other signalR entry points, how can I pass the function key when the javascript code connects to signalR:
function:
public static SignalRConnectionInfo Negotiate(
[HttpTrigger( AuthorizationLevel.Function, "post" )] HttpRequest req,
[SignalRConnectionInfo( HubName = "myHub")] SignalRConnectionInfo connectionInfo,
ILogger log )
{
return connectionInfo;
}
website:
const connection = new signalR.HubConnectionBuilder()
.withUrl('https://<myfunction>.azurewebsites.net')
.configureLogging(signalR.LogLevel.Information)
.build();
connection.start()
.catch(console.error);
It seems HubConnectionBuilder can access the Headers in c# but not in javascript.
I have read Add headers to #aspnet/signalr Javascript client
but the first suggestion appends the key to the url, and when connecting it would append /negotiate to it resulting in an invalid url with https://host/&code=/negotiate.
If it's not possible, any alternate way to protect my signalR function suggested?
(Maybe bearer token as in https://learn.microsoft.com/en-us/aspnet/core/signalr/authn-and-authz?view=aspnetcore-3.1)
Thank you
If you take a look at the documentation of the withUrl method, it allows an options object as a second parameter:
function withUrl(url: string, options: IHttpConnectionOptions)
The type of options is IHttpConnectionOptions, which gives some possibilities:
a) you can provide the implementation of IHttpConnectionOptions.accessTokenFactory, which should return a Bearer token (for this to work, you'd need to manually validate the Bearer token in your Azure Function)
b) you can provide your own HttpClient implemenatation, in which you'd modify the Post request by adding the Azure function key, something like below:
const connection = new signalR.HubConnectionBuilder()
.withUrl('https://<myfunction>.azurewebsites.net', {
httpClient: {
post: (url, httpOptions) => {
const headers = {
...httpOptions.headers,
'x-functions-key': YOUR_AZURE_FUNCTION_KEY,
}
return axios.post(url, {}, { headers }).then((response) => {
return (newResponse = {
statusCode: response.status,
statusText: response.statusText,
content: JSON.stringify(response.data),
})
})
},
},
})
.configureLogging(signalR.LogLevel.Information)
.build()
Sources:
https://learn.microsoft.com/en-us/aspnet/core/signalr/javascript-client?view=aspnetcore-3.1
How to pass Custom Header from React JS client to SignalR hub?
As noted in my answer to the question linked to in this question, you can now do as follows:
const connection = new signalR.HubConnectionBuilder()
.withUrl('https://<myfunction>.azurewebsites.net', {
headers: {'x-functions-key': YOUR_AZURE_FUNCTION_KEY}
})
.build();
ASP.NET Core 2.2 web app using code migrated from full fat MVC app.
My AccountController contains this simple code for its Logout route.
await this.SignInManager.SignOutAsync();
return this.RedirectToAction(nameof(Landing.HomeController.Index), "Home");
But this gives.
No sign-out authentication handler is registered for the scheme 'Identity.TwoFactorUserId'.
Pretty confusing given that I've never mentioned 2FA in my code, and Google login is working.
serviceCollection
.AddIdentityCore<MyUser>(identityOptions =>
{
identityOptions.SignIn.RequireConfirmedEmail = false;
})
.AddUserStore<MyUserStore>()
.AddSignInManager<SignInManager<MyUser>>();
serviceCollection.AddAuthentication(IdentityConstants.ApplicationScheme)
.AddCookie(IdentityConstants.ApplicationScheme, options =>
{
options.SlidingExpiration = true;
})
.AddGoogle(googleOptions =>
{
this.Configuration.Bind("OAuth2:Providers:Google", googleOptions);
googleOptions.ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "sub", "string");
})
.AddExternalCookie();
As a complement to #Luke's answer:
The reason why SignInManager::SignOutAsync() throws is this method will also sign out the TwoFactorUserIdScheme behind the scenes:
public virtual async Task SignOutAsync()
{
await Context.SignOutAsync(IdentityConstants.ApplicationScheme);
await Context.SignOutAsync(IdentityConstants.ExternalScheme);
await Context.SignOutAsync(IdentityConstants.TwoFactorUserIdScheme);
}
(See source code)
Typically, these tree authentication schemes are registered automatically by AddIdentity<TUser, TRole>():
public static IdentityBuilder AddIdentity<TUser, TRole>(
this IServiceCollection services,
Action<IdentityOptions> setupAction)
{
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = IdentityConstants.ApplicationScheme;
options.DefaultChallengeScheme = IdentityConstants.ApplicationScheme;
options.DefaultSignInScheme = IdentityConstants.ExternalScheme;
})
...
.AddCookie(IdentityConstants.TwoFactorUserIdScheme, o =>
{
o.Cookie.Name = IdentityConstants.TwoFactorUserIdScheme;
o.ExpireTimeSpan = TimeSpan.FromMinutes(5);
});
... // other services
}
(See source code )
However, you added the Identity services by AddIdentityCore<>() instead of the AddIdentity<>().
Because the AddIdentityCore<>() doesn't register a TwoFactorUserIdScheme scheme (see source code) automatically, there's no associated CookieAuthenticationHandler for TwoFactorUserIdScheme. As a result, it throws.
How to solve
In order to work with SignInManager.SignOutAsync(), according to above description, we need ensure a <scheme>-<handler> map has been registed for TwoFactorUserIdScheme .
So I change your code as below, now it works fine for me:
serviceCollection.AddAuthentication(IdentityConstants.ApplicationScheme)
.AddCookie(IdentityConstants.ApplicationScheme, options =>
{
options.SlidingExpiration = true;
})
.AddCookie(IdentityConstants.TwoFactorUserIdScheme, o =>
{
o.Cookie.Name = IdentityConstants.TwoFactorUserIdScheme;
o.ExpireTimeSpan = TimeSpan.FromMinutes(5);
})
.AddGoogle(googleOptions =>
{
this.Configuration.Bind("OAuth2:Providers:Google", googleOptions);
googleOptions.ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "sub", "string");
})
.AddExternalCookie();
Also you can create your own SignInManager<MyUser> and override sign out as you need
public class CustomSignInManager : SignInManager<MyUser>
{
public override async Task SignOutAsync()
{
await Context.SignOutAsync(IdentityConstants.ApplicationScheme);
await Context.SignOutAsync(GoogleDefaults.AuthenticationScheme);
}
}
Then change AddSignInManager<SignInManager<MyUser>>() to AddSignInManager<CustomSignInManager>() in your Startup class
serviceCollection
.AddIdentityCore<MyUser>(identityOptions =>
{
identityOptions.SignIn.RequireConfirmedEmail = false;
})
.AddUserStore<MyUserStore>()
.AddSignInManager<CustomSignInManager>();
Do not use the SignOutAsync method on a SignInManager<T> you've injected into the controller. Instead, use the method on the HttpContext which takes a scheme argument. I don't know why.
Below code works for me , use the same AuthenticationScheme that you use while "AddAuthentication" in startup.cs
[HttpGet("signout")]
[AllowAnonymous]
public async Task signout()
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
var prop = new AuthenticationProperties
{
RedirectUri = "/logout-complete"
};
// after signout this will redirect to your provided target
await HttpContext.SignOutAsync(OpenIdConnectDefaults.AuthenticationScheme, prop);
}
[HttpGet("logout-complete")]
[AllowAnonymous]
public string logoutComplete()
{
return "logout-complete";
}
I agree with itminus reply, We would get an error because in .net core 3.0 if we use AddIdentityCore<>() instead of AddIdentity<>() we would get an error. But when upgrading to .net 7.0 if we again use AddIdentityCore<>() instead of AddIdentity<>() we would get the same error for Identity.TwoFactorRememberMeScheme as well that I am faced with after upgrading. For SignInManager we require Identity.TwoFactorRememberMeScheme as well otherwise we get an error.
The solution which I applied in mine .net 7.0 project is:
Instead of adding every scheme and handler by yourself, we can just use
services.AddAuthentication().AddIdentityCookies();
This will add all the schemes handlers for you and at the time of signout we need to should use below:
await HttpContext.SignOutAsync(IdentityConstants.ApplicationScheme);
await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);
await HttpContext.SignOutAsync(IdentityConstants.TwoFactorUserIdScheme);
I have two services running on Azure :
a web service ( angular app / expressjs )
an app service ( aspnet core app )
All the web service does is query the app service for the following endpoint : my-app-service.azurewebsites.net/.well-known/openid-configuration
My app service is setup to allow CORS requests coming from my web service at the code level via the IdentityServer4 dll and as mentioned in many websites I DID ensure CORS settings were neither overridden by web.config or azure CORS management page.
These are my HTTP request headers :
Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate
Host:my-app-service.azurewebsites.net
Origin:http://my-web-service.azurewebsites.net
Pragma:no-cache
Referer:http://my-web-service.azurewebsites.net/
And these are my HTTP response headers
Content-Encoding:gzip
Content-Type:application/json
Date:Fri, 05 Jan 2018 17:22:53 GMT
Server:Kestrel
Set-Cookie:ARRAffinity=da4c4ff244aae03ae3c7548f243f7c2b5c22567a56a76a62aaebc44acc7f0ba8;Path=/;HttpOnly;Domain=Host:my-app-service.azurewebsites.net
Transfer-Encoding:chunked
Vary:Accept-Encoding
X-Powered-By:ASP.NET
As you can see, none of the Access-Control-* headers are present. I have added a custom middleware to the asp.net core app pipeline to trace the response headers and I can clearly see them present.
So somewhere Azure is stripping off my headers and I have no more clues where to look now.
Update #1
I forgot to specify that if everything runs on localhost, it works fine. But it does not on Azure.
Update #2
My identity server 4 code
[...]
using Microsoft.IdentityModel.Tokens;
using IdentityServer4.EntityFramework.Mappers;
using IdentityServer4.EntityFramework.DbContexts;
using IdentityServer4;
namespace My.IdentityServer4
{
public class Startup
{
private const string DEFAULT_DEVELOPMENT_AUTHORITY = "http://localhost:5000/";
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
// [... add db context. identity framework, default token provider]
services.AddMvc();
// Cors ( not required, identity server 4 manages it internally )
//services.AddCors(options =>
// options.AddPolicy("AllowAllOrigins", builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()));
string connectionString = Configuration.GetConnectionString("SQLServer");
var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;
// configure identity server with in-memory stores, keys, clients and scopes
services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddAspNetIdentity<ApplicationUser>()
// this adds the config data from DB (clients, resources)
.AddConfigurationStore(options =>
{
options.ConfigureDbContext = builder =>
builder.UseSqlServer(connectionString,
sql => sql.MigrationsAssembly(migrationsAssembly));
})
// this adds the operational data from DB (codes, tokens, consents)
.AddOperationalStore(options =>
{
options.ConfigureDbContext = builder =>
builder.UseSqlServer(connectionString,
sql => sql.MigrationsAssembly(migrationsAssembly));
// this enables automatic token cleanup. this is optional.
options.EnableTokenCleanup = true;
options.TokenCleanupInterval = 30;
});
services.AddAuthentication()
.AddOpenIdConnect("oidc", "OpenID Connect", options =>
{
//TODO: enable HTTPS for production
options.RequireHttpsMetadata = false;
options.Authority = DEFAULT_DEVELOPMENT_AUTHORITY;
options.ClientId = "app"; // implicit
options.SaveTokens = true;
options.TokenValidationParameters = new TokenValidationParameters
{
NameClaimType = "name",
RoleClaimType = "role"
};
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// [... Some stuff before not useful for this snippet]
// For debug purposes, print out request and response headers
app.UseMiddleware<LogHeadersMiddleware>();
app.UseStaticFiles();
// Cors ( not required, identity server 4 manages it internally )
//app.UseCors("AllowAllOrigins");
app.UseIdentityServer();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
public class LogHeadersMiddleware
{
private readonly RequestDelegate next;
private readonly ILogger<LogHeadersMiddleware> logger;
public LogHeadersMiddleware(RequestDelegate next, ILogger<LogHeadersMiddleware> logger)
{
this.next = next;
this.logger = logger;
}
public async Task Invoke(HttpContext context)
{
await this.next.Invoke(context);
logger.LogInformation(
$"------------------------\r\n" +
$"*** Request headers ****\r\n" +
string.Join("\r\n", context.Request.Headers.OrderBy(x => x.Key)) + "\r\n" +
$"*** Response headers ***\r\n" +
string.Join("\r\n", context.Response.Headers.OrderBy(x => x.Key)) + "\r\n" +
$"------------------------\r\n");
}
}
}
Update #3 - CORS on Azure service app is not set
Any hints ? Thanks
#NoName found the answer to my issue on this thread.
In a nutshell, https has to be enabled on Azure in order to work.
A warning from Azure in the logs would have been appreciated though. I wouldn't have lost days on this :S
CORS on Azure service app is not set.
Actually, Azure website is supposed to manage CORS for you. You just need to set the CORS on the Azure service App. I also find a similar SO thread about it.
The good thing is that you can completely disable this middleware and manage CORS by your own means, you just have to remove every single allowed origin (including *) from the CORS settings blade in the portal.