Scribe OAuth2 where Endpoints are variable eg: Shopify - scribe

I am building an app where I use Scribe for all my oauth needs. I create a service API class overriding DefaultApi20 with my end points for authorization and token URLs.
However for Shopify, the authorization URL is dependent on another parameter (Eg: shop name) where the authorization url needs shopname as subdomain. How do I send parameters for this?
I can do the oauth manually constructing the auth url and token but I am looking for a better way to construct sending custom parameters.
Thanks.

We had a similar situation where a variable on the API had to set differently for different users. We did the following:
-Created a custom serviceImpl which extended OAuth10aServiceImpl (may be OAuth20ServiceImpl in your case).
-gave it a method to set the variable on it's api class
-after service is created by your ServiceBuilder lookup the appropriate value and call the setter method of the service.
-continue with normal OAUth token flow
Note that you also need to let the API know to use the custom service class, for example:
#Override
OAuthService createService(OAuthConfig config)
{
return new CustomServiceImpl(this,config)
}
Hope that helps

Related

Implement user authentication with gRPC

I'm looking to implement simple user authentication with my dart gRPC server + client and am struggling to find samples on how to achieve this properly.
So my problems are the following:
How do I add the user authentication data (JWT) to API calls that require authentication on the client?
How to I handle this data on the server?
I assume that on the client, metadata is the way to go, but is there a way to add the authentication data automatically for each call?
For the server, I assume that interceptors are the way to go, but how do I specify interceptors for specific services only (since not all API calls require authentication)?
is there a way to add the authentication data automatically for each call?
You can supply the default CallOptions with the options parameter in the generated client constructor.
You can use that to add authorization info to all your calls. If you need to perform async work for each call (for instance, to check if the token is still valid and optionally refresh it), you could add a MetadataProvider which gets invoked for each call.
how do I specify interceptors for specific services only (since not all API calls require authentication)?
The interceptor gets access to a ServiceMethod, which contains a name. So you could check that to only invoke an interceptor on some methods:
extension OnlyInterceptSome on Interceptor {
Interceptor limitTo(Set<String> endpoints) {
return (call, method) {
// Skip the check if we don't care about the method.
if (!endpoints.contains(method.name)) return null;
// Invoke the regular interceptor otherwise
return this(call, method);
};
}
}

Asp.net 5 web api bearer authentication and multiple areas

I have a webapi backend that several client applications are using. The api is secured with jwt authentication, it is based upon the following example: https://github.com/mrsheepuk/ASPNETSelfCreatedTokenAuthExample. Since I am not yet very comfortable with all the concepts of token based authentication I could use some guidance in this. My issue is that I need my applications to utilize the same api but to limit access for each application to a specific area or controller.
According to the example I can protect methods within an area with:
[Authorize("Api")]
A policy is added in startup with
authOptions.AddPolicy("Api", new AuthorizationPolicyBuilder()
.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme) // "Bearer" scheme
.RequireAuthenticatedUser().Build());
For secured requests from the client I typically have an angular 2 app that simply adds the jwt in the headers like so:
headers.append('Authorization', 'Bearer ' + jwt);
I don't know of all the mechanics here but I am assuming that when a secure method is requested, the "Api" attribute decoration is what decides/limits which policy is to be used with a certain route in the api.
What is best practice and how do I extend this to work with individually accessible sections?
You can create an ActionFilterAttribute for Authorization and use it on all the actions.
You can implement the FrameworkAuthorise filter methods as per your requirements.
Global.ApiKey is the unique code for your application to identity you have access to that application or not.
[FrameworkAuthorise(Global.ApiKey, AuthorisationType.None)]
public async Task<IHttpActionResult> Get()
{
// code goes here
}
[FrameworkAuthorise(Global.ApiKey, AuthorisationType.Bearer)]
public async Task<IHttpActionResult> Post()
{
// code goes here
}

how to create a temporary variable in the camel context for later use in the route

I have a route which interacts with 4 http endpoints. the first http endpoint is an authorization service from which i will get one authentication token. What i want is once i get the token from the authorization service i will pass the token to each further http service in the header. so how can i achieve that? is there any way of creating a temporary variable using the token value and if i can place it in the context then in any endpoint i can set it.
or else i was thinking if i can invoke the authorization service once at application startup once and store the token somewhere and i can use it.
You can store properties on your exchange object:
http://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/Exchange.html#setProperty(java.lang.String,%20java.lang.Object)
For example in my "pipeline" I'm storing ID from DB for later use:
from("quartz2://myScheduler?cron=0+0+6,14,22+*+*+?")
.to("sql:" + getNextID() + "?dataSource=#dataSource&outputType=SelectOne")
.setProperty("NextID", simple("${body[id]}"))
Then, the NextID is accessible from exchange exchange.getProperty("NextID")
You can use headers or properties

