Checking roles from some group Micronaut Security - security

There is a controller with an edit object endpoint.
#Secured(SecurityRule.IS_AUTHENTICATED)
public class Controller
#PUT
#Secured(MODIFY) // Security Mapping for requests
public CompletableFuture<ModifyResponse> update(#NotBlank List<String> list,
#RequestContext UserContext context){
return super.update(storage.schema(), list, context);
}
As you can see now - any authorized user can edit the object.
We need to implement role validation from a user group, but each object has its own validation group. What tools to use to implement this functionality?
I was thinking of just storing the desired roles in the object and pulling them out for validation.
If you can, provide examples with detailed descriptions of the tools used, as I'm a young developer and it's still hard to implement everything myself.
Thanks in advance!

Related

How to properly secure my rest endpoints in jhipster?

I would like to secure my rest endpoints in the backend. For example an author can query his books like this:
/books?authorId=5&login=username
#GetMapping("/books")
#Timed
public ResponseEntity<List<Book>> getAllBooks(
#RequestParam(value="authorId", required = false) String authorId,
#RequestParam(value="login", required = false) String login) {
if(!login.equals(SecurityUtils.getCurrentUserLogin().get())){
return ResponseEntity.status(401).build();
}
List<Book> result;
if(authorId!= null)
result = bookService.findByAuthorId(authorId);
else if("admin".equals(SecurityUtils.getCurrentUserLogin().get()))
result = bookService.findAll();
else return ResponseEntity.status(401).build();
return ResponseEntity.ok().body(result);
}
Preferable I would like to only pass the authorId in the params
/books?authorId=5
but since SecurityUtils only gives me the loginName I can't compare them and identify the user in the backend.
Also since it's a microservice I can't access the AccountService.java which is handled by the gateway.
It all works fine but it seems wrong? Is there a better way to allow certain querys only for certain users? Should I make another rest endpoint which handles specifally requests to get books for specific users?
Thank you
You are addressing 2 use cases: one for authors (list my books) and one for management (list all books) for security reasons but usually you may also want to return different data based on use case. It could be a good idea to have 2 different resources: /api/my_books for authors and /api/books for management, you could even use nested resources.
For returning different data (also for security reasons) you can use the DTO option of JHipster with a service layer to map them from entities rather than exposing entities in your REST controllers.
Also don't pass the user id as a request param, you should modify TokenProvider to add it to the token as a claim. If you don't want to add user id to the token, you should modify book entity in your service so that it references user login rather than internal id, as long as it is immutable it does not make a difference.

JHipster User Authorization Implemetation

I wanted to block some users for accessing some services in JHipster.
How can I authorize a particular user for accession a ReST web Service in JHipster?
For blocking the access on the backend side, use the #Secured annotation on selected methods (rest entry points) in web/rest/*resource.java.
Example:
#RequestMapping(value = "/data-fields",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
#Timed
#Secured({AuthoritiesConstants.ADMIN})
public List<DataFieldDTO> getAllDataFields() {
log.debug("REST request to get all DataFields");
return dataFieldService.findAll();
}
As Gaël Marziou says, I believe that what you are trying to do is to block it on frontend's part. If it´s the case a possible way to do it is managing the use of "has-authority". For example: has-authority="ROLE_ADMIN"
So what you should do is the opposite, create an authority which allows some users to have access to ReST web Service
use has-authority and put your expected authority it will work 100% . tasted
write it on your html tag has-authority="ROLE_ADMIN" or your expected user
On /config/SecurityConfiguration.java
You can change access of the api that you want like
.antMatchers("/api/authenticate").permitAll()
.antMatchers("/api/**").authenticated()
.antMatchers("/management/**").hasAuthority(AuthoritiesConstants.ADMIN)
.antMatchers("/auth/*").hasAnyAuthority("ADMIN", "USER")
Or you can use auth.inMemoryAuthentication()
for more information read link below:
https://www.baeldung.com/spring-security-expressions

