Spring Security SAML with Spring session - spring-security

I am using OpenAM as my IDP and my SP (an angular2 SPA) is based on the example shared at: https://github.com/vdenotaris/spring-boot-security-saml-sample
After authentication, my webapp is supposed to invoke few REST services which are secured via http-basic authentication(using spring security) whose sessions are managed via Spring Session.
I am trying to create spring-session based sessions after a user is authenticated through OpenAM IDP. My intent is to use these sessions to talk to my http-basic-secured REST services.
Following is the "configure()" of my webapp's WebSecurityConfig before I attempted integrating spring-session with spring-saml and this works just fine.
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.httpBasic()
.authenticationEntryPoint(samlEntryPoint());
http
.csrf()
.disable();
http
.addFilterBefore(metadataGeneratorFilter(), ChannelProcessingFilter.class)
.addFilterAfter(samlFilter(), BasicAuthenticationFilter.class);
http
.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/publicUrl").permitAll()
.antMatchers("/app/**").permitAll()
.antMatchers("/error").permitAll()
.antMatchers("/saml/**").permitAll()
.anyRequest().authenticated();
http
.logout()
.logoutSuccessUrl("/");
}
And the authentication works just fine. In the POST fired from IDP (OpenAM) I can see the cookie being set properly. eg : Set-Cookie: JSESSIONID=8DD6CDBF8079E83C8F4E7976C970BB27; Path=/; HttpOnly
Response
Headers
Pragma: no-cache
Date: Sun, 31 Jul 2016 02:12:06 GMT
X-Content-Type-Options: nosniff
Server: Apache-Coyote/1.1
X-Frame-Options: DENY
Location: http://localhost:8097/
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Set-Cookie: JSESSIONID=8DD6CDBF8079E83C8F4E7976C970BB27; Path=/; HttpOnly
Content-Length: 0
X-XSS-Protection: 1; mode=block
Expires: 0
Cookies
JSESSIONID: 8DD6CDBF8079E83C8F4E7976C970BB27
Following is the "configure()" of my webapp's WebSecurityConfig after I tried integrating spring-session with spring-saml and this breaks the authentication.
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.httpBasic()
.authenticationEntryPoint(samlEntryPoint());
http
.csrf()
.disable();
http
.addFilterBefore(metadataGeneratorFilter(), ChannelProcessingFilter.class)
.addFilterAfter(samlFilter(), BasicAuthenticationFilter.class);
http
.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/publicUrl").permitAll()
.antMatchers("/app/**").permitAll()
.antMatchers("/error").permitAll()
.antMatchers("/saml/**").permitAll()
.anyRequest().authenticated();
http
.logout()
.logoutSuccessUrl("/");
http
.addFilterBefore(sessionRepositoryFilter(sessionRepository(), httpSessionStrategy()),
ChannelProcessingFilter.class)
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED);
}
In the POST fired back from IDP (OpenAM) I dont see the cookie being set.
Response
Headers
Pragma: no-cache
Date: Sun, 31 Jul 2016 02:18:44 GMT
X-Content-Type-Options: nosniff
Server: Apache-Coyote/1.1
X-Frame-Options: DENY
Location: http://localhost:8097/
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
x-auth-token: 666412f1-b293-49fa-bacb-0aa6fc3d2fe0
Content-Length: 0
X-XSS-Protection: 1; mode=block
Expires: 0
Cookies
The SAML response was ok as I can see the Subjects details from IDP post authentication.
snippet from the SAML response
<saml:Subject>
<saml:NameID
Format="urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress"
NameQualifier="http://openam.example.com:8080/OpenAM-13.0.0">vin#example.com
</saml:NameID>
<saml:SubjectConfirmation
Method="urn:oasis:names:tc:SAML:2.0:cm:bearer">
<saml:SubjectConfirmationData
InResponseTo="a1f07e22gi7db1h425hfj65i5gh0464"
NotOnOrAfter="2016-07-31T02:28:44Z"
Recipient="http://localhost:8097/saml/SSO"/>
</saml:SubjectConfirmation>
</saml:Subject>
Since the cookie is not set, I am not able to get hold of the principal object. My UI assumes the user is not authenticated and redirects the user again to IDP and it keeps running in a loop.
Your response is highly appreciated.

