Authorization based on multiple scopes in C# web API ( scopes based authorization ) using policies - endpoint

I am posting this to share information to Authorization in C# WEB API using multiple scopes.
After posting this user-defined I got a simple answer from https://stackoverflow.com/users/4830196/ryan-wilson
Thank you Ryan-Wilson for commenting your answer instead of just ignoring question.
i.e
options.AddPolicy("ReadPolicy", policy => {
policy.RequireClaim("scope","scope1","scope2");
});
Authorizing based on a single scope I found reference from https://docs.duendesoftware.com/identityserver/v5/apis/aspnetcore/authorization/
i.e in :
services.AddAuthorization(options =>
{
options.AddPolicy("read_access", policy =>
policy.RequirementClaim("scope", "item1.read");
});
and utilizing it at the end point:
public class DataController : ControllerBase
{
[Authorize(Policy="read_access")]
public async Task<IActionResult> Get()
{
return logic here
}
}
The above only works for single scope i.e item1.read. If we want a logic to make the end point accessible with either of multiple scopes if have written following logic.
options.AddPolicy("ReadPolicy", policy => {
policy.RequireAssertion(context => {
return context.User.HasClaim(c =>
(c.Type == "scope" &&
(c.Value.Contains("item.read") ||
c.Value.Contains("complete.read")
)
));
});
});
Here the scope item1.read means providing scope for only 1st item and scope complete.read means full access.
Hope this might helpful for any of us. Please hit like if this is understandable and useful. If not please share comment on how to improve my skills.
Thank you,
Naveen Devi.

Related

Faking a module in angular 2 test

I have a function in angular 2 service which I would like to test.
service.ts
upload(){
let file = new Transfer();
file.upload(myfile).then( // my callback );
}
I would like to mock Transfer in my test using jasmine. I tried this in my
sevice.spec.ts
import { TransferMock as Transfer } from '../mocks/mocks' to mock it. But it is not working. This is how my test is instantiated .
describe('authentication service' , () => {
beforeEach(() => {
auth = new Service(<any>new HttpMock(), <any>new StorageMock())
});
it('initialize authentication',() => {
expect(auth).not.toEqual(null);
auth.upload('file'); //it fails here
});
})
edit
Transfer is not injected in the service. Only one function uses Transfer . So not injecting can reduce the initial loading time of the app i guess(would be happy to know other opinions) . So I would like to know if there is anyway to mock if its constructed this way ?
edit
Although I had accepted Martin's answer as it is the best practice, it has one issue which can happen when you use ionic-native plugins.If the plugin doesnt have browser support it can fail. In this case it happened when I inject it, with error FileTransfer is not defined . So I am back again, looking for suggestions.
In order to provide a mock for a class in a test, you need to inject the class in your implementation.
In your ngModule add Transfer to your providers. Then simply inject it into your service.
Then in your test you can use { provide: Transfer, useClass: TransferMock } in your TestBed providers.
Update
The primary purpose of Dependency Injection is to make code testable and to allow mocking - faking - stubbing of services.
Update
With Dependancy Injection you can configure a different set of providers for different environments.
For example, if you are running your application in the browser, and in a native mobile environment you can swap out your configuration.
In your module you could have something like this:
const TRANSFER_PROVIDER: any;
if (environment.browser) {
TRANSFER_PROVIDER = Transfer;
} else {
TRANSFER_PROVIDER = { provide: Transfer, useClass: NativeTransfer }
}
...
providers: [ TRANSFER_PROVIDER ]
NativeTransfer could be a simple stub that does nothing but prevent errors, or it could let the user know that this feature is not supported in their browser.

Promises on AWS Lambda function do not resolve/return - Nightmare JS

I am trying to run Nightmare JS on AWS Lambda, but my function always returns null and does not seem to be running any of my async code. Here is my code:
exports.handler = (event, context, callback) => {
console.log('starting....')
const Nightmare = require('nightmare')
const nightmare = Nightmare()
console.log('created Nightmare: ', nightmare)
return nightmare
.goto('https://www.myurl.com')
.exists('[data-selector-element]')
.then((exists) => {
console.log('element exists: ', exists)
if (exists) {
return nightmare.click('[data-selector-element]')
.wait(200)
.evaluate(() => {
const title = document.querySelector('h1.header')
return { title }
})
.then((res) => {
context.success(res)
console.log('success:', res)
callback('success: ')
return res
})
} else {
return 'not present'
}
})
}
The function always returns null, and although this process should take at least a couple of seconds, the function usually ends in around 100ms. The first two console logs (above return nightmare.goto...) are registered by Lambda, but later logs are not.
Is there something I'm doing wrong?
I guess that main reason why you only see one log statement is that exists evaluates to false (or any other value that JavaScript considers to be false). I base this assumption on the fact that the else path of the execution consists of a simple return statement instead of using the Lambda callback function (or context.succeed or context.fail if you use the older version). Not executing the callback may cause the Lambda function to terminate before it has completed (or written the logs).
To verify this in practice, please change the last return statement to
callback(null, 'not present`)
to indicate that the Lambda execution was successful, or
callback('not present`)
if you consider this to be a Lambda error.
Please also consider to update the then part of the success result to something like
.then((res) => {
console.log('success:', res)
callback(null, 'success: ')
})
For more information, please read the Using the Callback Parameter paragraph of the Lambda Function Handler in the AWS docs.
TL;DR - you cannot run Nightmare on Lambda, you can only run it on a regular server where you can install extra dependencies (e.g. web drivers).
This was not working because Nightmare requires various web drivers in order to run, which are not present on Lambda, and as far as I know cannot be installed on Lambda.
There's a long thread on the Nightmare repo here discussing how you CAN run Nightmare headlessly on Linux, but this requires you to install various dependencies, which as far as I'm aware is not possible on Lambda.
Please do leave an answer if you find a way in the future!

scopes with lambda and arguments in Rails 4 style?

I'm wondering how the following is done in Rails 4 or if I just use the Rails 3 approach for using a lambda that can pass an argument the same way with 4 as I do with 3.
I'm pretty new to Rails 3 and trying to work through some samples running Rails 4.
Here is my Rails 3 code:
class Person < ActiveRecord::Base
scope :find_lazy, lambda {|id| where(:id => id)}
end
# In console I can call
Person.find_lazy(1)
So if this is the Rails 4 way is to use the -> {}, that's a lambda, right? scope :all_lazy, -> { select("*") } What if I needed an argument. I tried a few different ideas and get argument errors in the console when using the -> {}.
I think it should be:
scope :find_lazy, -> (id) { where(id: id) }
Ruby has not deprecated the old style of lambda either, so if you feel more comfortable using that by all means go for it.
I don't personally like the stabby lambda's syntax myself but eventually they will probably become the norm so it doesn't hurt to get used to them.
Rails 4, you can do:
scope :find_lazy, -> (id) { where(id: id) }
That was in the old ruby:
:id => id
Better hash:
id: id
guy I was usually using the below programming syntax
scope :find_lazy, -> (id) { where(id: id) }
But when I was reviewing my code using Codacy I found it alerting me about this syntax
Use the `lambda` method for multiline lambdas.
I changed it to be and it working well
scope :find_lazy, lambda {|id|
where(id: id)
}
To support associations:
scope :find_lazy, -> (object) { where(object_id: object.id) }
scope :find_lazy, -> (id) { where(id: id) }
is equivalent with
self.find_lazy(id)
where(id: id)
end
Based on ruby on rails guide: Using a class method is the preferred way to accept arguments for scopes.
There is no reason to use scopes together with lambdas in preference to class methods. It is a matter of personal preference. But, if you want to follow the guidelines, you should use the class method when arguments are involved.

in ember how are view's names determined with respect to the router?

ember rc1. i don't understand how views are automatically instantiated by naming convention wrt their routes.
i have the following resource defined:
this.resource('groups', { path : '/groups' }, function() {
this.resource('received', { path : '/received' }, function() {
this.route('show', { path : '/:asset_link_group_id' });
});
when the router instantiates the view for groups/received/index it looks for a view named ReceivedIndexView. why not GroupsReceivedIndexView ?
the same goes for controllers - it looks for ReceivedIndexController, not GroupsReceivedIndexController. why?
"Routes nested under a resource take the name of the resource plus their name as their route name", from http://emberjs.com/guides/routing/defining-your-routes/
My understanding of the setup is that a route is looked at and then it's parent resource in order to automatically derive the patching. In this way /resource1/sameresourcename/new and /resource2/sameresourcename/new will actually cause problems because it doesn't use the full "tree" to generate these paths/names.
I spent a lot of time researching this as i was having problems understanding the hows and whys of the naming conventions. This is the most informative site I have found in regards to which pieces of the route/resources are picked to create the view/controller/resource name.
From Peter "We intentionally only nest one level deep. The correct solution is what #jamesarosen suggested."
https://github.com/emberjs/ember.js/issues/2086

Is it possible to hide substates from showing up in the URL when using the Ember Router v2?

I would like to have a route substate not show up in the URL, but still be able to take advantage of having a route class on which I can define renderTemplate, model, setupController, etc. hooks. Is this possible with the v2 router? I am using Ember release candidate 2.
Here's an example.
Suppose I have the routes:
/exercise/:exercise_id
/exercise/:exercise_id/correct
/exercise/:exercise_id/incorrect
I would like all of these to show up in the URL as:
/exercise/:exercise_id
As I don't want the student to just directly type in /correct onto the end of the ULR and get to the correct answer. And although I have a way to prevent that from working, the full route still shows up in the URL. From the student's perspective, I only want them to think about the state as /exercise/:exercise_id.
Of course I could just store the state correct vs. incorrect in some controller variable, but then I loose the convenience of having route classes, ExerciseCorrectRoute and ExerciseIncorrectRoute, which I want to behave differently, and so the hooks, like renderTemplate and setupController, are nice to have defined cleanly in separate places.
Thoughts?
Kevin
UPDATE:
I went with Dan Gebhardt's suggestion because I like to keep things as much as possible within the framework's considered design cases, as this seems to reduce headaches given Ember is still evolving. Also I didn't get a chance to try out inDream's hack.
Although I still think it would be nice if the router added a feature to mask substates from the URL.
Every route must be associated with a URL for Ember's current router.
Instead of using multiple routes, I'd recommend that you use conditionals in your exercise template to call the appropriate {{render}} based on the state of the exercise. In this way you can still maintain separate templates and controllers for each state.
You can reference to my answer in Ember.js - Prevent re-render when switching route.
Reopen the location API you're using and set window.suppressUpdateURL to true if you want to handle the state manually.
Ember.HistoryLocation:
Ember.HistoryLocation.reopen({
onUpdateURL: function(callback) {
var guid = Ember.guidFor(this),
self = this;
Ember.$(window).bind('popstate.ember-location-'+guid, function(e) {
if(window.suppressUpdateURL)return;
// Ignore initial page load popstate event in Chrome
if(!popstateFired) {
popstateFired = true;
if (self.getURL() === self._initialUrl) { return; }
}
callback(self.getURL());
});
}
});
Ember.HashLocation:
Ember.HashLocation.reopen({
onUpdateURL: function(callback) {
var self = this;
var guid = Ember.guidFor(this);
Ember.$(window).bind('hashchange.ember-location-'+guid, function() {
if(window.suppressUpdateURL)return;
Ember.run(function() {
var path = location.hash.substr(1);
if (get(self, 'lastSetURL') === path) { return; }
set(self, 'lastSetURL', null);
callback(path);
});
});
}
});