Does netsuite have REST ful API? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 2 years ago.
Improve this question
I want to know does Netsuite provides REST ful api? Currently i am doing integration with my application(java) with soap based web services.i have done some research but didn't get useful information.IF it does where can i found api?
Avoid the SuiteTalk SOAP web services API like the plague; it will do nothing but waste your time to. Usage of Netsuite SOAP API is viable only when you are okay with the SOAP API being non performant, don't mind interacting with gross buggy SOAP API, have much time to implement robust error handling to account for the random SOAP errors, concurrency errors. You'll need much time to develop robust fault tolerance. All that time will be wasted time; because no amount of time will make the SOAP API performance acceptable.
RESTlet's are preferred over SOAP API usage for writing data; RESTlets tend to be slightly more performant for writes (although responses are still extremely slow and not suitable for a customer facing app).
RESTlet's are a viable short term solution for writing data to Netsuite. Its essentially a JS script that allows you to set up a token based auth poor man's JSON endpoint; in which you can send JSON request bodies and get back JSON response bodies. Usage is reasonable in cases in which not much data needs to be written via the Restlet's (for instance for SalesOrders). A queue based system and background jobs with retry capabilities will mitigate the random Netsuite error issues (concurrency errors, timeouts etc).
If you must write to a bunch of Netsuite entities frequently and are using Netsuite as the source of truth for your data rather than attempting to build an entire REST like JSON API on top of Netsuite; I'd recommend implementing a pub/sub service in which Netsuite publishes events to an external service subscribed to by your app/API. Your app could also publish mutations to a channel subscribed to by Netsuite. This way data mutations sent to Netsuite can occur in a middle layer with reduced complexity.
To fetch Netsuite data for outside apps the most efficient means available appears to be the Netsuite ODBC database driver; it provides a direct connection to Netsuite database read only table views. Simple select queries for a set of Items that with same schema in Postgres or MySQL typically take 0.5 ms or less; typically take between 15 seconds to slightly over 100 seconds to return.
Connection timeouts and other errors from Netsuite are still common using NS ODBC driver. Despite slow query results retrieval of all data needed for a set of 5000 items in 14 seconds is far better than the hours it would take to get the same via Netsuite's SOAP API.
Yes. That is in Customization/Scripts section. You will find "RestLet" there. Doc is here.
However you said your application is soap based, I suggest you take a look Netsuite's WebServices aka SuiteTalk.
The SuiteTalk Platform provides programmatic access to your NetSuite data and business processes through an XML-based application programming interface (API).
I think you do need to access to your Netsuite data, right?
You can download their sample for test and learning.
In NetSuite, you can build RESTlet scripts which provide a REST-based interface. You can essentially use them to build your own JSON API. Recommend researching RESTlets in the NetSuite Help.
SOAP is easier to configure and use, but only allows 1 connection per
Netsuite account (you use your login credentials as authentication)
and is relatively slow.
That's not quite true, as you can extend it with suite cloud plus program. Check help for:
- Understanding Web Services Governance
- Enabling Web Services Concurrent Users with SuiteCloud Plus
UPDATE: There are two types of governance in NetSuite since approx July 2016 - user governance (also known as a legacy governance model, implicitly used when sessions / SOAP Login method are utilized) and account governance. In the account governance there is a shared pool for all incoming concurrent requests (no sessions should be used, authentication via user credentials or Token-Based Authentication).
This is the proper REST API provided by NetSuite for integration purposes.
https://system.netsuite.com/help/helpcenter/en_US/APIs/REST_API_Browser/record/v1/2020.1/index.html
The REST API can be invoked either via Token-based authentication or OAuth 2.0 enabled HTTP client.
First you need to login to NetSuite account and enable the SuiteTalk Webservice features of the account (Setup->Company->Enable Features).
Then obtain the SuiteTalk Base URL, which contains the account ID under the company URLs (Setup->Company->Company Information). E.g., https://<ACCOUNT_ID>.suitetalk.api.netsuite.com
After that create an integration application (Setup->Integration->New), enable OAuth 2.0 or TBA. This blog contains the process of enabling features and obtaining tokens.
Then use the BaseUrl + API resource path to as the HTTP client path to invoke each record API. Operations such as CRUD, search and filter can be done via this REST API. For more information See NetSuite Documentation
Yes, Netsuite supports REST web services.
Here's a working Java example, that uses the open source scribe library.
Note that an Accept (and for Posts, a Content-Type) header of application/json is needed for Netsuite to accept the requests, otherwise you'll get a "Request media type is not valid." error. Also getSignatureType method must be implemented for API class (NetSuiteApi.java).
Change all the string constants to suit your setup. Note that this code will also work with Netsuite RESTlets.
REST documentation is available here:
https://[your-netsuite-ID].app.netsuite.com/help/helpcenter/en_US/PDF/REST_Web_Services.pdf
File #1: NetSuiteApi.java
package com.scribe.api;
import com.github.scribejava.core.builder.api.DefaultApi10a;
import com.github.scribejava.core.model.OAuth1RequestToken;
public class NetSuiteApi extends DefaultApi10a {
private static class InstanceHolder {
private static final NetSuiteApi INSTANCE = new NetSuiteApi();
}
public static NetSuiteApi instance() {
return InstanceHolder.INSTANCE;
}
#Override
public String getAccessTokenEndpoint() {
return null;
}
#Override
public String getRequestTokenEndpoint() {
return null;
}
#Override
public String getAuthorizationUrl(OAuth1RequestToken requestToken) {
return null;
}
#Override
protected String getAuthorizationBaseUrl() {
return null;
}
#Override
public OAuth1SignatureType getSignatureType() {
return OAuth1SignatureType.HEADER;
}
}
File #2: NetSuiteApiCallExample.java
package com.scribe.api;
import com.github.scribejava.core.builder.ServiceBuilder;
import com.github.scribejava.core.model.OAuth1AccessToken;
import com.github.scribejava.core.model.OAuthRequest;
import com.github.scribejava.core.model.Response;
import com.github.scribejava.core.model.Verb;
import com.github.scribejava.core.oauth.OAuth10aService;
public final class NetSuiteRestExample {
private String CONSUMER_KEY = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
private String CONSUMER_SECRET = "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy";
private String TOKEN_ID = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
private String TOKEN_SECRET = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";
private String REST_URL = "https://1234567-sb1.suitetalk.api.netsuite.com/rest/platform/v1/record/inventoryitem/";
private String REALM = "1234567_SB1";
private String POSTBODY = "{\"type\": \"SIMPLE\",\"authorId\": -5}";
public static void main(String[] args) {
final OAuth10aService service = new ServiceBuilder(CONSUMER_KEY).apiSecret(CONSUMER_SECRET))
.build(NetSuiteApi.instance());
OAuth1AccessToken accessToken = new OAuth1AccessToken(TOKEN_ID, TOKEN_SECRET);
// This is POST method call
// OAuthRequest request = new OAuthRequest(Verb.POST, REST_URL);
// request.addHeader("Content-Type", "application/json");
// // Without next line, you'll get a "Request media type is not valid." error, even though this is not needed with Postman
// request.addHeader("Accept", "application/json");
// request.setRealm(REALM);
// request.setPayload(POSTBODY);
// This is GET method call
OAuthRequest request = new OAuthRequest(Verb.GET, params.get("REST_URL"));
// Without next line, you'll get a "Request media type is not valid." error, even though this is not needed with Postman
request.addHeader("Accept", "application/json");
request.setRealm(params.get("REALM"));
service.signRequest(accessToken, request);
System.out.println("Sending this request...");
System.out.println(request.getHeaders());
System.out.println(request.getCompleteUrl());
// System.out.println(request.getPayload());
final Response response = service.execute(request);
System.out.println("Got this response...");
System.out.println(response.getCode() + "\n" + response.getHeaders());
System.out.println(response.getBody());
return response.getBody();
}
}
Add this to you Maven dependencies (pom.xml):
...
<dependencies>
...
<dependency>
<groupId>com.github.scribejava</groupId>
<artifactId>scribejava-apis</artifactId>
<version>6.9.0</version>
</dependency>
</dependencies>

