how to configure session time out in spring acegi framework? - time

We are using acegi security for my spring application.
Can you please help how to make user to session time out by 5 mins and go back to login screen?
I tried to configure session-timeout in web.xml. But it is not working.
Thank you for your help and time.
I realized that i need to keep 5 min = 300000 mill secconds on expiring tickets in acegi security configuration xml.
Now i have another questions that how to redirect to application home page on login. Currently it is trying to go to the page where it previously logged out. But i want to make it as home page on what ever condition.
Your help is greatly appreciated. Thank you.

to get forwared to a specific url after a timeout (defined in the web.xml), you may use
<http>
...
<session-management invalid-session-url="/sessionTimeout.htm" />
</http>
Session Management docu

Changing following expiration policy, we can make session log out within time
<bean
id="serviceTicketExpirationPolicy"
class="org.jasig.cas.ticket.support.MultiTimeUseOrTimeoutExpirationPolicy">
<constructor-arg
index="0"
value="1" />
<constructor-arg
index="1"
value="600000" />
</bean>
Cas expiration policies gives more information.
To redirect to login page use following:
<property name="alwaysUseDefaultTargetUrl" value="true"/>
in casProcessingFilter bean configuration

Related

Spring Security - Is SavedRequestAwareAuthenticationSuccessHandler broke?

