Currently my app looks at router parameter and logged in user (Principal.Identity) to authorize access to certain resources (e.g: Add student to your class [identity + class id]). However, If I'm not wrong, breeze js support just one bulk save. It seems to be that I will have to open each and every data and run through the validation/authorization. That is fine,
but what I may lose is nice separation of cross cutting concern out side my business logic (as a message handler) (finding what roles user has on the class) and nice Authroize annotation feature (just say what roles are needed). So do I have to trade off or is there better programming model which Breeze JS might suggest?
Update:
My question is more on how to separate the authorization (find assigned roles in message handler + verify if required roles are present by adding authorize attribute to controller methods) logic from business or data access logic. Without breeze, I will inspect the incoming message and its route parameter to fetch all its roles then in my put/post/delete methods I would annotate with required roles. I cannot use this technique with breeze (its not breeze's limitation, its trade off when you go for bulk save). So wanted to know if there is any programming model or design pattern already used by breeze guys. There is something on breeze's samples which is overriding context and using repository pattern, will follow that for now.
Breeze can have as many 'save' endpoints as you want. For example, a hypothetical server implementation might be
[BreezeController]
public class MyController : ApiController {
[HttpPost]
[Authorize(...)]
public SaveResult SaveCustomersAndOrders(JObject saveBundle) {
// CheckCustomersAndOrders would be a custom method that validates your data
ContextProvider.BeforeSaveEntitiesDelegate = CheckCustomerAndOrders;
return ContextProvider.SaveChanges(saveBundle);
}
[HttpPost]
[Authorize]
public SaveResult SaveSuppliersAndProducts(JObject saveBundle) {
...
}
You would call these endpoints like this
var so = new SaveOptions({ resourceName: "SaveWithFreight2", tag: "freight update" });
myEntityManager.saveChanges(customerAndOrderEntities, {
resourceName: "SaveCustomersAndOrder" }
).then(...)
or
myEntityManager.saveChanges(supplierAndProductEntities, {
resourceName: "SaveSuppliersAndProducts" }
).then(...)
Authorization is mediated via the [Authorize] attribute on each of the [HttpPost] methods. You can read more about the [Authorize] attribute here:
http://sixgun.wordpress.com/2012/02/29/asp-net-web-api-basic-authentication/
The proper way to do this IMHO is to separate the endpoint authorization and the database actions authorization.
First, create an entity that manages the grands per controller/method and role. For each method you have a value allowed - not allowed for the specific role. You create a special attribute (subclass of Authorize) that you apply to your controllers (breeze or plain web api) that reads the data and decides whether the specific endpoint can be called for the user/role. Otherwise it throws the Unauthorized exception.
On the breeze side (client) you extend the default adapter settings with a method that adds the authentication headers from identity that you received at login, something like this :
var origAjaxCtor = breeze.config.getAdapterInstance('ajax');
$.extend(true, origAjaxCtor.defaultSettings, Security.getAuthenticationHeaders());
On the server, add a second entity that manages the authorization for the CRUD operations. You need a table like (EntityName, AllowInsert, AllowUpdate, AllowDelete). Add a BeforeSave event on the Context Manager or on the ORM (EF or something else) that loops all entities and applies the policy specified on the table above.
This way you have a clear separation of the endpoint logic from the backend CRUD logic.
In all cases the authorization logic should first be implemented server side and if needed should be pushed to the clients.
The way breeze is implemented and with the above design you should not need more than 1 save endpoint.
Hope it helps.
However, If I'm not wrong, breeze js support just one bulk save.
That is entirely wrong. You have free reign to create your own save methods. Read the docs, it's all there.
Related
I am working on a spring base web application where, we have a few RestControllers and some Request DTO classes. Request DTO contains a token field which needs some validation. So I used spring validators to validate that. After validation, we want to send that field to an external system using another REST API (Just for some kind of analytics logging). The same field is repeated in multiple DTO objects and their controllers. So, I am easily able to define annotations for validators and reuse them across the DTOs. But I am not sure how to process that field after validation succeeds (i.e. call analytics API to consume that field post validation), without mixing it with the core logic of controllers.
Approaches I could think of:
Implement a filter/interceptor and process the field there. But then
there is a limitation that request body can be read only once so I
need to use some alternate ways by creating request wrappers.
Repeat the logic in every controller and it is very error prone as for
every new controller we need to remember to write that code.
But non of these approaches look cleaner. Can someone recommend a better way to achieve that?
Thanks in advance.
You can create a BaseController and implement the method there. Extend this BaseController wherever you need this logging service. Like below.
BaseController.java
class BaseController {
protected void remoteLogging(String name,String token) {
//Calling the remote log services}
}
AppController.java
#Controller
#RequestMapping("register")
public class LeaseController extends BaseController {
#PostMapping("new")
public String new(#Valid #ModelAttribute("registration") Registration registration,BindingResult result){
if(rest.hasErrors(){
remoteLogging("name","token");
}
}
I need to grant permissions for users to call exact actions. And also each permission rule can contain validation rules for action arguments:
[CustomAuth]
public MyController : ApiController
{
[ValidateAccess, ActionName("Myaction")]
public void MyAction([MyTypeAccess] MyType myType)
{
}
}
In my logic i need to check can user call this action and can he call this action with passed MyType value (custom validation).
At the moment i dont see how to get attributes from custom AuthorizeAttribute and i see the solution with Castle interceptors, i'm using for my another purposes (from invocation info)..
Is there a standard way to implement this custom authorization?
Didn't find any direct solution in Web API for this issue.
As i'm using Castle interceptors, i've added a new interceptor on all controllers, which are support auth. Interceptor provide access to invocation and you can retrieve any attribute and value passed to the controller/action.
Validation attribute on an action says you need to apply validation routines on this call, ActionName identifies the type of call (if necessary, in a future this will be moved to an own attribute as action name can differ in legacy controllers for old versions).
If you need to validate action parameters there set of attributes you can use, which identify the type of argument and validation algorithm.
I have an application written using the Spring and Hibernate frameworks. Everything works correctly but I do have one question: if controllers invoke business logic by calling service layer methods, where should certain code go, e.g. in the following code, should the code for setting up a new Person's Role and password be in the controller method processing the AddPerson page's POST request, or in a service layer method?
// Saves addPerson.jsp.
#RequestMapping(value = "/add", method = RequestMethod.POST)
public String postAdd(#ModelAttribute("person") Person person) {
logger.debug("PersonController.postAdd called");
// Create random number for new Person's password.
person.setPassword(String.valueOf(Java_Utils.getRandomNumber()));
// Create role for new Person.
person.setRole("PERSON");
// Add Person.
personService.add(person);
// Set records.jsp
return "redirect:/demo/main/record/list";
}
This is of course only a simple example but I'm curious. The role of PERSON is to satisfy a constraint using Tomcat to prevent user's reaching an authenticated page.
It should be in the service layer. The Controller layer is for handling and translating GUI stuff. But the creation of an user and configure it correct is not GUI stuff it is a business (or technical) use case, therefore one should place it in a service.
`personService.createPersonWithRandomPassword();`
What do you think about exposing domain entities through services? I tried it in an application, but I came to the conclusion that exposing domain model to the client is not such a good idea.
Advantages:
Really easy to transport data from-to client
List item
(De)Serialization is really easy: just put jackson in the classpath and it will handle it. No extra logic is needed.
No need to duplicate entities POJOs. At least in early stages, the API resources will be pretty much the same as the domain model.
Disadvantages:
The API's get very tightly coupled to the model and you can't change the model without affecting the API
Partial responses. There are cases where you don't want to return all the fields of the entities, just some of them. How do you accomplish it?
So, let's take the following REST example. The following API declares that GET on the user resource returns the following information.
GET
/users/12
{
"firstName":"John",
"lastName":"Poe"
"address":"my street"
}
Usually, I would create a User entity, a user service to return the user and a REST controller to serve the request like this:
#RequestMapping("/users/{id}")
public #ResponseBody User getUser(#PathVariable Long id) {
return userService.findById(id);
}
Should I avoid returning the User entity?
If yes, should I create another class and handle myself the mapping between this class and the entity?
Is there a pattern for this?
How to accomplish partial expansion? (i.e. return only the firstName and lastName for the user)
P.S: using #JSONFilter and ObjectMapper to accomplish partial responses seems too heavyweight to me because you loose the beauty of spring data
I have a question regarding Multi-tenancy (with MVC3, EF) and a custom SQL Membership provider.
I have custom User and Roles membership classes created, since I have to include the userId in my application tables along with additional user based attributes. I am now converting this into a multi-tenancy application. We are going for a shared-db, shared-app model. We have a master Tenant table that stores the tenant details (including URL ) and the Tenant_id has been included in every table. And now we're working on the changes to the application itself.
The assumption is that tenants will login using a URL like so: tenantUrl.mybaseURL.com.
I am going to change my custom User Validate methods as per this algorithm:
- User goes to URL to login
- The Account controller logon method calls the Custom validate method passing in user/pwd and the tenantId (which has been looked up from the db using the URL).
- The custom validate method checks if the user/password/tenantId combination are valid.
- If valid, we set the tenant Id in a HttpRequest Object and login the user
- For each db access, we lookup the Request object for the tenandId and use that as a filter.
Edit: This is my TenantContext class, where I will be setting/getting the tenantId
public class TenantContext
{
public static int TenantId
{
set
{
if (!HttpContext.Current.Items.Contains("tenant-code"))
HttpContext.Current.Items.Add("tenant-code", value);
HttpContext.Current.Items["tenant-code"] = value;
}
get {return HttpContext.Current.Items.Contains("tenant-code") ? Convert.ToInt32(HttpContext.Current.Items["tenant-code"]) : -1; }
}
}
The tenantId will be set in the Account Controller Login in the above Context.
Is the above a good way to do this or is there a better way? Anybody see any issues with this I should be aware of?
I have seen an example of the tenantId being stored in AppSettings here Handling data access in multi tenant site. Is this a better way to do it?
Thank You
Your algorithm is perfect and in fact i have been working in this kind of an implementation. I have a suggestion that for you, that you use the custom object to maintain the useridentity across different layers. This will contain the userid, tenantid etc.. as this HttpContext will not be helping you in the case of a WCF service and in the context of a user belonging to a tenant and operating on behalf of another tenant. Hence, it would be a better option to have a UserIdentity object that identifies the user. Also, do send the tenantids to the data access layers and do not infer the tenant id's from the request as it will not be available in all environments.