Try to add this: server.session.tracking-modes=cookie in your properties file. Also, try to add an SSL. The cookie may be marked as secure and without SSL cannot be visible.

Similar issue for me, I had to explicitly set the following configuration as the default for SameSite cookie config is 'lax' if not set, and when lax is used, Chrome won't send the cookie after being posted back from the IDP
Ref: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite#lax
server.servlet.session.cookie:
# OWASP best practice
secure: true
http-only: true
# Ensure SAML SSO IDP POST response sends SESSION cookie
same-site: none

Related

Asp.Net MVC CORS enabled in Web API but headers no longer being sent

I have two DotNet MVC sites. One accesses a Web API from the other with an AJAX GET call.
This all worked, but has stopped functioning now. I've hardly made any changes on my side, so I'm wondering if my host might have made changes (in IIS, for example) that would stop this from working?
Here's how I initially got it working...
I installed the Microsoft.Aspnet.Cors and Microsoft.Aspnet.WebApi.Cors packages.
I added the following code...
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.EnableCors();
And in the controller for my API I added...
namespace Webscope.Controllers
{
[EnableCors(origins: "[URL of my other website]", headers: "*", methods: "*")]
public class EventAPIController : ApiController
This used to work, but now get the following error in the console:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https:[my website URL]/EventRead/1-1-2015/12-12-2099. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
In response to #FoggyDay's answer below, I've called the API from Fiddler and got the following headers...
HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-Frame-Options: AllowAll
X-Powered-By: ASP.NET
Date: Fri, 13 Mar 2020 03:56:39 GMT
Content-Length: 198
So it looks as if CORS headers have not been included in the response. Can anyone tell me why this would be?
UPDATE
I found some extraneous code from a previous attempt to get CORS working. Now that I've removed this code, I am seeing the CORS headers in Fiddler.
Access-Control-Allow-Headers: *
Access-Control-Allow-Methods: *
Access-Control-Allow-Origin: https://[ calling website's URL ]/
However I'm still getting the following error in my calling site's console...
Access to XMLHttpRequest at
'https://[ destination site URL ]/api/EventRead/1-1-2015/12-12-2099' from
origin '[ calling website's URL ]' has been blocked by CORS
policy: Response to preflight request doesn't pass access control
check: No 'Access-Control-Allow-Origin' header is present on the
requested resource.
SUGGESTIONS:
Back out your "new" changes. It sounds like you've inadvertantly introduced a second header.
Read this: Reason: CORS header 'Access-Control-Allow-Origin' missing
Look at your HTTP traffic, for example in Fiddler. Verify that you're sending the header ... and verify that you're allowing the correct combination of host and port.
If you're still having problems, post back with the exact error message and relevant HTTP headers.

Why isn't my browser storing ASP MVC CORE 2 cookies?

