Spring Security SAML assertion expiry with Application Session Expiry - angularjs

I'm getting confused with the SAML assertion expiry vs Application session expiry.
In simple words, when we have an application deployed in a container, there is a session created. This session expiry can be controlled with the below entry in web.xml
<session-config>
<session-timeout>60</session-timeout>
</session-config>
Moving on, when I have Spring Security with SAML extension, obviously the same session concept applies. (I'm deploying the application in WildFly 8.2, if that matters)
Further, when the application session expires, the logout behaviour seems to be equivalent to Local Logout concept.
So far so good. Now lets say that the SAML assertion is good for 2 hours and the user has been actively working for 2 hours. What should happen to the subsequent request then? Should it re-login to the IDP? But, wouldnt that be inconvenient to the user? If the application redirects to IDP for logging in again after 2 hours of assertion expiry, How should AJAX requests be handled?
This is in reference to the question here

Spring SAML issues an ExpiringUsernameAuthenticationToken for authenticated users. The token starts returning false in its isAuthenticated() method once the SAML Assertion used to authenticate the user reaches its sessionNotOnOrAfter time.
This behavior can be disabled by overriding SAMLAuthenticationProvider and changing method getExpirationDate(credential), which returns time when the Assertion expires, or null in case it never does. Application will then fully rely on session expiration configured in the container.
Once the ExpiringUsernameAuthenticationToken expires, Spring Security will pass the current token to the AuthenticationManager (configured in securityContext.xml under <security:authentication-manager>).
You can affect what happens next, by adding your own AuthenticationProvider able to handle the ExpiringUsernameAuthenticationToken. Otherwise system fails with ProviderNotFoundException or some other AuthenticationException like BadCredentialsException (in case you're using username/password authentication at the same time).
The exception is subsequently handled by ExceptionTranslationFilter, which start new authentication process by invoking the configured authentication EntryPoint - e.g. SAMLEntryPoint which either starts authentication with default IDP or displays IDP selection page. The process will also essentially perform local logout, as you say.
System by default behaves the same for all HTTP calls - AJAX or not. You can define different behavior by splitting your API and normal URLs into separate <security:http> elements and use different EntryPoints (interface AuthenticationEntryPoint) for each. For example Http403ForbiddenEntryPoint might be suitable for your AJAX calls.

Related

Azure app Service authentication token not refreshing after calling .\auth\refresh endpoint

I have an angular app hosted in one azure windows app service and a asp.net core api hosted in another, both are protected using the app service authentication feature. I am using an app service plan which currently has two servers. I am using the token store and it is using the file system to store the tokens.
When the angular app calls the api it needs to pass an access token in the authorization header. The access token is retrieved by performing a GET on the \.auth\me endpoint and sending the AppServiceAuthSession cookie as the credential. The returned token is then cached in session storage and used for subsequent requests until the token expires. When the token expires I call the \.auth\refresh endpoint (and send the AppServiceAuthSession cookie) and then call the \.auth\me to get the refreshed token.
All this works well when running on one server but when the app service plan is scaled to 2 or more servers the call to \.auth\refresh succeeds but the subsequent call to the .auth\me endpoint gets a token which has already expired. I can tell the token has expired by checking the internal exp claim and also the call to the api fails with a 401 Unauthorized when it would normally succeed.
If I scale back to one server the problem goes away and if I enable ARR affinity the problem goes away but I don't want to have to enable affinity just to resolve this.
also the call to the api fails with a 401 Unauthorized when it would normally succeed.
You shouldn't be calling /.auth/refresh on the API app. You must call /.auth/refresh on the WEB app because the auth token is produced on the WEB app.
Alternative to the bearer token is the AppServiceAuthSession cookie from your client request to /.auth/refresh.
The returned token is then cached in session storage and used for subsequent requests until the token expires. When the token expires I call the .auth\refresh endpoint (and send the AppServiceAuthSession cookie) and then call the .auth\me to get the refreshed token.
We have a user-facing web application that calls an API backend, which in turn queries the MSFT graph, just to be sure we have the context correctly captured. At each phase, we anticipate a distinct AAD registration:
Web app registration (with permission to API app)
API app registration (with permission to Microsoft Graph)
Our initial assumption is that the user hasn't explicitly given their agreement to using the Microsoft Graph because this looked to be tied to adding the graph permission. Since the user isn't involved if you're merely updating the existing token, there isn't a chance for that consent to be obtained. The user would need to re-login with an explicit consent prompt, which could be done by calling /.auth/login/aad?prompt=consent. But we wouldn't anticipate that to cause the expiration problem. I'm speculating here, but it's possible that a cached, outdated value is being utilised in place of the permission error. There would need to be input from Connor.
The logs from the actual Authentication / Authorization layer itself, particularly if there is an error message, are another piece of information that would be useful to have. To obtain these logs:
From your app in the portal (the API app is what I'm most interested in): “Platform features” > “Diagnostic logs”. Change “Application Logging (Filesystem)” to “On” and set the level to “verbose.” Hit Save.
Back to “Platform features” > “Log stream” and keep that window open as you reproduce the issue (in this case, the call to the API app)
Actually, the issue is that AAD bearer tokens are incompatible with the /.auth/refresh API. Instead, you must use a session token (_x-zumo-auth_ header) or a session cookie (_AppServiceAuthSession_ cookie), which are the results of a login activity.
For more info - see here #refreshing-the-access-tokens

Sustainsys.Saml2 SLO Logout RequestDenied status error

I need help in implementing Single Logout.I'm able to implement SSO service successfully.But SLO service is not working.
I got RequestDenied status code after performing logout on my OWIN based asp.net MVC application.
<saml2p:LogoutRequest
Destination="https://sap-client.accounts.ondemand.com/saml2/idp/slo/sap-client.accounts.ondemand.com"
ID="idb2d655f7174f465696a433c75a717b46" IssueInstant="2019-08-03T02:16:03Z" Version="2.0"
xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion"
xmlns:saml2p="urn:oasis:names:tc:SAML:2.0:protocol">
<saml2:Issuer>https://sp.domain.com/Saml2</saml2:Issuer>
<saml2:NameID Format="urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress">xxx#xxx.com</saml2:NameID>
<saml2p:SessionIndex>S-SP-6aff8686-a642-4381-8ab3-0f18c6815ffe</saml2p:SessionIndex>
<LogoutResponse Destination="https://sp.domain.com/Saml2/Logout" ID="S0e6a2f99-2517-4326-a8ce-2ede2dfe1bfa" InResponseTo="idb2d655f7174f465696a433c75a717b46" IssueInstant="2019-08-03T02:16:04.933Z" Version="2.0" xmlns="urn:oasis:names:tc:SAML:2.0:protocol" xmlns:ns2="urn:oasis:names:tc:SAML:2.0:assertion" xmlns:ns4="http://www.w3.org/2001/04/xmlenc#" xmlns:ns3="http://www.w3.org/2000/09/xmldsig#">
<ns2:Issuer>sap-client.accounts.ondemand.com</ns2:Issuer>
<Status>
<StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Requester">
<StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:RequestDenied" />
</StatusCode>
<StatusMessage>Identity Provider could not process the logout message received.</StatusMessage>
</Status>
Here is Owin log
Sustainsys.Saml2.Owin.Saml2AuthenticationMiddleware Error: 0 : Error in Saml2 for /Saml2/Logout
Sustainsys.Saml2.Exceptions.UnsuccessfulSamlOperationException: Idp returned status "Requester", indicating that the single logout failed. The local session has been successfully terminated.
at Sustainsys.Saml2.WebSso.LogoutCommand.HandleResponse(UnbindResult unbindResult, StoredRequestState storedRequestState, IOptions options, Uri returnUrl)
at Sustainsys.Saml2.WebSso.LogoutCommand.Run(HttpRequestData request, String returnPath, IOptions options)
at Sustainsys.Saml2.Owin.Saml2AuthenticationHandler.d__4.MoveNext()
ProcessId=14888
DateTime=2019-08-04T06:16:22.3060366Z
Thank you in advance.
The Idp returns an error. You should check the logs on the Idp to get more information on why.
It might also be worth using SAML dev tools for Chrome to check the actual messages, there might be more status codes embedded in the response.
One reason that this might occur is if you have a long lived session in your application that extends beyond the life time of the Idp session. With owin based applications where the external login session is typically swapped to an application login session this might happen - the session life time limit is lost in the swap done in ExternalLoginCallback.

Okta Kentor.AuthServices IdentityServer3 IDP-initiated SSO is triggering SP-initiated SSO - error or design?

Using IdentityServer3, Kentor.AuthServices 0.19 (with OWIN middleware) and a standard MVC 4 WebApi 2 app, we have followed instructions at https://github.com/KentorIT/authservices/blob/master/doc/IdentityServer3Okta.md
and it appeared that we achieved successful IDP-initiated login.
However, when we looked closely at this, and using KentorStubIdp (where we first noticed we were prompted to provide a SAML response), we found the following
IDP hits our endpoint, e.g. identityserver/okta/acs, status 303
Successful redirection to our redirection endpoint in our app, which is coded to return a redirection to the identityserver authorisation endpoint, thus
var client = new AuthorizeRequest(new Uri(identityServerUrl + "connect/authorize"));
var returnUrlForIdp = client.CreateAuthorizeUrl(
"{client_identifier}",
"id_token token",
scopesForAuth,
hostUrl,
state,
nonce,
acrValues: string.Format("idp:{0}", idp),
responseMode: "form_post"
);
return Redirect(returnUrlForIdp);
This results in a 302 to identityserver/connect/authorise. It appears that this has all the login information it needs, and I would have expected a 200 straight into the app, but instead we get a 302 to identityserver/login?signin=xxx which gives a 401 which appears to trigger...
The subsequent call to the login endpoint gets a 303 redirection back to the IDP, which marks the start of an ultimately successful SP-initiated login. Meaning it comes back to identityserver/okta/acs, then the /callback endpoint, then /connect/authorise then the user is logged in.
I cannot find any meaningful difference between the first and second calls to /connect/authorise except
The successful attempt is preceeded by a call to identityserver/callback
Cookies for idsvr and idsvr.session appear not to be set on the first call but are in the second
Also, Kentor config settings seem to be in order - e.g.
AllowUnsolicitedAuthnResponse = true
and
AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Passive although this last one didn't seem to have an effect either way
At this point I'm just trying to work out a) whether this is how it is supposed to work under the covers and b) if not, where should I focus my attention to diagnose the problem.
Is there a particular set of circustances that trigger authservices to initiate an SP-initiated SAML request if a, IDP-initiated one is lacking info?
Any advice much appreciated.
Using Idp-initiated sign on with SAML2 + OIDC is a bit tricky, as OIDC doesn't support it. Which means that IdSrv3 is not really built for that scenario either.
The outline of what you would need is:
Idp sends unsolicited response to IdSrv3/AuthServices.
AuthServices validates response
IdSrv3 establishes log in session on IdSrv3.
User is redirected to client application's login init url
Client app initiates a OIDC sig in towards IdSrv3.
IdSrv3 Single signs on with session established in 3.
User is redirect back to client app.
Looks like step 2 works, but step 3 is not properly done. Which means that in step 6 there is no session, so user is redirected all the way to the Idp to pick up existing session. This works, but is somewhat ugly. And if you later on want to do single sign out there is a session count mismatch which might cause issues.

How can you implement refresh tokens in a web app - angularjs

I am using token based security in my web app. The server side is wrote using c# and i am using openiddict for logging in and issuing tokens, found here. I am currencyly using Implict flow.
By default my tokens have a lifespan of 1 hour, after that you have to logging again. I have locked down my API to accept bearer tokens only and not cookies.
I wanted to implement refresh tokens but after reading many websites, it appears that implementing refresh tokens on a web app, is not a good way to go due to a hacker getting the refresh token. I know that to use refresh tokens, you must use code flow, instead of implict, which i can do.
How do people get round this situation in their web apps? I cant be the only one who wants a token to last longer than an hour in a web app?
The approach recommended by OpenID Connect is to send an authorization request in a hidden frame with the same parameters as the ones you use for the initial implicit flow request plus prompt=none and optionally, an id_token_hint corresponding to the id_token you extracted from the authorization response.
When using prompt=none, the identity provider won't display any consent form and will directly redirect the user agent to the redirect_uri you specify, with the new token appended to the URI fragment, just like for a classic implicit flow request. You can retrieve it by extracting it from the popup.location.hash property.
If the request cannot be processed (invalid request, unauthenticated user, invalid id_token_hint, consent required, etc.), an error is returned and the identity provider either redirects the user agent to the redirect_uri with an error parameter or stops processing the request.
Note that due to the same origin policy, you can't access popup.location.hash if the current location belongs to a different domain (e.g if the identity provider refuses to redirect the user agent to your client app): it will throw an access denied exception. In this case, it's always better to add a timeout to your "refresh" operation.
Sadly, there are very few libraries that can help you with this task. oidc-token-manager is one of them, but it has a few limitations that will prevent it from working OTB with OpenIddict: it doesn't support raw RSA keys (you have to explicitly use a X509 certificate in the OpenIddict options) and it doesn't send the id_token_hint parameter required by OpenIddict when sending a prompt=none request.

Spring SAML - Is it mandatory to call SAML local logout when user signs off from application?

As per the answer from the link, I understand that if SAML local logout (/saml/logout?local=true) is invoked Spring-SAML will clean the local cookies. So, I have modified the logout logic in my application to invoke it.
All looks good till now. But my application have session timeout set to 20 minutes in web.xml.
<session-config>
<session-timeout>20</session-timeout>
</session-config>
In case of user inactive for 20 minutes or browser is closed by the user, session will be destroyed by the container silently. In that case SAML Logout is not invoked.
Questions:
Does Spring-SAML maintains any references once user is authenticated after SAML response is received?
If yes, where does it maintain references (session or somewhere else)? Any alternative way to clean them up?
What are the implications if we do not call SAML local logout?
My worry is that if the references are not cleaned up, It might cause memory leaks in a long run of the application.
By default all state of Spring SAML is stored in HttpSession (as part of Spring Security context in object SAMLCredential) and will be cleaned at session timeout (or more precisely at time when your container decides to perform the session cleanup after expiration).
It is exactly the same as with any other authentication method supported by Spring Security, so you don't need to worry about not calling the local logout.

Resources