What is an efficient way to create/manage RESTful API with grails?

I've built my first grails application. My URL mappings are what the default application provides:
static mappings = {
"/$controller/$action?/$id?"{
constraints {
// apply constraints here
}
}
"/"(view:"/index")
"500"(view:'/error')
}
Senario
I have a controller called ColorController with actions save and list. It simply does something like this:
def save () {
def colorInstance = new Color(params)
colorInstance.save(flush: true)
}
def list () {
[colorList: Color.list, colorTotal: Color.count()]
}
I would like to build a simple API for these actions.
The save action should accept parameters as JSON and provide a successful message if the records save.
The list action should provide the list as JSON
Questions
Should I make a separate URL mapping for api? (e.g. http://<domain>/<app>/rest/controller/action)
Should I be making a separate controller for my API's
I am using spring security plugin for authentication. But at some point I might want to authenticate the restful api as well. What are some solutions for that?
If I use the same controller, how can I modify these simple actions to do what I need.
Before even looking below for my opinion/answers I would suggest to visit this SO Question for the basic understanding of RESTful WS in Grails.
Opinions:
"The save action should accept parameters as JSON and provide a successful message if the records save" - Save is mapped to POST RESTful. Instead of binding a JSON body to params it is bound to the request. In order to access the JSON object you just need to use request.JSON in the action method.
request.JSON instanceof JSONObject
"The list action should provide the list as JSON" - list() action is mapped to a GET Request and you can render the map as JSON in the list() as below
//Controller list()
import grails.converter.JSON
def list () {
[colorList: Color.list, colorTotal: Color.count()] as JSON
}
Answers to Questions:-
Should I make a separate URL mapping for api?
Abiding by the basics of REST, the client should only access the resource (Color in this case) and should not bother about the underlying controller or action. The server side logic should be abstracted from the client. URL Mapping is what the client would use to as form of request. I would have something like this in my url mapping for Color Resource.
/color/$id?(resource: "color")
or
/color/$id?(controller: 'color'){
action = [GET: "list", POST: "save"]
}
Should I be making a separate controller for my API's? - Depends on the way the App is designed. You also can have the above controller as the API. For example, currently I am working on a grails app which used AngularJS in the front End which connects to the Grails APP RESTFully. In order to achieve I had a RestClientController which works as an API to Angular. The rationale behind having a REST api in the same app is that in future we can expose the underlying service to external clients other than the Angular client present in the app itself.
I am using spring security plugin for authentication. But at some point I might want to authenticate the restful api as well. What are some solutions for that? - You can use Spring Security here as well. In my case I am using the plugin and I secure the controller by using the plugin's annotated component #Secured. I have custom OAuth enabled as well for authorization which interacts to the company wide LDAP and AD Groups.
If I use the same controller, how can I modify these simple actions to do what I need. - I think you would have got the answer to this question by now (after going through the SO question I mentioned above). Here is my opinion, controller actions can route to appropriate service classes which does the business implementations based on the request parameters.
For example,
//Action
def show(){
if(params.id){
colorService.getColor()
} else {
colorService.searchColor()
}
}
In the above example, the url mapping would be /color/123 or /color. In the former case, it will get the color and in the later it will search the colors

WCF4 REST APIkey question - pass information from ServiceAuthorizationManager to services

I want to implement an API key authentication solution for my WCF4 REST API.
I know that I need to make a class and derive it from ServiceAuthorizationManager and override the CheckAccessCore method. All that I understand.
But what I want to do from the CheckAccessCore pass internal information from the CheckAccessCore to my Service implementation classes. Information like "ApiKeyID, rights, flags and other details" that I looked up when doing the ApiKey authentication.
So that my services internally can use the internal ApiKeyID when it calls the domain logic.
I have seen many different ways of doing this, like
operationContext.ServiceSecurityContext.AuthorizationContext.Properties["Principal"] = p;
or
System.Threading.Thread.CurrentPrincipal = principal;
HttpContext.Current.User = principal;
and other ways....
Another way you can pass along objects is by adding the object to the Properties Collection of the RequestMessage object.
IssuedToken Token = new IssuedToken()
operationContext.RequestContext.RequestMessage.Properties.Add("NameOfObj",Token);