Can someone tell me why I can't use the same token to retrieve userInfo and calendars list from Google?
I have set the correct scopes (I think):
private static final String PLUS_ME_SCOPE = "https://www.googleapis.com/auth/plus.me";
private static final String USER_INFO_PROFILE_SCOPE = "https://www.googleapis.com/auth/userinfo.profile";
private static final String USER_INFO_EMAIL_SCOPE = "https://www.googleapis.com/auth/userinfo.email";
private static final String GOOGLE_CALENDAR_SCOPE = "https://www.googleapis.com/auth/calendar";
To get the user info I use this url: https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token= and for calendars I use: https://www.googleapis.com/calendar/v3/users/me/calendarList?minAccessRole=writer&key= .
In user Info I get all the correct info but for the calendar I get Error 401 : Login Required.
What's wrong in here?
Change
https://www.googleapis.com/calendar/v3/users/me/calendarList?minAccessRole=writer&key=
to
https://www.googleapis.com/calendar/v3/users/me/calendarList?minAccessRole=writer&access_token=
Just that simple ;)
UPDATE:
Also note, that it is not recommended to specify the access token as a query parameter:
Because of the security weaknesses associated with the URI method (see Section 5), including the high likelihood that the URL containing the access token will be logged, it SHOULD NOT be used unless it is impossible to transport the access token in the "Authorization" request header field or the HTTP request entity-body.
Related
I need to update the permissions of a Drive document from Salesforce.
I wanted to use Named Credentials, but I didn't find any way of building a call like this one:
https://www.googleapis.com/drive/v3/files/{documentId}/permissions
where {documentId} is a dynamic value.
I've seen that it is possible to add a prefix, but actually even if I create a Named Credential with only https://www.googleapis.com/drive/v3/files, when I call it from my Apex class I get a permission error.
Is there a way to achieve what I would like or I need to change approach?
Thank you
What exactly error are you getting? Salesforce security about not having access to class X? Something about callouts not allowed from triggers? You're sure it works with hardcoded document id?
Should be possible to make the named credential point to https://www.googleapis.com or https://www.googleapis.com/drive/v3/files/ and then add the rest of the endpoint in Apex. If it throws errors - maybe Drive's API is special, you'd need to read up.
String endpoint = 'callout:MyNamedCredential' + '/abc123/permissions';
HttpRequest req = new HttpRequest();
req.setEndpoint(endpoint);
req.setMethod('GET');
I have something like that:
Named credential pointing to https://maps.googleapis.com/maps/api/geocode/json
and then
static final String ENDPOINT = 'callout:GoogleMaps?key={0}&latlng={1}&result_type=premise%7Cstreet_address';
String apiKey = SomeCustomSetting__c.getInstance().GoogleApiKey__c;
String latLng = '60.23,11.17';
req.setEndpoint(String.format(ENDPOINT, new List<String>{apiKey, latLng}));
HttpResponse res = h.send(req);
You could also look into "Files Connect" API I guess.
Has anyone an idear what to use as a general Authorization Service and have an working code example or good implementation steps how to implement such of thing.
It takes a lot of time to look what I am after, but didn't found any satisfied solution yet.
IdentityServer is not an option, while my permissions can not be stored as claims, because of the size of the token. It comes with about 200 persmissions, so it should be done in a dbcontext or something.
I looked at the PolicyServer, but it wasn't working as I expected. When I installed it at the IS4 application, it works on the IS4 controllers, but when the Authorize is called from an external application, it doesn't call the Authorize override at all were it should check the permissions.
And it seems that the permissions aren't set in the external application either in the User.Claims or what so ever. I'm missing some settings I think.
What I want to accomplish is that I have one permissions store (table) (which for example contains a bunch of index, add, edit or delete button or what so ever). The should be given to the autheniticated user which is logged in. But this single persmission-store should be available at all applications or APIs I run, so that the Authorize attribute can do his job.
I think it shouldn't be so hard to do, so I'm missing a good working example how to implement something like this and what is working.
Who can help me with this to get this done?
I wrote some code to get the permissions by API call and use that in the IsInRole override. But when I declare it with the Authorize attr, it will not get in the method:
[ApiController]
1) [Authorize]
public class AuthController : ControllerBase
{
private readonly IdentityContext _context;
public AuthController(IdentityContext context)
{
_context = context ?? throw new ArgumentNullException(nameof(context));
}
[HttpGet()]
[Route("api/auth/isinrole")]
public bool IsInRole(string role)
{
2) if (User.FindFirst("sub")?.Value != null)
{
var userID = Guid.Parse(User.FindFirst("sub")?.Value);
if([This is the code that checks if user has role])
return true;
}
return false;
This is the IsInRole override (ClaimsPrincipal.IsInRole override):
public override bool IsInRole(string role)
{
var httpClient = _httpClientFactory.CreateClient("AuthClient");
3) var accessToken = _httpContextAccessor.HttpContext.GetTokenAsync(OpenIdConnectParameterNames.AccessToken).Result;
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
var request = new HttpRequestMessage(HttpMethod.Get, "/api/auth/isinrole/?id=" + role);
var response = httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead).Result;
etc...
This isn't working while it is not sending the access_token in the request
The 'sub' isn't send
Is always null
The open source version of the PolicyServer is a local implementation. All it does is read the permissions from a store (in the sample a config file) and transform them into claims using middleware.
In order to use the permissions you'll have to add this middleware in all projects where you want to use the permissions.
Having local permissions, you can't have conflicts with other resources. E.g. being an admin in api1 doesn't mean you are admin in api2 as well.
But decentralized permissions may be hard to maintain. That's why you probably want a central server for permissions, where the store actually calls the policy server rather than read the permissions from a local config file.
For that you'll need to add a discriminator in order to distinguish between resources. I use scopes, because that's the one thing that both the client and the resource share.
It also keeps the response small, you only have to request the permissions for a certain scope instead of all permissions.
The alternative is to use IdentityServer as-is. But instead of JWT tokens use reference tokens.
The random string is a lot shorter, but requires the client and / or resource to request the permissions by sending the reference token to the IdentityServer. This may be close to how the PolicyServer works, but with less control on the response.
There is an alternative to your solution and that is to use a referense token instead of a JWT-token. A reference token is just an opaque identifier and when a client receives this token, he has go to and look up the real token and details via the backend. The reference token does not contain any information. Its just a lookup identifier that the client can use against IdentiyServer
By using this your tokens will be very small.
Using reference token is just one option available to you.
see the documentation about Reference Tokens
I am persisting reference tokens to a db, my users have the ability to change or get a generated password. But if for example a user have forgotten their password and gets a new generated one then i would like to invalidate/remove all current tokens for this subject. Is it a good idea/acceptable to interact directly with the db via efcore or is there a api for this besides the /connect/revocation endpoint?
There is no problem in interacting with the database, but use the existing services to do this.
In IdentityService you can find the stores in the IdentityServer4.Stores namespace.
using IdentityServer4.Stores;
Inject the store in your controller:
private readonly IReferenceTokenStore _referenceTokenStore;
public class MyController : Controller
{
public MyController(IReferenceTokenStore referenceTokenStore)
{
_referenceTokenStore = referenceTokenStore;
}
}
And call it to remove the reference tokens for this user / client combination:
await _referenceTokenStore.RemoveReferenceTokensAsync(subjectId, clientId);
This will effectively remove the records from the database. You shouldn't create your own model of the database and remove the tokens directly.
Since IdentityServer is open source, you can take a look at the code that is used for token revocation.
I am trying to use Spring Social on my application and I noticed while debugging that the original 'OAuth2' state parameter is always null on my app.
See Spring Social source code for org.springframework.social.connect.web.ConnectSupport below:
private void verifyStateParameter(NativeWebRequest request) {
String state = request.getParameter("state");
String originalState = extractCachedOAuth2State(request);//Always null...
if (state == null || !state.equals(originalState)) {
throw new IllegalStateException("The OAuth2 'state' parameter is missing or doesn't match.");
}
}
private String extractCachedOAuth2State(WebRequest request) {
String state = (String) sessionStrategy.getAttribute(request, OAUTH2_STATE_ATTRIBUTE);
sessionStrategy.removeAttribute(request, OAUTH2_STATE_ATTRIBUTE);
return state;
}
Can anyone please help?
edit: I do see the state parameter being passed back by facebook:
Request URL:https://www.facebook.com/v2.5/dialog/oauth?client_id=414113641982912&response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Fconnect%2Ffacebook&scope=public_profile&state=0b7a97b5-b8d1-4f97-9b60-e3242c9c7eb9
Request Method:GET
Status Code:302
Remote Address:179.60.192.36:443
edit 2: By the way, the exception I get is the following:
Exception while handling OAuth2 callback (The OAuth2 'state' parameter is missing or doesn't match.). Redirecting to facebook connection status page.
It turned out that the issue was caused by the fact that I was relying on headers - as opposed to cookies - to manage the session.
By commenting out the following spring session configuration bean:
#Bean
public HttpSessionStrategy sessionStrategy(){
return new HeaderHttpSessionStrategy();
}
The oauth2 state parameter issue was sorted.
P.S. Now I have got to find a way to get Spring Social to work with my current configuration of Spring Session...
Edit: I managed to keep the HeaderHttpSessionStrategy (on the spring session side) and get it to work by implementing my own SessionStrategy (on the spring social side) as follows:
public class CustomSessionStrategy implements SessionStrategy {
public void setAttribute(RequestAttributes request, String name, Object value) {
request.setAttribute(name, value, RequestAttributes.SCOPE_SESSION);
}
public Object getAttribute(RequestAttributes request, String name) {
ServletWebRequest servletWebRequest = (ServletWebRequest) request;
return servletWebRequest.getParameter(name);
}
public void removeAttribute(RequestAttributes request, String name) {
request.removeAttribute(name, RequestAttributes.SCOPE_SESSION);
}
}
Try this work around and see if that works for you:
To my surprise I opened application in a 'incognito' browser and everything worked. Just like that. I think before something got cached and was causing the issue.
I ran into this issue today, My application was working perfectly fine. I just took a break for few hours and when I ran it again it started complaining about 'The OAuth2 'state' parameter is missing or doesn't match.'
The state param is first put into the session then the request goes out to facebook and the request comes back with the same state param but when spring is looking for session object to get the state param, it is not finding the session. I think it is not finding the session because when the request comes back it thinks that it is a different client (or host), even though the old HttpSession object still exists. The container maintains a HttpSession per client.
What you're getting from Facebook is not a request attribute , it's a request parameter.
You should get it by something like:
request.getParameter("state")
I am referencing #MinWan 's awesome answer in this post Google Cloud Endpoints and user's authentication, where he describes a way to add custom headers to a request against App Engine's Cloud Endpoints.
It becomes clear that we can add a custom header and write an authenticator per each service (e.g. Google, Twitter, Facebook) against which we want to authenicate, where each authenticator reads a specific header and authenticates against the service. If the token is valid, a service typically returns a response with an email address or user id, plus some extra information [A], from which we generate a com.google.api.server.spi.auth.common.User, which is later passed into the endpoint method as com.google.appengine.api.users.User.
First question: Why do we have two different User entities, e.g. users with different namespaces? As it seems, these are neither sub/superclasses, so they are possibly explicitly cast behind the scenes.
Second question: The problem that comes with the explicitly cast User entity and that there is no custom field where I could put the extra information [A] returned by the service, is that the extra information is lost. Such extra information may be helpful for matching the oauth2 user of the external service to a local user or to oauth2 users returned by other services.
Any input? What's the suggested way of handling multiple authentication services?
Just tested, and you can definitely subclass User to contain whichever private fields you want. Just use class inheritance polymorphism to return an object of that type from the Authenticator method, without changing the type from default User in the method signature.
import javax.servlet.http.HttpServletRequest;
import com.google.api.server.spi.auth.common.User;
import com.google.api.server.spi.config.Authenticator;
public class BazUser extends User {
private String secret; // extra piece of data held by this User
public BazUser(String email) {
super(email);
this.secret = "notasecret";
}
public BazUser (String email, String secret) {
super (email);
this.secret = secret;
}
}
public class BazAuthenticator implements Authenticator {
public User authenticate(HttpServletRequest req) {
return new BazUser ("userid#baz.com", "secret");
}
}
Functionally, everything works with:
import com.google.api.server.spi.auth.common.User;
even with gradle:
compile 'com.google.endpoints:endpoints-framework:2.0.0-beta.11'
The IDE warning can be cleared by including #SuppressWarnings("ResourceParameter") as follows:
/**
* Adds a new PmpUser.
*
* #param pmpUser pmpUser object
*/
#SuppressWarnings("ResourceParameter")
#ApiMethod(
name = "pmpUser.post",
path = "pmpUser",
httpMethod = ApiMethod.HttpMethod.POST)
...