I am creating a custom controller for an SFCC Commerce Cloud (Demandware) store.
Because I need to have communication with Third-party systems, I created a custom REST API controller to be able to receive some data inside the SFCC.
I created a rest controller in order to receive information by POST.
How can I provide an authentication mechanism for my controller?
The OCAPI provides resources that come protected by default and you can use OAuth for the authentication, but custom controllers are unprotected and I was wondering how to add OAuth or another authentication mechanism.
My controller:
server.post('Test', server.middleware.https, function (req, res, next) {
//Some logic that should be protected...
}
You could use an encrypted parameter on request and add logic to decrypt on your controller.
You could use Private Keys and Certificates to authenticate the Request.
If the request always comes from a particular Domain you can add the certificate. Or add a Public and Private key pair.
server.post('InboundHookRequest', server.middleware.https, function (req, res, next) {
var payload = null,
requestStored = false;
if (verifySignature(req) === true) {
try {
payload = JSON.parse(req.body);
// Do the logic here
} catch (e) {
Logger.error(e);
}
if (requestStored === true) {
okResponse(res);
return next();
}
}
notOkResponse(res);
return next();
});
Then Verify the same in
function verifySignature(req) {
var signature,
algoSupported,
result;
signature = new Signature();
algoSupported = signature.isDigestAlgorithmSupported("SHA256withRSA"); // or other algo
if (algoSupported === true) {
try {
var certRef = new CertificateRef(WEBHOOK_CONFIG.CERT_NAME);
result = signature.verifySignature("YOURINCOMINGREQHEADER", content, certRef, "SHA256withRSA");;
if (result === true) {
return true;
}
} catch (e) {
Logger.error(e); // Certificate doesn't exist or verification issue
}
}
}
return false;
}
Signature : https://documentation.b2c.commercecloud.salesforce.com/DOC2/topic/com.demandware.dochelp/DWAPI/scriptapi/html/api/class_dw_crypto_Signature.html?resultof=%22%53%69%67%6e%61%74%75%72%65%22%20%22%73%69%67%6e%61%74%75%72%22%20
Certificates and Private Keys: https://documentation.b2c.commercecloud.salesforce.com/DOC2/topic/com.demandware.dochelp/content/b2c_commerce/topics/b2c_security_best_practices/b2c_certificates_and_private_keys.html?resultof=%22%70%72%69%76%61%74%65%22%20%22%70%72%69%76%61%74%22%20%22%6b%65%79%73%22%20%22%6b%65%69%22%20
More on Web Service Security : https://documentation.b2c.commercecloud.salesforce.com/DOC2/topic/com.demandware.dochelp/content/b2c_commerce/topics/web_services/b2c_webservice_security.html?resultof=%22%70%72%69%76%61%74%65%22%20%22%70%72%69%76%61%74%22%20%22%6b%65%79%73%22%20%22%6b%65%69%22%20
Related
We have a ASP.Net Core application that authenticates against a standalone Identity Server 4. The ASP.Net Core app implements a few SignalR Hubs and is working fine when we use the self hosted SignalR Service. When we try to use the Azure SignalR Service, it always returns 401 in the negotiation requests. The response header also states that
"Bearer error="invalid_token", error_description="The signature key
was not found"
I thought the JWT-Configuration is correct because it works in the self hosted mode but it looks like, our ASP.Net Core application needs information about the signature key (certificate) that our identity server uses to sign the tokens. So I tried to use the same method like our identity server, to create the certificate and resolve it. Without luck :-(
This is what our JWT-Configuration looks like right now:
services.AddAuthentication("Bearer")
.AddJwtBearer("Bearer", options => {
var appSettings = Configuration.Get<AppSettingsModel>();
options.Authority = appSettings.Authority;
options.RefreshOnIssuerKeyNotFound = true;
if (environment.IsDevelopment()) {
options.RequireHttpsMetadata = false;
}
options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters {
ValidateAudience = false,
IssuerSigningKey = new X509SecurityKey(getSigningCredential()),
IssuerSigningKeyResolver = (string token, SecurityToken securityToken, string kid, TokenValidationParameters validationParameters) =>
new List<X509SecurityKey> { new X509SecurityKey(getSigningCredential()) }
};
options.Events = new JwtBearerEvents {
OnMessageReceived = context => {
var accessToken = "";
var headerToken = context.Request.Headers[HeaderNames.Authorization].ToString().Replace("Bearer ", "");
if (!string.IsNullOrEmpty(headerToken) && headerToken.Length > 0) {
accessToken = headerToken;
}
var queryStringToken = context.Request.Query["access_token"];
if (!string.IsNullOrEmpty(queryStringToken) && queryStringToken.ToString().Length > 0) {
accessToken = queryStringToken;
}
// If the request is for our hub...
var path = context.HttpContext.Request.Path;
if (!string.IsNullOrEmpty(accessToken) && path.StartsWithSegments("/hubs")) {
context.Token = accessToken;
}
return Task.CompletedTask;
}
};
});
Update:
We also have a extended the signalR.DefaultHttpClient in our Angular Client and after playing around a bit, I noticed the application is working fine without it:
export class CustomSignalRHttpClientService extends signalR.DefaultHttpClient {
userSubscription: any;
token: string = "";
constructor(private authService: AuthorizeService) {
super(console); // the base class wants a signalR.ILogger
this.userSubscription = this.authService.accessToken$.subscribe(token => {
this.token = token
});
}
public async send(
request: signalR.HttpRequest
): Promise<signalR.HttpResponse> {
let authHeaders = {
Authorization: `Bearer ${this.token}`
};
request.headers = { ...request.headers, ...authHeaders };
try {
const response = await super.send(request);
return response;
} catch (er) {
if (er instanceof signalR.HttpError) {
const error = er as signalR.HttpError;
if (error.statusCode == 401) {
console.log('customSignalRHttpClient -> 401 -> TokenRefresh')
//token expired - trying a refresh via refresh token
this.token = await this.authService.getAccessToken().toPromise();
authHeaders = {
Authorization: `Bearer ${this.token}`
};
request.headers = { ...request.headers, ...authHeaders };
}
} else {
throw er;
}
}
//re try the request
return super.send(request);
}
}
The problem is, when the token expires while the application is not open (computer is in sleep mode e.g.), the negotiaton process is failing again.
I finally found and solved the problem. The difference of the authentication between "self hosted" and "Azure SignalR Service" is in the negotiation process.
Self Hosted:
SignalR-Javascript client authenticates against our own webserver with
the same token that our Javascript (Angular) app uses. It sends the
token with the negotiation request and all coming requests of the
signalR Http-Client.
Azure SignalR Service:
SignalR-Javascript client sends a negotiation request to our own
webserver and receives a new token for all coming requests against the
Azure SignalR Service.
So our problem was in the CustomSignalRHttpClientService. We changed the Authentication header to our own API-Token for all requests, including the requests against the Azure SignalR Service -> Bad Idea.
So we learned that the Azure SignalR Service is using it's own token. That also means the token can invalidate independently with our own token. So we have to handle 401 Statuscodes in a different way.
This is our new CustomSignalRHttpClientService:
export class CustomSignalRHttpClientService extends signalR.DefaultHttpClient {
userSubscription: any;
token: string = "";
constructor(private authService: AuthorizeService, #Inject(ENV) private env: IEnvironment, private router: Router,) {
super(console); // the base class wants a signalR.ILogger
this.userSubscription = this.authService.accessToken$.subscribe(token => {
this.token = token
});
}
public async send(
request: signalR.HttpRequest
): Promise<signalR.HttpResponse> {
if (!request.url.startsWith(this.env.apiUrl)) {
return super.send(request);
}
try {
const response = await super.send(request);
return response;
} catch (er) {
if (er instanceof signalR.HttpError) {
const error = er as signalR.HttpError;
if (error.statusCode == 401 && !this.router.url.toLowerCase().includes('onboarding')) {
this.router.navigate([ApplicationPaths.Login], {
queryParams: {
[QueryParameterNames.ReturnUrl]: this.router.url
}
});
}
} else {
throw er;
}
}
//re try the request
return super.send(request);
}
}
Our login-Route handles the token refresh (if required). But it could also happen, that our own api-token is still valid, but the Azure SignalR Service token is not. Therefore we handle some reconnection logic inside the service that creates the SignalR Connections like this:
this.router.events.pipe(
filter(event => event instanceof NavigationEnd)
).subscribe(async (page: NavigationEnd) => {
if (page.url.toLocaleLowerCase().includes(ApplicationPaths.Login)) {
await this.restartAllConnections();
}
});
hope this helps somebody
I am making a ktor web application with keycloak as auth.
val keycloakProvider = OAuthServerSettings.OAuth2ServerSettings(
name = CLIENT_NAME,
authorizeUrl = KEYCLOAK_AUTH,
accessTokenUrl = KEYCLOAK_TOKEN,
clientId = CLIENT_ID,
clientSecret = CLIENT_SECRET,
accessTokenRequiresBasicAuth = false,
requestMethod = HttpMethod.Post, // must POST to token endpoint
defaultScopes = listOf("roles")
)
There are multiple endpoints that I want to secure but the redirect URI can only be set to one URL, in the example below it's /login/oauth and /secret.
install(Authentication)
{
oauth("secretOAuth") {
client = HttpClient(Apache)
providerLookup = { keycloakProvider }
urlProvider = { "/secret" }
}
oauth("keycloakOAuth") {
client = HttpClient(Apache)
providerLookup = { keycloakProvider }
urlProvider = { "/login/oauth" }
}
}
Does it make sense to create multiple of these authentication paths like in the example above or would it be bad practice?
The /login/oauth and /secret are pointing to the following routes:
authenticate(keycloakOAuth) {
get("/login/oauth") {
val principal = call.authentication.principal<OAuthAccessTokenResponse.OAuth2>()
?: throw Exception("No principal was given")
createSession(principal)
call.respondRedirect("/")
}
}
authenticate(secretOAuth){
get("/secret")
{
val principal = call.authentication.principal<OAuthAccessTokenResponse.OAuth2>()
?: throw Exception("No principal was given")
createSession(principal)
call.respondHtml {
body{
h1{
+"You accessed secure page!"
}
}
}
}
}
Functionality wise it works, when the user isn't logged in it prompts them with the login window, otherwise they get to see the secret/their session gets created but I'm not sure if this is the correct way of doing it. Is there really no way to change the urlProvider based on the accessed URI? Because then I will have to make an authentication for each protected endpoint and that might be a bit too much.
In your scenario, it's redundant to have multiple authentication configurations for the same provider because a client can acquire an access token with any. I suggest using the authenticate block to just get an access token and save it somewhere. You can use the usual routes for the "secret" resources where you can check a user having an access token.
routing {
authenticate("keycloakOAuth") {
get("/login") {
// The endpoint for user login
}
get("/callback") {
val principal = call.authentication.principal<OAuthAccessTokenResponse.OAuth2>()
if (principal != null) {
// Save access token (principal.accessToken) for further use
} else {
// Something went wrong
}
}
}
get("/secret") {
if (!hasToken()) {
call.respondRedirect("/login")
}
}
}
I just need advise if this is feasible. I am developing an authorization for my Shopify app and I need to somewhat store the access token from shopify auth for future verification of my front-end app.
So the first end-point the shopify is calling is this one:
[HttpGet("install")]
public async Task<IActionResult> Install()
{
try
{
if (ModelState.IsValid)
{
var queryString = Request.QueryString.Value;
var isValid = _shopifyService.VerifyRequest(queryString);
if (isValid)
{
var shopifyUrl = Request.Query["shop"];
var authUrl = _shopifyService.BuildAuthUrl(shopifyUrl,
$"{Request.Scheme}://{Request.Host.Value}/api/shopify/authorize",
Program.Settings.Shopify.AuthorizationScope);
return Redirect(authUrl);
}
}
}
catch (Exception ex)
{
var exceptionMessage = await ApiHelpers.GetErrors(ex, _localizer).ConfigureAwait(false);
ModelState.AddModelError(new ValidationResult(exceptionMessage));
}
ModelState.AddModelError(new ValidationResult(_localizer["InvalidAuthStore"]));
return BadRequest(ModelState.GetErrors());
}
This works fine and the result of this api call will actually redirect to same link to my api, but this one will authorize the app:
[HttpGet("authorize")]
public async Task<IActionResult> AuthorizeStore()
{
try
{
if (ModelState.IsValid)
{
var code = Request.Query["code"];
var shopifyUrl = Request.Query["shop"];
var accessToken = await _shopifyService.AuthorizeStore(code, shopifyUrl).ConfigureAwait(false);
var identity = User.Identity as ClaimsIdentity;
identity.AddClaim(new Claim(Constants.Claims.AccessToken, accessToken));
// genereate the new ClaimsPrincipal
var claimsPrincipal = new ClaimsPrincipal(identity);
// store the original tokens in the AuthenticationProperties
var props = new AuthenticationProperties {
AllowRefresh = true,
ExpiresUtc = DateTimeOffset.UtcNow.AddDays(1),
IsPersistent = false,
IssuedUtc = DateTimeOffset.UtcNow,
};
// sign in using the built-in Authentication Manager and ClaimsPrincipal
// this will create a cookie as defined in CookieAuthentication middleware
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimsPrincipal, props).ConfigureAwait(false);
Uri uri = new Uri($"{Program.Settings.Shopify.RedirectUrl}?token={accessToken}");
return Redirect(uri.ToString());
}
}
catch (Exception ex)
{
var exceptionMessage = await ApiHelpers.GetErrors(ex, _localizer).ConfigureAwait(false);
ModelState.AddModelError(new ValidationResult(exceptionMessage));
}
ModelState.AddModelError(new ValidationResult(_localizer["InvalidAuthStore"]));
return BadRequest(ModelState.GetErrors());
}
So the above api will authorize my app in shopify and will return an access token. The accessToken is the one I want to save in the claims identity with Cookie authentication type(this is without authorizing user credentials). Still no errors at that point and after calling the HttpContext.SignInAsync function, I can still view using debugger the newly added claims.
As, you can see in the code, after assigning claims, I call to redirect the app to front-end link(Note: front-end and back-end has different url)
In my front-end app, I have a Nuxt middleware that I put a logic to check the token received from back-end since I only pass the token to the front-end app using query params. Here's my middleware code:
export default function ({ app, route, next, store, error, req }) {
if (process.browser) {
const shopifyAccessToken = store.get('cache/shopifyAccessToken', null)
if (!shopifyAccessToken && route.query.token) {
// if has token on query params but not yet in cache, store token and redirect
store.set('cache/shopifyAccessToken', route.query.token)
app.router.push({
path: '/',
query: {}
})
// verify access token on the route
app.$axios
.get(`/shopify/verifyaccess/${route.query.token}`)
.catch((err) => {
error(err)
})
} else if (!shopifyAccessToken && !route.query.token) {
// if does not have both, throw error
error({
statusCode: 401,
message: 'Unauthorized access to this app'
})
}
} else {
next()
}
}
In my middleware, when the route has query params equal to token= It calls another api to verify the accessToken saved in my claims identity:
[HttpGet("verifyaccess/{accessToken}")]
public async Task<IActionResult> VerifyAccess(string accessToken)
{
try
{
if (ModelState.IsValid)
{
var principal = HttpContext.User;
if (principal?.Claims == null)
return Unauthorized(_localizer["NotAuthenticated"]);
var accessTokenClaim = principal.FindFirstValue(Constants.Claims.AccessToken);
if (accessToken == accessTokenClaim)
{
return Ok();
}
else
{
return Unauthorized(_localizer["NotAuthenticated"]);
}
}
}
catch (Exception ex)
{
var exceptionMessage = await ApiHelpers.GetErrors(ex, _localizer).ConfigureAwait(false);
ModelState.AddModelError(new ValidationResult(exceptionMessage));
}
ModelState.AddModelError(new ValidationResult(_localizer["InvalidAuthStore"]));
return BadRequest(ModelState.GetErrors());
}
Looking at the code above, it always fails me because the claims identity that I saved on the authorize endpoint was not there or in short the ClaimsIdentity is always empty.
Here's how I register the Cookie config:
private void ConfigureAuthCookie(IServiceCollection services)
{
services.AddAuthentication(option =>
{
option.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
option.RequireAuthenticatedSignIn = false;
})
.AddCookie(options => {
options.ExpireTimeSpan = TimeSpan.FromMinutes(60);
options.SlidingExpiration = true;
options.Cookie.Name = "shopifytoken";
});
services.Configure<CookiePolicyOptions>(options =>
{
options.MinimumSameSitePolicy = SameSiteMode.None;
});
}
and I also put a app.UseAuthentication() and app.UseAuthorization() on my Startup.Configure
Please let me know if this seems confusing so I can revised it. My main goal here is to be able to access that accessToken that I saved in the ClaimsIdentity so that I can verify the token. The reason why I did this because currently the shopify does not have an API for verifying access token. So when a user access my app link like this one http://example.com/?token=<any incorrect token> then they can already access my app.
I have an Angular app that uses Auth0 for authentication, and I'm trying to use checkSession({}, …) to persist a user's session if the token hasn't expired yet.
When I log in with my username/pw that I set up for the site, this works fine when I reload the browser/navigate directly to a resource. However, when I log in using a social provider (such as Google), the checkSession({}, …) call on a page reload returns an error and forces the user to log in again.
Some of the relevant code (mostly from the auth0 tutorial(s)):
export class AuthService {
// Create Auth0 web auth instance
private _auth0 = new auth0.WebAuth({
clientID: AUTH_CONFIG.CLIENT_ID,
domain: AUTH_CONFIG.CLIENT_DOMAIN,
responseType: 'token',
redirectUri: AUTH_CONFIG.REDIRECT,
audience: AUTH_CONFIG.AUDIENCE,
scope: AUTH_CONFIG.SCOPE
});
accessToken: string;
userProfile: any;
expiresAt: number;
// Create a stream of logged in status to communicate throughout app
loggedIn: boolean;
loggedIn$ = new BehaviorSubject<boolean>(this.loggedIn);
loggingIn: boolean;
isAdmin: boolean;
// Subscribe to token expiration stream
refreshSub: Subscription;
constructor(private router: Router) {
// If app auth token is not expired, request new token
if (JSON.parse(localStorage.getItem('expires_at')) > Date.now()) {
this.renewToken();
}
}
...
handleAuth() {
// When Auth0 hash parsed, get profile
this._auth0.parseHash((err, authResult) => {
if (authResult && authResult.accessToken) {
window.location.hash = '';
this._getProfile(authResult);
} else if (err) {
this._clearRedirect();
this.router.navigate(['/']);
console.error(`Error authenticating: ${err.error}`);
}
this.router.navigate(['/']);
});
}
private _getProfile(authResult) {
this.loggingIn = true;
// Use access token to retrieve user's profile and set session
this._auth0.client.userInfo(authResult.accessToken, (err, profile) => {
if (profile) {
this._setSession(authResult, profile);
this._redirect();
} else if (err) {
console.warn(`Error retrieving profile: ${err.error}`);
}
});
}
private _setSession(authResult, profile?) {
this.expiresAt = (authResult.expiresIn * 1000) + Date.now();
// Store expiration in local storage to access in constructor
localStorage.setItem('expires_at', JSON.stringify(this.expiresAt));
this.accessToken = authResult.accessToken;
this.userProfile = profile;
if (profile) {
this.isAdmin = this._checkAdmin(profile);
}
...
}
...
get tokenValid(): boolean {
// Check if current time is past access token's expiration
return Date.now() < JSON.parse(localStorage.getItem('expires_at'));
}
renewToken() {
// Check for valid Auth0 session
this._auth0.checkSession({}, (err, authResult) => {
if (authResult && authResult.accessToken) {
this._getProfile(authResult);
} else {
this._clearExpiration();
}
});
}
}
(This is from a service that is called in many places within the app, including some route guards and within some components that rely on profile information. If more of the app code would be useful, I can provide it.)
Also note: AUTH_CONFIG.SCOPE = 'openid profile email'
So, the issue appears to not have been related to my app at all. When using Social Providers, Auth0 has an explicit note in one of their tutorials that really helped me out:
The issue with social providers is that they were incorrectly configured in my Auth0 dashboard, and needed to use provider-specific app keys.
Important Note: If you are using Auth0 social connections in your app,
please make sure that you have set the connections up to use your own
client app keys. If you're using Auth0 dev keys, token renewal will
always return login_required. Each social connection's details has a
link with explicit instructions on how to acquire your own key for the
particular IdP.
Comment was found on this page: https://auth0.com/blog/real-world-angular-series-part-7/
I have an Anuglar5 spa frontend and ASP.NET Core API. Both secured by Azure AD B2C service. The angular application redirects correctly to the login page and signing in returns a token. When I try to call the API with the token I get;
AuthenticationFailed: IDX10214: Audience validation failed. Audiences: '627684f5-5011-475a-9cbd-55fcdcdf369e'. Did not match: validationParameters.ValidAudience: 'ee8b98a0-ae7a-38b2-9e73-d175df22ef4c' or validationParameters.ValidAudiences: 'null'.
"627684f5-5011-475a-9cbd-55fcdcdf369e" is the Application ID of the frontend app. And "ee8b98a0-ae7a-38b2-9e73-d175df22ef4c" is the Application ID of the API.
My code;
`export class MSALService {
private applicationConfig: any = {
clientID: '627684f5-5011-475a-9cbd-55fcdcdf369e',
authority: 'https://login.microsoftonline.com/tfp/mytenant.onmicrosoft.com/B2C_1_my_signin_signup',
b2cScopes: ['https://meeblitenant.onmicrosoft.com/api/myapp_read', 'https://meeblitenant.onmicrosoft.com/api/myapp_write'],
redirectUrl: 'http://localhost:4200/'
};
private app: any;
public user: any;
constructor() {
this.app = new UserAgentApplication(this.applicationConfig.clientID, this.applicationConfig.authority,
(errorDesc, token, error, tokenType) => {
console.log(token);
},
{ redirectUri: this.applicationConfig.redirectUrl }
);
}
public login() {
let tokenData = '';
this.app.loginRedirect(this.applicationConfig.b2cScopes).then(data => { tokenData = data; });
}
public getUser() {
const user = this.app.getUser();
if (user) {
return user;
} else {
return null;
}
}
public logout() {
this.app.logout();
}
public getToken() {
return this.app.acquireTokenSilent(this.applicationConfig.b2cScopes)
.then(accessToken => {
console.log(accessToken);
return accessToken;
}, error => {
return this.app.acquireTokenPopup(this.applicationConfig.b2cScopes)
.then(accessToken => {
return accessToken;
}, err => {
console.error(err);
});
}
);
}
}`
Using the token that is returned in Postman also returns the same error. My theory is that the URL I am using to call Azure AD B2C is the problem but looking through the docs I cannot find the problem.
Any help would be greatly appreciated.
Kinda sounds like you are sending the Id token to the API (which is meant for your front-end) instead of an access token. You can debug the issue further by decoding the token you get at https://jwt.ms.
There the aud (audience) should match your API's id, and the scopes you asked should also be there.