TLDR: Spring is destroying the current HTTP session when redirecting to the login page; this destroys the ability to navigate to the DefaultSavedRequest after login. Why is this happening?
Details -
I am maintaining a legacy Spring application:
Spring Core version 3.1.0
Spring Security version 3.1.0
When trying to utilize SavedRequestAwareAuthenticationSuccessHandler in my login configuration, it is not working. Here is what seems to be happening:
HTTP GET to secured resource: http://localhost:8080/myapp/viewWorkOrder?workOrderNumber=315261
Spring correctly determines that I am not logged in and saves my request:
DEBUG o.s.s.w.s.HttpSessionRequestCache - DefaultSavedRequest added to Session: DefaultSavedRequest[http://localhost:8080/myapp/viewWorkOrder?workOrderNumber=315261]
Spring correctly redirects to my login page:
DEBUG o.s.security.web.FilterChainProxy - /login.jsp at position 1 of 9 in additional filter chain; firing Filter: 'ChannelProcessingFilter'
Spring destroys the current session which effectively destroys the ability to later use the DefaultSavedRequest:
DEBUG o.s.s.w.s.HttpSessionEventPublisher - Publishing event: org.springframework.security.web.session.HttpSessionDestroyedEvent[source=org.apache.catalina.session.StandardSessionFacade#b25f027]
Why or what is causing the current session to be destroyed?
Here are the pertinent configuration details:
<bean id="savedRequestAwareAuthenticationSuccessHandler"
class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">
<property name="defaultTargetUrl" value="/postLogin" />
<property name="targetUrlParameter" value="targetUrl" />
<property name="alwaysUseDefaultTargetUrl" value="false" />
</bean>
<security:http auto-config="false">
<!-- Override default login and logout pages -->
<security:form-login login-page="/login.jsp"
login-processing-url="/j_spring_security_check"
authentication-failure-url="/login.jsp?login_error=1"
authentication-success-handler-ref="savedRequestAwareAuthenticationSuccessHandler"
/>
<security:session-management session-fixation-protection="none"/>
Note that the inclusion of session-management does not seem to affect the feature either way.
Well, this is embarrassing but in the interest of being a good citizen on stack overflow I thought I would share what I found.
After setting a breakpoint in the Spring HttpSessionEventPublisher to see if the stack might give me a clue, it certainly did. Here is a screenshot:
You'll notice that login.jsp is on the stack. Being new to this particular application, I hadn't really even suspected the JSP but here is what I found:
Obviously, removing this scriptlet solved my issue. Now I just wonder why someone did it and what I broke in the process :)

Spring Security Twitter Access Token

I'm trying to get the ability to write to someone's Twitter account through Java and Spring Social.
Whenever I request write access through my application on twitter, I get the following exception:
org.springframework.social.NotAuthorizedException: Invalid or expired token
org.springframework.social.twitter.api.impl.TwitterErrorHandler.handleClientErrors(TwitterErrorHandler.java:104)
org.springframework.social.twitter.api.impl.TwitterErrorHandler.handleError(TwitterErrorHandler.java:58)
org.springframework.web.client.RestTemplate.handleResponseError(RestTemplate.java:537)
However, when I turn off access, I don't get this exception, but I (obviously) lose the ability to write. From all the research I have done, I have yet to be able to find anything about spring social except that I need an access token. I cannot find Spring Social documentation that tells me where to get that.
Anyway, this is in my controller:
#Autowired
ConnectionRepository connectionRepository
private Twitter getTwitter() {
connectionRepository.findPrimaryConnection(Twitter.class).api
}
#RequestMapping(value = "/connect/twitter/connect/twitter")
String loggedIn(Model model) {
if (twitter?.authorized) {
model.addAttribute("screenName", twitter.userOperations().screenName)
twitter.timelineOperations().updateStatus("Welcome to Miami #helloWorld")
HOME
}
else {
"redirect:/twitter"
}
}
My ConnectionRepository implementation is a basic one for MongoDB. I don't think it is the issue, but if it is it is nearly identical to:
https://github.com/CarloMicieli/spring-social-mongo/blob/master/src/main/java/org/springframework/social/connect/mongo/MongoConnectionRepository.java
Here is my dispatch xml:
<bean class="org.springframework.social.connect.web.ConnectController">
<property name="applicationUrl" value="http://localhost:8081/MinnesotaCows/" />
</bean>
<bean class="org.springframework.social.connect.web.ProviderSignInController">
<property name="applicationUrl" value="http://localhost:8081/MinnesotaCows/" />
<property name="signUpUrl" value="/register" />
</bean>
<bean id="twitterConnectionFactory"
class="org.springframework.social.twitter.connect.TwitterConnectionFactory">
<constructor-arg value="bUC8VEWgkfkeTXuTBuxCg" />
<constructor-arg value="5I1CNYKBCkNbsbgL2JfTNdSnSA9JVY4KHI4myxV7k4" />
</bean>
<bean id="connectionFactoryLocator"
class="org.springframework.social.connect.support.ConnectionFactoryRegistry">
<property name="connectionFactories">
<list>
<ref bean="twitterConnectionFactory" />
</list>
</property>
</bean>
<bean id="textEncryptor" class="org.springframework.security.crypto.encrypt.Encryptors"
factory-method="noOpText" />
Note: I'm running at localhost. Could the problem be that? Since there is no callback? Also, I'm not using the signUpUrl in the ProviderSignInController for anything. I'm not quite sure what that is for either.
Anyone have any ideas on what I might be doing wrong - or how I can exactly get the access token through the API?
Thanks for your time!
I haven't tested CarloMicieli's mongo based connection repositories, but looking the code I can see that primary connection is the first connection created. This is the same behavior that the built in jdbc based repository in Spring Social has. But I think it's wrong, primary connection should be always the last issued connection/login to the provider (the connection with rank 1 can be expired even though there are newer connections).
You could try to empty the connections collection in your mongo db and test if your code works after that. If the token works then, it is the issue that I described.
I have created my own mongo based social repositories that rank the connections by timestamp and order them so that the last issued connection is the primary one. That way you can issue multiple logins and the last login will be the primary connection.
See reference from github: https://github.com/trautonen/spring-social-mongodb/tree/master/src/main/java/org/eluder/spring/social/mongodb
You also defined ConnectController which map the social provider connection paths. You can initialize login flow by doing POST request to /connect/twitter and if completed without problems should result a working connection in your connections collection in mongodb.
See full reference here: http://docs.spring.io/spring-social/docs/1.1.0.RELEASE/reference/htmlsingle/#creating-connections-with-connectcontroller

How to keep the home page i18n on subsequent failed log in attempts

When a user first clicks a link to my homepage, if the link contains ?langId=fr_FR the page displays in French; so far so good. If the user makes a failed attempt to log in the page will display the error message in French, which is perfect. The problem is if a second failed attempt is made to log in. In this case the page language defaults to English.
I am not sure how to keep the page in French for the above case (i.e. any subsequent requests when the initial url contained langId=fr_FR). Should I be using a CookieLocaleResolver instead of a SessionLocaleResolver?
The site uses Spring Security and I have implemented a filter which runs before the Spring Security filters. This filter will set the LocaleContextHolder using the langId request parameter. This works great for the initial log in attempt. Any other requests made and I loose the langId parameter.
Is there something I can do in the loadByUserName() method that will allow me to persist the original langId?
Here is the config for the resolver and interceptor
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver" >
<property name="defaultLocale" value="en" />
</bean>
<mvc:interceptors>
<bean id="localeChangeInterceptor"
class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="langId" />
</bean>
</mvc:interceptors>
EDIT
Using a CookieLocaleResolver instead of a SessionLocaleResolver does fix this issue. But, if users disable cookies then I am back to square one. I'd like to find a way to keep the page in French upon multiple log in attempts for a user. Any help is really appreciated Thank you!
The problem is exactly the sessionlocaleresolver. Since the login attemps fail a new session is created every time ( i believe ) .
Thats why the cookielocaleresolver is working. The cookie is set and remains for your domain.
I do use the sessionlocaleresolver and havent thought about this issue yet.
One way i see should be to include the locale parameter in your form action. It is probably the easiest solution?

Spring Security: Session handling on application start-up

I'm using the following for handling sessions in my web application:
<security:session-management invalid-session-url="/session-expired" session-authentication-strategy-ref="sas"/>
<bean id="sas"
class="org.springframework.security.web.authentication.session.ConcurrentSessionControlStrategy">
<constructor-arg name="sessionRegistry"
ref="sessionRegistry" />
<property name="maximumSessions" value="1" />
</bean>
Whenever I start my application (usually on Tomcat 7) and I try accessing my log-in page, it goes to the /session-expired url. Why is this happening? Shouldn't all the sessions be invalidated once the application has stopped? Or is this more of a browser session issue?
You could still have JSESSIONID cookie on your browser from previous session which no longer valid once you shutdown tomcat, hence you get redirected to the invalid session page. Try deleting your cookies first before accessing the app for the first time after a server start, and check if the behavior is as you intended

Spring security with AD Authentication and Database Authorization

I'm trying to implement the solution of this question
Spring Security 3 Active Directory Authentication, Database Authorization
but i don't understand how to use the MyAuthoritySupplementingProvider .
Is there someone that can help me?
i think MyAuthoritySupplementingProvider should be specified in
<beans:bean id="activeDirectoryAuthenticationProvider"
class="xxx.package.MyAuthoritySupplementingProvider">
<beans:constructor-arg value="mydomain" />
<beans:constructor-arg value="ldap://my URL :389" />
<beans:property name="convertSubErrorCodesToExceptions" value="true"/>
</beans:bean>
i am not sure weather this will work or not but to get more detail you should refer to book "Spring Security 3" Chapter 9 for ldap and active directory configuration and options, this will help you understand this in better way instead of just going through SO post.

Resources