I have an Angular(4) client (localhost:4200) which calls across to an ASP MVC CORE 2 WebApi. One of the calls http://localhost:5000/api/session/resume returns a cookie along with the response.
In the action method I have returned 3 cookies for testing purposes.
[AllowAnonymous, HttpPost, Route("api/session/resume")]
public async Task<AccountSignInResponse> Resume([FromBody]SessionResumeCommand command)
{
AccountSignInResponse apiResponse = await Mediator.Send(command);
if (!apiResponse.HasErrors) {
Response.Cookies.Append("TestCookie", ..., new CookieOptions
{
Domain = "localhost",
Expires = DateTimeOffset.Now.AddDays(100),
HttpOnly = false
});
Response.Cookies.Append("TestCookie4200", ..., new CookieOptions
{
Domain = "localhost:4200",
Expires = DateTimeOffset.Now.AddDays(100),
HttpOnly = false
});
Response.Cookies.Append("TestCookie5000", ..., new CookieOptions
{
Domain = "localhost:5000",
Expires = DateTimeOffset.Now.AddDays(100),
HttpOnly = false
}); }
return apiResponse;
}
The header for this request is
Request URL:http://localhost:5000/api/session/resume
Request Method:POST
Status Code:200 OK
Remote Address:[::1]:5000
Referrer Policy:no-referrer-when-downgrade
And the response headers are
HTTP/1.1 200 OK
Transfer-Encoding: chunked
Content-Type: application/json; charset=utf-8
Vary: Origin
Server: Kestrel
Set-Cookie: TestCookie=XXVtPqCdZ%2BBt9IbhP5Bi7sOLZ%2F%2BELB4fZ0rFArkM%2Be4%3D; expires=Fri, 03 Nov 2017 09:47:28 GMT; domain=localhost; path=/
Set-Cookie: TestCookie4200=XXVtPqCdZ%2BBt9IbhP5Bi7sOLZ%2F%2BELB4fZ0rFArkM%2Be4%3D; expires=Fri, 03 Nov 2017 09:47:28 GMT; domain=localhost:4200; path=/
Set-Cookie: TestCookie5000=XXVtPqCdZ%2BBt9IbhP5Bi7sOLZ%2F%2BELB4fZ0rFArkM%2Be4%3D; expires=Fri, 03 Nov 2017 09:47:28 GMT; domain=localhost:5000; path=/
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: http://localhost:4200
X-SourceFiles: =?UTF-8?B?QzpcZGV2XFhlcnhlc1xYZXJ4ZXMtU2VydmVyXFNlcnZlclxhcGlcc2Vzc2lvblxyZXN1bWU=?=
X-Powered-By: ASP.NET
Date: Wed, 26 Jul 2017 09:47:28 GMT
As you can see, the cookies are being returned from the http://localhost:5000/api/session/resume call, but they are not being stored in my local cookies in either Chrome, Edge, or Firefox. So when further requests are made for images and other resources I am only seeing another cookie (cookieLawSeen), and not this cooked.
When I browse the cookies for localhost in all of these browsers I don't see any SessionTokens in the storage. However, if I look at the request in the F12 developer tools I can click the [Cookies] tab and see ResponseCookies contains all three cookies.
You need to use withCredentials property. It is needed for both sending and receiving cookies:
indicates whether or not cross-site Access-Control requests should be made using credentials such as cookies, authorization headers or TLS client certificates.
Set it to true each time when you do api call from Angular. Something like the following:
this.http.get('http://...', { withCredentials: true })
I had the same problem and i found out that in .net core 2 the default of session cookie was changed from "Send for: Any kind of connection" to send only to same origin. In my case the server was at a different domain from local host and there for the cookie was not sent to the server.
In order to allow it you need to change the property of the session cookie called SameSite to SameSiteMode.None.
In addition to the above I haven't been able to access a localhost server from the local postman (even-though they have the same origin). the above solved it as well.

Issue during migration from Google OAuth 1.0 to OAuth 2.0 - The oAuth client was disabled