Multiple database application ACL (part 2)

I posted this question Access Control with a multi database application
So I tried putting it into application. Here is the case. I have a mainDB that has an ACL with no roles defined. The User clicks a button and it opens a control for CRUD with a datasource that has a computed filepath to a different database call it appDB. In appDB the ACL has several roles defined, and I have added myself to the ACL and assigned me the roles [Admin] and [Finance]. In this control I have added an After Page Load event that does the following:
var roles = context.getUser().getRoles();
viewScope.put("vsRoles", roles);
Upon opening the page the viewScope vsRoles is [] so it has not recognized that I have an additional set of roles in the appDB. So it would appear that context.getUser().getRoles() only gets my roles at authentication time when I log into the mainDB.nsf, and is not picking up the roles when I open appDB. I need to use the roles to configure what actions a person can perform, plus which documents a user can read and/or edit.
To complicate the issue the user may switch between multiple target application databases and will no doubt have different roles and access to each one.
thanks for the response to my previous question,but I might not have explained it in enough detail.
So, as far as I understood, what you need is to learn what specific roles the user has for the appDb.
context.getUser().getRoles() provides information about the current application (mainDB.nsf in your case). You are accessing appDB.nsf at a data source level. You can use a java method to learn the roles of a specific user in a target database:
public static List<String> getRoles(Database targetDb, String userName) {
ACL acl=null;
List<String> roles=new ArrayList<String>();
try {
acl=targetDb.getACL();
roles.addAll(targetDb.queryAccessRoles(userName));
} catch (NotesException e) {
// failed, nothing to do...
} finally {
if(acl!=null) acl.recycle();
}
return roles;
}
As an example:
Session session=ExtLibUtil.getCurrentSession();
Database appDb=session.getDatabase("", "appdb.nsf");
// Make sure appDb is not null...
List<String> roleList=getRoles(appDb, session.getEffectiveUserName());
ExtLibUtil.getViewScope().put("vsRoles", roleList);

