Spring security url interceptor - spring-security

I have spring security implemented in my application, and you can logged with twitter facebook o normal, if you sign in with your email and password there aren't any problem, but if you logged with twitter,the url interceptor don't let see that page.
I have this code when you logged with twitter in my controller in java.
Authentication authentication = new UsernamePasswordAuthenticationToken(userRegister.getEmail(), "ROLE_USER");
SecurityContextHolder.getContext().setAuthentication(authentication);
And this is my url:interceptor in my spring-security.xml
<security:intercept-url pattern="/member/**" access="hasRole('ROLE_USER')" />
Anybody can help me?
Thanky yoU!

Related

Why Request.IsAuthenticated is false when token generated from iframe for SSO azure B2C msal .net

I have 2 applications, one is mvc web application with Msal .net code for Azure ad B2C login and second application is power apps portal using same azure ad b2c login. I have added iframe into both application for silent login if user logged in any one of the application, on power apps portal it worked on all browser like chrome, firefox, edge, opera. But for mvc application it work only on firefox browser, other than firefox it's request does not get authenticated. When I debug iframe request, able to see acquire token
IConfidentialClientApplication confidentialClient = MsalAppBuilder.BuildConfidentialClientApplication(new ClaimsPrincipal(notification.AuthenticationTicket.Identity));
Globals.ClientInfo = confidentialClient;
// Upon successful sign in, get & cache a token using MSAL
AuthenticationResult result = await confidentialClient.AcquireTokenByAuthorizationCode(Globals.Scopes, notification.Code).ExecuteAsync();
Globals.AuthenticationResult = result;
Globals.Claims = notification.AuthenticationTicket.Identity.Claims;
Globals.EncryptedClaim = notification.JwtSecurityToken.RawData;
but into call back function Request.IsAuthenticated is false.
My web application is using .net framework 4.7.1 and Microsoft.Identity.Client version 4.29.0, please help me to resolve this issue.
Also i am getting below error for my b2c callback method on chrome and edge, automatically response cookies are getting set Lax instead None, is this causing problem to set cookies for iframe.
Thanks,
Sandy
Request.IsAuthenticated is FALSE when you deal with <authentication mode="Forms"> and TRUE if you deal with <authentication mode="Windows" />.
So, to solve this problem check the authentication mode in your web.config. Add the following code in your web.config :
<authentication mode="Forms">
<forms loginUrl="~/_Login/Login" timeout="30" />
</authentication>
and
<system.webServer>
<modules>
<remove name="FormsAuthentication" />
<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" />
</modules>
<system.webServer>
Set the reply URL to your main homepage URL in both the registration and the config and make sure that the application ID and client ID are matching.
Refer the following links for more information :
Microsoft AAD Identity And Access Management With MVC 5 Web Application.
Request.IsAuthenticated is false after logging into Active Directory| MSDN
If in case you are getting redirected to the login page after successfull login then you will need to change the CookieManger :
var cookieOptions = new CookieAuthenticationOptions();
cookieOptions.CookieManager = new SystemWebCookieManager();
app.UseCookieAuthentication(cookieOptions);
Check this document for more information.

WSO2 and Spring SAML single logout issue