I'm trying to follow the documentation "https://developers.google.com/accounts/docs/OAuth_ref" to migrate oAuth to oAuth2 but keep getting an error
In the "APIs & auth" - "Credentials" Section in our API developers console we have 1 Client ID for web application set up along with a number of service account client Ids.
The client Ids appear to be in a format xxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com for each client ID that is set up.
If I use the exact Id for the 'client ID for web application' in the format [xxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com] then I get an error
{
"error" : "invalid_client"
}
If I use the more generic client ID [ xxxxxxxxxxxx.apps.googleusercontent.com
] then I get the following error
{
"error" : "disabled_client",
"error_description" : "The OAuth client was disabled."
}
Here is my post request from Fiddler
POST https://accounts.google.com/o/oauth2/token HTTP/1.1
Authorization: OAuth realm="",oauth_consumer_key="<consumerKey>",oauth_token="<token>",oauth_timestamp="1400680750",oauth_nonce="6637551",oauth_signature_method="HMAC-SHA1",oauth_signature="I%2FCOsR1BrGQHnqTeyhX4GUrKrv8%3D"
Content-Type: application/x-www-form-urlencoded
Host: accounts.google.com
Content-Length: 151
Expect: 100-continue
Connection: Keep-Alive
grant_type=urn:ietf:params:oauth:grant-type:migration:oauth1&client_id=<clientID>.apps.googleusercontent.com&client_secret={<client_secret>}
Here is the base string I use for oauth_signature
POST&https://accounts.google.com/o/oauth2/token&client_id=<clientID>.apps.googleusercontent.com&client_secret=<clientSecret>&grant_type=urn:ietf:params:oauth:grant-type:migration:oauth1&oauth_consumer_key=<consumerKey>&oauth_nonce=2648138&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1400681371&oauth_token=<token>
Here is the response I get from Google
HTTP/1.1 401 Unauthorized
Content-Type: application/json; charset=utf-8
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: Fri, 01 Jan 1990 00:00:00 GMT
Date: Wed, 21 May 2014 13:59:16 GMT
Content-Disposition: attachment; filename="json.txt"; filename*=UTF-8''json.txt
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block
Server: GSE
Alternate-Protocol: 443:quic
Transfer-Encoding: chunked
5b
{
"error" : "disabled_client",
"error_description" : "The OAuth client was disabled."
}
0
Any suggestions?
Here a related post: https://groups.google.com/forum/#!topic/google-analytics-data-export-api/yveoPwSVzCQ
As for Owen's suggestion, I am pretty sure the error is not related to oauth1 vs oauth2 client type validation but rather to the provided oauth2 credentials (client id and client secret).
It turns out that the POST body that I was sending to google was incorrect.
Originally I had sent
grant_type=urn:ietf:params:oauth:grant-type:migration:oauth1&client_id=<clientID>.apps.googleusercontent.com&client_secret={<client_secret>}
Note the { } around the client_secret. When I removed these then I no longer got the errors.
Now I can pass in the client_id in the format xxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com and the client_secret without { } and I get a sucessful response.
The reason for the other error that I had been receiving was that the client id in the format xxxxxxxxxxxx.apps.googleusercontent.com was an old client_id that had been deleted and was no longer visible on the Google Developer console.

Box oauth2: Invalid grant_type parameter or parameter missing

I don't know what I do wrong, but everytime I tried to obtain the token (after user authentication of course), the result is always Invalid grant_type parameter or parameter missing
Possibly related to Box API always returns invalid grant_type parameter on obtaining access token
Here is my fiddler result:
POST https://api.box.com/oauth2/token HTTP/1.1
Host: api.box.com
Content-Length: 157
Expect: 100-continue
Connection: Keep-Alive
grant_type=authorization_code&code=nnqtYcoik7cjtHQYyn3Af8uk4LG3rYYh&client_id=[myclientId]&client_secret=[mysecret]
Result:
HTTP/1.1 400 Bad Request
Server: nginx
Date: Thu, 07 Mar 2013 11:18:36 GMT
Content-Type: application/json
Connection: keep-alive
Set-Cookie: box_visitor_id=5138778bf12a01.27393131; expires=Fri, 07-Mar-2014 11:18:35 GMT; path=/; domain=.box.com
Set-Cookie: country_code=US; expires=Mon, 06-May-2013 11:18:36 GMT; path=/
Cache-Control: no-store
Content-Length: 99
{"error":"invalid_request","error_description":"Invalid grant_type parameter or parameter missing"}
Even following the curl example gives the same error. Any help would be appreciated.
Edit: tried with additional redirect_uri params but still the same error
POST https://api.box.com/oauth2/token HTTP/1.1
Content-Type: application/json; charset=UTF-8
Host: api.box.com
Content-Length: 187
Expect: 100-continue
Connection: Keep-Alive
grant_type=authorization_code&code=R3JxS7UPm8Gjc0y7YLj9qxifdzBYzLOZ&client_id=*****&client_secret=*****&redirect_uri=http://localhost
Result:
HTTP/1.1 400 Bad Request
Server: nginx
Date: Sat, 09 Mar 2013 00:46:38 GMT
Content-Type: application/json
Connection: keep-alive
Set-Cookie: box_visitor_id=513a866ec5cfe0.48604831; expires=Sun, 09-Mar-2014 00:46:38 GMT; path=/; domain=.box.com
Set-Cookie: country_code=US; expires=Wed, 08-May-2013 00:46:38 GMT; path=/
Cache-Control: no-store
Content-Length: 99
{"error":"invalid_request","error_description":"Invalid grant_type parameter or parameter missing"}
Looks like Box requires a correct Content-Type: application/x-www-form-urlencoded request header in addition to properly URL encoding the parameters. The same seems to apply to refresh and revoke requests.
Also, per RFC 6749, the redirect_uri is only
REQUIRED, if the "redirect_uri" parameter was included in the authorization request
as described in Section 4.1.1, and their values MUST be identical.
I was facing a similar issue.
The problem is not with Content-Type.
The issue is with the lifecycle of code you receive.
One key aspect not mentioned in most places is that the code you get on redirect lasts only 30 seconds.
To get the access token and refresh token, you have to make the post request in 30 seconds or less.
If you fail to do that, you get the stated error. I found the info here.
Below code worked for me. Keep in mind, the 30-second rule.
import requests
url = 'https://api.box.com/oauth2/token'
data = [
('grant_type', 'authorization_code'),
('client_id', 'YOUR_CLIENT_ID'),
('client_secret', 'YOUR_CLIENT_SECRET'),
('code', 'XXXXXX'),
]
response = requests.post(url, data=data)
print(response.content)
Hope that helps.
You are missing the redirect URI parameter. Try:
POST https://api.box.com/oauth2/token HTTP/1.1
Host: api.box.com
Content-Length: 157
Expect: 100-continue
Connection: Keep-Alive
grant_type=authorization_code&code=nnqtYcoik7cjtHQYyn3Af8uk4LG3rYYh&client_id=[myclientId]&client_secret=[mysecret]&redirect_uri=[your-redirect-uri]
I have also face same issue implementing oauth2. I have add Content-Type: application/x-www-form-urlencoded. When I add content-type my issue solved.
Check and add valid content-type.
Not sure who might need this in the future but be sure you're sending a POST request to get the access token and not trying to retrieve it by using GET or if you're testing- pasting in the address bar won't work, you need to send a POST request with the data in the BODY and not as query parameter.
Also the code usually lasts for a few seconds, so you need to use it as soon as its sent back.

