Google oAuth 2.0 new authorization and token endpoint - google-oauth

I will update my code for Google oAuth2.0 web-views disallow warning.
I found the authorization and token endpoints had changed in document.
I use the endpoint as follows since 2014.
"accounts.google.com/o/oauth2/auth"
"accounts.google.com/o/oauth2/token"
new endpoint as follows
"accounts.google.com/o/oauth2/v2/auth"
"www.googleapis.com/oauth2/v4/token"
I try my code for old and new endpoint. It works on all endpints.
Can I still use old endpoints? or Have expired date for old endpoints?
Thanks!

In order to be fully compliant with the OpenIDConnect spec, We created the new endpoints because we didn't want to break existing developers. So the new endpoints are OpenIDConnect complaint (and tools find them through discovery doc). There are minor changes (I don't remember all of them at the moment) .. e.g. issuer in the id_token is https://accounts.google.com instead of accounts.google.com
Since many new open source tools in the future (which you may use) will be OpenIDConnect complaint, I suggest using the new ones. We don't have any plans to deprecate the old ones but will continue to monitor the usage and decide if it is worth deprecating if all the traffic shifts to new ones.

Related

How does OAuth work API to API without interactive users?

I have a background task that runs periodically which needs to connect to a customer's Apigee OAuth2 protected API. From my understanding of OAuth2, a user must go to a sign in page on Apigee, and it will redirect to a return Url with a token. This is the way I have used previously on website projects. But in this scenario, there are no users, no website, and no return Url, it is just some code making a http request.
Is the above possible to do? Every google search I make is all about users logging in manually and getting a token to a return url.
I found some mention of 'Flows' and maybe there is some other 'Flow'? but its really hard to get a clear understanding of how it works because guides are focused on user interactive websites.
OAUTH 2.0 is an industry-standard for authorization. OAUTH 2.0 supports many authorization grant types, namely they are;
Authorization Code
Implicit
Resource Owner Password Credentials
Client Credentials
[Note that you may come up with your own custom grants as well if you are building or extending your authorization server - however it is beyond the scope of this question]
In the example you have provided, you are using the Authorization code grant type where you redirect to APIGEE and getting an authorization code. The APIGE server acts as the "intermediary between the client and resource owner" in OAUTH 2.0 terms.
For your new requirement, you should consider using the client-credentials grant type where the client is provided a client key and a secret. The client has the responsibility of calling the authorization server (like APIGEE in your previous example or anything else) and getting a token and then using that token in the subsequent requests.
I recommend you to read the ietf standard for oauth 2.0 to get a better understanding - Refer https://www.rfc-editor.org/rfc/rfc6749.
Make sure to read on "Roles" in this link well before diving onto the content of this document.
Good luck!

Securing a JAX-RS

I'm working on a RESTful API, that works as backend for a mobile application.
The underlying system is based on Jersey and Jetty server, but my question is more generic (for any JaX-RS compliant system).
I'm looking for a standard solution to secure it. I read about many answers talking about JWT, tokens, ... and OAuth.
But all solutions except OAuth do not have a Standard and neither any implementation apart from some basic examples on github.
I'm concern as OAuth seems a good solution for third party access on your API but I think is a great overhead for straight access & tokenization, from a Mobile app or a Website AJAX. Is hard for me to accept that is the only available solution.
Here I'm asking, am I wrong about OAuth (beeing designed for third party access)? or other access solutions are not available (eg opensourced) as they are only custom made for the specific purpose?
My scenario requirements:
Token should be self certified (eg JWT) so a proxy/load balancer can filter out a not signed one, before reaching the endpoint.
No need for a token/renew system as we have a distributed cache holding a SESSION and therefore a missing session mean that authorization expired/was revoked.
The second one, may not be true as if we issue a certificate to an App for 1 year, and revoke it after 1 hour. This token may be still used by an attacker to "frustrate" our cache for 1 year.

Google is updating their OpenID Connect implementation to be fully spec compliant, will anything break for me?