The issue I'm having has been discussed several times on this site, however most posts are quite old. Here is something similar to what I'm experiencing. I'm using WSO2 IS 5.2 as my IdP and I have 2 java based web applications hosted on difference servers that participate in SSO. Each webapp (SP) has implemented the Spring-SAML extension. Single Sign-On works perfectly but Single Logout only partially works. Here is the test case:
Access secure resource on webapp1
Login page from Idp (WSO2) is presented and user logs in
Secure resource from webapp1 is presented
Access secure resource on webapp2
SAML request is sent to Idp, Idp responds and user is authenticated
Secure resource from webapp2 is presented, end SSO
Initiate single log out from webapp2
Webapp2 send saml request (through browser) to Idp and saml response is returned
User is logged off locally on webapp2 and Idp session is terminated
The IdP directly sends logout request to webapp1 (back-channel type)
Logout request fails to webapp1 (log indicate SamlStatusException: No user is logged in)
So the end result is that I still have a local session on webapp1. If I change the order and initiate SLO from webapp1, then webapp1 will be logged out and webapp2's local session will continue to exist. The WSO2 server is able to determine the 2nd session participant during SLO, however the HTTP request sent from the Idp to the 2nd session participant does not have a Spring security context. This would be a stateless HTTP request so there wouldn't be a logged in user. This is why I believe it is failing.
I found this discussion. Its about 2 years old. Is there anything new on this issue? Maybe a configuration step missed by me on WSO2 or in the Spring-saml config.
Here is a relevant piece of my SP metadata:
<md:SingleLogoutService Location="https://tpap10-wwwdev04.arbfile.org:443/webapp/saml/SingleLogout" Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"/>
<md:SingleLogoutService Location="https://tpap10-wwwdev04.arbfile.org:443/webapp/saml/SingleLogout" Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect"/>
<md:NameIDFormat>urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress</md:NameIDFormat>
<md:NameIDFormat>urn:oasis:names:tc:SAML:2.0:nameid-format:transient</md:NameIDFormat>
<md:NameIDFormat>urn:oasis:names:tc:SAML:2.0:nameid-format:persistent</md:NameIDFormat>
<md:NameIDFormat>urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified</md:NameIDFormat>
<md:NameIDFormat>urn:oasis:names:tc:SAML:1.1:nameid-format:X509SubjectName</md:NameIDFormat>
<md:AssertionConsumerService Location="https://tpap10-wwwdev04.arbfile.org:443/webapp/saml/SSO" Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" isDefault="true" index="0"/>
<md:AssertionConsumerService Location="https://tpap10-wwwdev04.arbfile.org:443/webapp/saml/SSO" Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Artifact" index="1"/>
Some relevant Spring-Saml config on the SP:
<bean id="metadataGeneratorFilter" class="org.springframework.security.saml.metadata.MetadataGeneratorFilter">
<constructor-arg>
<bean class="org.springframework.security.saml.metadata.MetadataGenerator">
<property name="entityId" value="urn:webapp1:mycity"/>
<property name="entityBaseURL" value="https://wwwdev04.domain.org:443/webapp" />
<property name="extendedMetadata">
<bean class="org.springframework.security.saml.metadata.ExtendedMetadata">
<!-- <property name="signMetadata" value="false"/> -->
<property name="idpDiscoveryEnabled" value="false"/>
</bean>
</property>
</bean>
</constructor-arg>
</bean>
WSO2 was not implementing the SAML 2.0 specification correctly. The specification requires that Single Logout with HTTP-* bindings is done using front-end channel (= through user's browser) - which makes the HTTP session available and allows Spring SAML to terminate it correctly. I believe that this issue was never fixed in WSO2.
Spring SAML uses HttpSession for storage of user's state by default. This is also the reason why Spring SAML doesn't support Single Logout with SOAP binding out of the box. It would be possible to implement an application-wide storage of Spring Security sessions which could be invalidated independently from the HttpSession (and therefore work-around the WSO2's limitation), but this is not configured by default (and I have never tried it).

Pre-Authentication / Single SignOn using Spring Security

I am developing two web applications where one is a server app and the other is a client app, both are using Spring Security. My use case is such that after a user logs into the server app, the user can then access the client app from links within the server app. Since the user should not have to log in again when they click on these links (part of my requirements), I decided to use a strategy similar to Single SignOn in order to forward their authentication information from the server app to the client app.
On the client app, I am using Spring Security's RequestHeaderAuthenticationFilter to look for a custom request header that is set by the server app.
If this custom header is found, do I have to do any further validation that this request is trustworthy? In Spring's Pre-Authentication doc, RequestHeaderAuthenticationFilter does not perform any authentication and will assume the request to be from the user specified in the SM_USER attribute. How do I ensure that the request is genuine?
How do I send the user from one app to another with a custom header in the http request? Redirecting the request does not work as the header information will be lost. Forwarding does not work as the forwarded request does not go through the configured Spring Security filters on the client app, thus the request is never "authenticated" and no session is created.
Since I didn't receive any responses, I changed my approach slightly in order to achieve the same SSO behavior. I am answering my own question here to close this issue.
Instead of using the RequestHeaderAuthenticationFilter, I subclassed Spring's AbstractPreAuthenticatedProcessingFilter which retrieves the Principal and Credentials from the HttpRequest. I then implemented a custom preAuthenticatedUserDetailsService that will validate the Credentials with the server app before loading the UserDetails.
As for #2, I am no longer using custom headers in the initial pre-authenticated login request. I am simply appending the principal (username) and credentials as url parameters to the initial pre-authenticated "login" request to the client app. Since the communicated between the two apps are secured via SSL, I figured that should be safe.
This is what my security configuration looks like now:
<b:bean id="http403EntryPoint" class="org.springframework.security.web.authentication.Http403ForbiddenEntryPoint" />
<b:bean id="navigatorPreAuthFilter" class="com.example.NavigatorPreAuthenticatedProcessingFilter">
<b:property name="authenticationManager" ref="authenticationManager" />
</b:bean>
<http auto-config="false" entry-point-ref="http403EntryPoint">
<custom-filter position="PRE_AUTH_FILTER" ref="navigatorPreAuthFilter" />
<session-management session-fixation-protection="newSession" />
<logout logout-success-url="/logout" delete-cookies="JSESSIONID" />
<intercept-url pattern="/index.jsp" access="ROLE_QUESTIONNAIRE_ASSIGNEE"/>
</http>
<b:bean id="preAuthenticatedUserDetailsService" class="com.example.NavigatorPreAuthenticatedUserDetailsService" />
<b:bean id="preauthAuthProvider" class="org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider">
<b:property name="preAuthenticatedUserDetailsService" ref="preAuthenticatedUserDetailsService" />
</b:bean>
<authentication-manager alias="authenticationManager">
<authentication-provider ref="preauthAuthProvider"/>
</authentication-manager>

Spring Security: invalid-session-url versus logout-success-url

I am using Spring-Security 3.1. Before I added invalid-session-url attribute of session management, it was correctly redirecting to logout page. However, after adding invalid-session-url it is redirecting to session expire page even I click on logout button.
Also, after session-timeout period if I load login page it redirects to session expired page.
I have to check for session-expiry and redirect user to session expired page if session is expired. However, after usage of invalid-session-url tag it redirects me to session expire page even for login and logout scenario.
In some of the posts it is advised not to use invalid-session-url. However, I am unable to understand that then how would I be able to show session expire page after actual session expire.
Any help will be appreciated.
By default, the logout process will first invalidate the session, hence triggering the session management to redirect to the timeout page. By specifying invalidate-session="false" will fix this behavior.
<sec:logout logout-success-url="/logout" invalidate-session="false"
delete-cookies="JSESSIONID" />
The session expiry is limited to detecting an invalid session cookie in a submitted request. If your logout doesn't remove the session cookie, then it will be resubmitted if you access the site again, which will trigger the invalid session URL. This is explained in the reference manual. I would read that and the accompanying footnote. As described there, you need to remove the session cookie, which may or may not work depending on your container.
Try with adding following in your security configuration.
<http>
<logout delete-cookies="JSESSIONID" />
</http>

Spring security is not deleting remember me cookie when I logout

I have a login page with a remember me checkbox when i actually checkbox and login it works and creates the cookie for me logging in the problem is when I logout it redirects me just fine but for some reason it keeps the rememberMe Cookie active so when I get back into the application from another page it immediately logs me in
What are some things I can look so that I can delete the cookie when i logout.
Try to configure your custom logout page if it differs from '/j_spring_security_logout'.
<http>
<logout logout-success-url="/logout.htm"/>
</http>
Specifying 'logout-success' parameter you say Spring that it have to delete the cookie after request with such address.
NOTE: any code mapped to this link ('/logout.htm') will be never executed 'cause of standard spring filters.

Resources