Logged in user can only access 1 page?

Using Orchard 1.6 Iv created a new role 'FactoryWorker'. When this user logs in from the front end I want them to be navigated to one page only.
OrchardLocal/System/ManufacturedProducts
I have set this page to be a print screen of the order details so the factory worker will know what products to get ready for ship out & they wont be able to navigate as no menu appears, but also need the other pages blocked incase the user decides to enter the URL of a page they arnt allowed access to.
This is the only page I want this particular user to be able to access(after they login), and I have added a logout button, which logs out the user and returns them to the home page.
So iv been looking through editing a role, with permissions and content etc...but this all seems to be applying to forms and content in general. where the user can access any content type etc...
So can someone advise me on how to do this?
thanks for any replies
UPDATE
I forgot to mention that this is not a content type, item or part I am talking about.
I have created my own controller & View & VM which is accessible from the dash board (using the AdminMenu, which brings the admin user to OrchardLocal/System/ManufacturedProducts)
I have looked at Orchard.ContentPermissions Feature but it only seems to allow me to 1)Grant permissions for others or 2)Grant permission for own content
any ideas?
You can use a Request Filter, (I do not know if it is the best way) :
FilterProvider – defines the filter applied to each request. Resembles the way default ASP.NET MVC action filters work with the difference that it’s not an attribute. All FilterProvider objects are injected into the request pipeline and are applied to all requests (so you need to check if the current request is suitable for your filter at the beginning of an appropriate method).
From : http://www.szmyd.com.pl/blog/most-useful-orchard-extension-points
So you could implement something like this
public class Filter : FilterProvider, IAuthorizationFilter {
private readonly IAuthenticationService _authenticationService;
public Filter(IAuthenticationService authenticationService) {
_authenticationService = authenticationService;
}
public void OnAuthorization(AuthorizationContext filterContext) {
//If route is the restricted one
if (filterContext.HttpContext.Request.Url.AbsoluteUri.Contains("OrchardLocal/System/ManufacturedProducts")) {
//Get the logged user
IUser loggedUser = _authenticationService.GetAuthenticatedUser();
if (loggedUser == null)
return filterContext.Result = new HttpUnauthorizedResult();
//Get the Roles
var roles = loggedUser.As<IUserRoles>().Roles;
if (!roles.Contains("FactoryUser")) {
//User is not authorized
return filterContext.Result = new HttpUnauthorizedResult();
}
}
}
}
Note: Untested code!
EDIT: Also you could invert the logic and check if the logged user has the role 'FactoryUser' and restrict its access to every page except the one they should see.
Your module can create a new permission (look at one of the permissions.cs files for examples), then create a role that has only that permission. Have your controller action check that permission (again, many examples found by finding usage of the permissions defined in one of the permissions.cs).
You can use the Content Permissions module. Using this module you can attach a content item permission part to a content type. This part allows you to choose which roles can see the content when you create it.

Resources