Google updated their OpenID Connect endpoints to be fully spec compliant, as part of the OpenID Certification effort. I rely on OpenID Connect to sign my users in with Google. Will I need to do anything as a relying party to avoid breaking due to these changes?
It depends on how you use OpenID Connect with Google. If you are performing dynamic discovery by fetching https://accounts.google.com/.well-known/openid-configuration as recommended by the docs then the way your servers interact with Google will change, but you will only be affected if your implementation cannot handle the newer, more spec compliant responses.
On the other hand, if you have hardcoded the various endpoints directly (i.e. the auth and token endpoints) then you are isolated from these changes, but you should consider migrating to the new endpoints.
Major changes in the new endpoints include:
Id Token issuer (the iss claim) changes from accounts.google.com to https://accounts.google.com (during the migration peroid, you should accept either value)
If your response_type includes id_token, you must include a nonce or your requests will hard-error.
If you are using a spec-compliant OpenID Connect library then theoretically everything should continue to work as before.
To avoid any possible problems during the migration period (or if your website suddenly breaks), you can hardcode the following URL to get the previous discovery document: https://google.com/accounts/o8/well-known-openid-configuration-old.json (or use the values within to hardcode your auth and token endpoints). As this document points to old versions of the endpoints, you will get the old behavior. Then you can test your products with the latest endpoints (as found in the current discovery document) at your leisure.
To compare the differences, or view the complete new & old, see this gist.

Using SAML2 Tokens with WCF channelfactory and Weblogic services

Help! :) I'm having no end of problems trying to get the following working(apologies in advance if I'm not using the exact correct terminology) :)
I need to get a .NET web application (client) communicating with Weblogic web services secured with SAML 2 policies. There are restrictions in that I need to use .NET 3.5/4 and as such am using WIF (with the extensions) to work with ADFS2 configured to generate SAML2 tokens.
The website -> adfs2 -> SAML2 token bit is working fine so far - I definitely getting tokens through.
Additional(1) - the Weblogic services have to use SAML2 policies that implement a sender-vouches confirmation method and although ADFS 2 supplies bearer by default, I am able to manipulate the SAML assertion before we send the token across the wires to the service(s).
Additional(2) - For numerous reasons, the webservices are not reached over SSL and basicHTTPBinding is my only option.
Now the problem.. I just can't communicate with Weblogic in such a way as to send the token in the request (any logged attempt returns an oracle "General Web Service Security Error" due to there being no valid security header in the request). The preferred approach would be via WCF, using a channel factory - the code below is a rough example of what I've tried - the claimsidentity/token stuff was taken from the code sample that came with the WIF extension stuff:
IClaimsIdentity identity = Thread.CurrentPrincipal.Identity as IClaimsIdentity;
Saml2SecurityToken token = identity.BootstrapToken as Saml2SecurityToken;
BasicHttpBinding binding = new BasicHttpBinding();
binding.Security.Mode = BasicHttpSecurityMode.None;
binding.Security.Transport.ClientCredentialType = HttpClientCredntialType.None;
EndpointAddress address = new EndpointAddress("http://someaddress");
ChannelFactory<weblogicService.MyService> factory = new ChannelFactory<weblogicService.MyService>(binding,address);
factory.ConfigureChannelFactory<weblogicService.MyService>();
factory.Credentials.SupportInteractive = false;
weblogicService.MyService proxy = factory.CreateChannelWithIssuedToken<weblogicService.MyService>(token)
proxy.DoSomething();
The answer at the following post (and everywhere else I've been able to find):
WCF and WebLogic SAML interop
..is exactly what I'm doing - but whether viewing the traffic with WireShark OR by implementing a customer MessageInspector and looking at the request in "BeforeSendRequest", I can't see any sign of the token (and the request is rejected as a consequence).
Also it doesn't matter if I manipulate the token to include sender-vouches or just leave it as it is originally.
Additional (3): I have been able to successfully communicate with the Weblogic service if I don't use ADFS2/SAML/WIF/WCF etc. but instead, go via a more basic WSE2.0/3.0 web references approach (i.e. creating SoapRequest, UserName token etc..)
The problem with that, is in supplying a valid username and password without user interaction. In other words, keeping a "SSO approach", and not have to implement Forms Authentication (or equivalent) to get the user credentials each time.. There doesn't appear to be any obvious way of using the SecurityToken generated by ADFS with WSE either..
Can anyone help shed some light? Why the WCF channel factory approach with a supplied token is simply not working i.e. no sign of a valid token when debugging and certainly no valid SAML token being received by Weblogic.
I have also looked at going the CustomMessageEncoder route, and adding the SAML Assertion into the SOAP header that way.. but from what I have been able to find out, it really shouldn't be this difficult. Is something in WCF broken?
End point binding limitations (basicHTTP) doesn't support SAML2 afaik, also ADFS2.0 only seems to supply bearer tokens and modifying the token after the fact is also non starter (the suggested overrides in WIF to do this don't seem to work as expected) and finally because the web services aren't behind https, having a security mode of none (which is the only one that could be used) meant no token was being sent anyway.. ahh well, back to the drawing board!