How to make use of jsessionid together with basic authentication

I am using JBoss 7.1 and have secured my web application with Basic authentication but I want only the first call to require the Basic authentication header, sequent calls should use the jsessionid for authentication. How to accomplish this?
So far I have created a rest servlet enforcing the creation of a session with a call to request.getSession()
#Path("/rest/HelloWorld")
public class HelloWorld {
#GET()
#Produces("text/plain")
public String sayHello(#Context HttpServletResponse response,
#Context HttpServletRequest request) {
HttpSession session = request.getSession();
return "Hello World! " + request.getUserPrincipal().getName();
}
My idea was that any other calls should only require the jsessionid cookie, but when looking in fiddler I see that the first call is behaving as expected. First you get a 401 and the client is re-sending including the basic authorization header and a jsessionid is returned. On the second call the jsessionid cookie is included but I still get an 401 that triggers the client to re-send the Basic authorization header.
This is the returned headers from the successful authenticated first call.
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Pragma: No-cache
Cache-Control: no-cache
Expires: Thu, 01 Jan 1970 01:00:00 CET
Set-Cookie: JSESSIONID=AFDFl2etiUNkn-mpM+DXr3KE; Path=/Test
Content-Type: text/plain
Content-Length: 18
Date: Tue, 29 Jan 2013 09:12:48 GMT
Hello World! test1
when I make a second call the jsessionid is included
GET /Test/index.html HTTP/1.1
Host: cwl-rickard:8080
Cookie: JSESSIONID=AFDFl2etiUNkn-mpM+DXr3KE
and I am getting a 401 enforcing the client to re-send the request including the basic authorization header.
HTTP/1.1 401 Unauthorized
Server: Apache-Coyote/1.1
Pragma: No-cache
Cache-Control: no-cache
Expires: Thu, 01 Jan 1970 01:00:00 CET
WWW-Authenticate: Basic realm="ApplicationRealm"
Content-Type: text/html;charset=utf-8
Content-Length: 958
Date: Tue, 29 Jan 2013 09:12:48 GMT
Any ideas what I am missing.

Resources