Best Practices for securing a REST API / web service [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
When designing a REST API or service are there any established best practices for dealing with security (Authentication, Authorization, Identity Management) ?
When building a SOAP API you have WS-Security as a guide and much literature exists on the topic. I have found less information about securing REST endpoints.
While I understand REST intentionally does not have specifications analogous to WS-* I am hoping best practices or recommended patterns have emerged.
Any discussion or links to relevant documents would be very much appreciated.
If it matters, we would be using WCF with POX/JSON serialized messages for our REST API's/Services built using v3.5 of the .NET Framework.
As tweakt said, Amazon S3 is a good model to work with. Their request signatures do have some features (such as incorporating a timestamp) that help guard against both accidental and malicious request replaying.
The nice thing about HTTP Basic is that virtually all HTTP libraries support it. You will, of course, need to require SSL in this case because sending plaintext passwords over the net is almost universally a bad thing. Basic is preferable to Digest when using SSL because even if the caller already knows that credentials are required, Digest requires an extra roundtrip to exchange the nonce value. With Basic, the callers simply sends the credentials the first time.
Once the identity of the client is established, authorization is really just an implementation problem. However, you could delegate the authorization to some other component with an existing authorization model. Again the nice thing about Basic here is your server ends up with a plaintext copy of the client's password that you can simply pass on to another component within your infrastructure as needed.
There are no standards for REST other than HTTP. There are established REST services out there. I suggest you take a peek at them and get a feel for how they work.
For example, we borrowed a lot of ideas from Amazon's S3 REST service when developing our own. But we opted not to use the more advanced security model based on request signatures. The simpler approach is HTTP Basic auth over SSL. You have to decide what works best in your situation.
Also, I highly recommend the book RESTful Web Services from O'reilly. It explains the core concepts and does provide some best practices. You can generally take the model they provide and map it to your own application.
You may also want to take a look at OAuth, an emerging open protocol for token-based authorization specifically targeting http apis.
It is very similar to the approach taken by flickr and remember the milk "rest" apis (not necessarily good examples of restful apis, but good examples of the token-based approach).
There is a great checklist found on Github:
Authentication
Don't reinvent the wheel in Authentication, token generation, password storage. Use the standards.
Use Max Retry and jail features in Login.
Use encryption on all sensitive data.
JWT (JSON Web Token)
Use a random complicated key (JWT Secret) to make brute forcing the token very hard.
Don't extract the algorithm from the payload. Force the algorithm in the backend (HS256 or RS256).
Make token expiration (TTL, RTTL) as short as possible.
Don't store sensitive data in the JWT payload, it can be decoded easily.
OAuth
Always validate redirect_uri server-side to allow only whitelisted URLs.
Always try to exchange for code and not tokens (don't allow response_type=token).
Use state parameter with a random hash to prevent CSRF on the OAuth authentication process.
Define the default scope, and validate scope parameters for each application.
Access
Limit requests (Throttling) to avoid DDoS / brute-force attacks.
Use HTTPS on server side to avoid MITM (Man In The Middle Attack)
Use HSTS header with SSL to avoid SSL Strip attack.
Input
Use the proper HTTP method according to the operation: GET (read), POST (create), PUT/PATCH (replace/update), and DELETE (to delete a record), and respond with 405 Method Not Allowed if the requested method isn't appropriate for the requested resource.
Validate content-type on request Accept header (Content Negotiation) to allow only your supported format (e.g. application/xml, application/json, etc) and respond with 406 Not Acceptable response if not matched.
Validate content-type of posted data as you accept (e.g. application/x-www-form-urlencoded, multipart/form-data, application/json, etc).
Validate User input to avoid common vulnerabilities (e.g. XSS, SQL-Injection, Remote Code Execution, etc).
Don't use any sensitive data (credentials, Passwords, security tokens, or API keys) in the URL, but use standard Authorization header.
Use an API Gateway service to enable caching, Rate Limit policies (e.g. Quota, Spike Arrest, Concurrent Rate Limit) and deploy APIs resources dynamically.
Processing
Check if all the endpoints are protected behind authentication to avoid broken authentication process.
User own resource ID should be avoided. Use /me/orders instead of /user/654321/orders.
Don't auto-increment IDs. Use UUID instead.
If you are parsing XML files, make sure entity parsing is not enabled to avoid XXE (XML external entity attack).
If you are parsing XML files, make sure entity expansion is not enabled to avoid Billion Laughs/XML bomb via exponential entity expansion attack.
Use a CDN for file uploads.
If you are dealing with huge amount of data, use Workers and Queues to process as much as possible in background and return response fast to avoid HTTP Blocking.
Do not forget to turn the DEBUG mode OFF.
Output
Send X-Content-Type-Options: nosniff header.
Send X-Frame-Options: deny header.
Send Content-Security-Policy: default-src 'none' header.
Remove fingerprinting headers - X-Powered-By, Server, X-AspNet-Version etc.
Force content-type for your response, if you return application/json then your response content-type is application/json.
Don't return sensitive data like credentials, Passwords, security tokens.
Return the proper status code according to the operation completed. (e.g. 200 OK, 400 Bad Request, 401 Unauthorized, 405 Method Not Allowed, etc).
I'm kind of surprised SSL with client certificates hasn't been mentioned yet. Granted, this approach is only really useful if you can count on the community of users being identified by certificates. But a number of governments/companies do issue them to their users. The user doesn't have to worry about creating yet another username/password combination, and the identity is established on each and every connection so communication with the server can be entirely stateless, no user sessions required. (Not to imply that any/all of the other solutions mentioned require sessions)
Everyone in these answers has overlooked true access control / authorization.
If for instance your REST APIs / web services are about POSTing / GETing medical records, you may want to define access control policie about who can access the data and under which circumstances. For instance:
doctors can GET the medical record of a patient they have a care relationship with
no one can POST medical data outside practice hours (e.g. 9 to 5)
end-users can GET medical records they own or medical records of patients for whom they are the guardian
nurses can UPDATE the medical record of a patient that belongs to the same unit as the nurse.
In order to define and implement those fine-grained authorizations, you will need to use an attribute-based access control language called XACML, the eXtensible Access Control Markup Language.
The other standards here are for the following:
OAuth: id. federation and delegation of authorization e.g. letting a service act on my behalf on another service (Facebook can post to my Twitter)
SAML: identity federation / web SSO. SAML is very much about who the user is.
WS-Security / WS-* standards: these focus on the communication between SOAP services. They are specific to the application-level messaging format (SOAP) and they deal with aspects of messaging e.g. reliability, security, confidentiality, integrity, atomicity, eventing... None cover access control and all are specific to SOAP.
XACML is technology-agnostic. It can be applied to java apps, .NET, Python, Ruby... web services, REST APIs, and more.
The following are interesting resources:
the OASIS XACML website
the NIST ABAC standard
I've used OAuth a few times, and also used some other methods (BASIC/DIGEST). I wholeheartedly suggest OAuth. The following link is the best tutorial I've seen on using OAuth:
http://hueniverse.com/oauth/guide/
One of the best posts I've ever come across regarding Security as it relates to REST is over at 1 RainDrop. The MySpace API's use OAuth also for security and you have full access to their custom channels in the RestChess code, which I did a lot of exploration with. This was demo'd at Mix and you can find the posting here.
Thanks for the excellent advice. We ended up using a custom HTTP header to pass an identity token from the client to the service, in preparation for integrating our RESTful API with the the upcoming Zermatt Identity framework from Microsoft. I have described the problem here and our solution here. I also took tweakt's advice and bought RESTful Web Services - a very good book if you're building a RESTful API of any kind.
OWASP(Open Web Application Security Project) has some cheat sheets covering about all aspects of Web Application development. This Project is a very valuable and reliable source of information.
Regarding REST services you can check this: https://www.owasp.org/index.php/REST_Security_Cheat_Sheet
I would recommend OAuth 2/3. You can find more information at http://oauth.net/2/
I searched a lot about restful ws security and we also ended up with using token via cookie from client to server to authenticate the requests . I used spring security for authorization of requests in service because I had to authenticate and authorized each request based on specified security policies that has already been in DB.
The fact that the SOAP world is pretty well covered with security standards doesn't mean that it's secure by default. In the first place, the standards are very complex. Complexity is not a very good friend of security and implementation vulnerabilities such as XML signature wrapping attacks are endemic here.
As for the .NET environment I won't help much, but “Building web services with Java” (a brick with ~10 authors) did help me a lot in understanding the WS-* security architecture and, especially, its quirks.
REST itself offers no security standards, but things like OAuth and SAML are rapidly becoming the standards in this space. However, authentication and authorization are only a small part of what you need to consider. Many of the known vulnerabilities relating to web applications apply very much to REST apis. You have to consider input validation, session cracking, inappropriate error messages, internal employee vulnerabilities and so on. It is a big subject.
I want to add(in line with stinkeymatt), simplest solution would be to add SSL certificates to your site. In other words, make sure your url is HTTPS://. That will cover your transport security (bang for the buck). With RESTful url's, idea is to keep it simple (unlike WS* security/SAML), you can use oAuth2/openID connect or even Basic Auth (in simple cases). But you will still need SSL/HTTPS. Please check ASP.NET Web API 2 security here: http://www.asp.net/web-api/overview/security (Articles and Videos)
As #Nathan ended up with which is a simple HTTP Header, and some had said OAuth2 and client side SSL certificates. The gist of it is this... your REST API shouldn't have to handle security as that should really be outside the scope of the API.
Instead a security layer should be put on top of it, whether it is an HTTP Header behind a web proxy (a common approach like SiteMinder, Zermatt or even Apache HTTPd), or as complicated as OAuth 2.
The key thing is the requests should work without any end-user interaction. All that is needed is to ensure that the connection to the REST API is authenticated. In Java EE we have the notion of a userPrincipal that can be obtained on an HttpServletRequest. It is also managed in the deployment descriptor that a URL pattern can be secure so the REST API code does not need to check anymore.
In the WCF world, I would use ServiceSecurityContext.Current to get the current security context. You need to configure you application to require authentication.
There is one exception to the statement I had above and that's the use of a nonce to prevent replays (which can be attacks or someone just submitting the same data twice). That part can only be handled in the application layer.
For Web Application Security, you should take a look at OWASP (https://www.owasp.org/index.php/Main_Page) which provides cheatsheets for various security attacks. You can incorporate as many measures as possible to secure your Application.
With respect to API security (authorization, authentication, identity management), there are multiple ways as already mentioned (Basic,Digest and OAuth). There are loop holes in OAuth1.0, so you can use OAuth1.0a (OAuth2.0 is not widely adopted due to concerns with the specification)
It's been a while but the question is still relevant, though the answer might have changed a bit.
An API Gateway would be a flexible and highly configurable solution.
I tested and used KONG quite a bit and really liked what I saw. KONG provides an admin REST API of its own which you can use to manage users.
Express-gateway.io is more recent and is also an API Gateway.