spring security session not behaving as expected - spring-mvc

I've just gone through implementing a SessionCounterListener in my spring mvc webapp as per http://www.mkyong.com/servlet/a-simple-httpsessionlistener-example-active-sessions-counter/ .
I am seeing some behavior that I did not expect and have two questions.
Question 1.
When I hit my login.jsp for the first time after server restart, the session counter by 1 even before I login (not expected).
For example when I go to the login page...
sessionCreated - add one session into counter:1
And then when I go to hit the log out button the session count is decreased by one (which is fine) but immediately after the session count is increased by 1 (not expected).
For example when I hit the logout button...
sessionDestroyed - deduct one session from counter:0
sessionCreated - add one session into counter:1
It is as if everytime I go to the login page the count is increased by 1. I would expect that the count is only increased after successful login.
Can someone help me understand what is happening here?
Question 2.
When I log in as a different user in my application whilst the first user is still logged in I don't get a new session counter. i.e. I don't think it is not creating a new sessions for the new user.
Again I need help to understand please.
Here is my spring security settings....
<http pattern="/login.htm" security="none"/>
<http use-expressions="true" auto-config="false" entry-point-ref="loginUrlAuthenticationEntryPoint">
<!-- custom filters -->
<custom-filter position="FORM_LOGIN_FILTER" ref="twoFactorAuthenticationFilter" />
<custom-filter ref="securityLoggingFilter" after="SECURITY_CONTEXT_FILTER"/>
<!-- session management -->
<session-management
invalid-session-url="/sessionExpired.htm"
session-authentication-error-url="/alreadyLoggedIn.htm">
<concurrency-control
max-sessions="1"
expired-url="/sessionExpiredDuplicateLogin.htm"
error-if-maximum-exceeded="false" />
</session-management>
<!-- error handlers -->
<access-denied-handler error-page="/accessDenied.htm"/>
<!-- logout -->
<logout logout-success-url="/logout.htm" invalidate-session="true" delete-cookies="JSESSIONID" />
<!-- authorize pages -->
<intercept-url pattern="/home.htm" access="isAuthenticated()" />
<intercept-url pattern="/shortsAndOvers.htm" access="isAuthenticated()" />
<intercept-url pattern="/shortsAndOversDaily.htm" access="isAuthenticated()" />
<intercept-url pattern="/birtpage.htm" access="isAuthenticated()" />
<intercept-url pattern="/reports/show.htm" access="isAuthenticated()" />
</http>
<beans:bean id="loginUrlAuthenticationEntryPoint" class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint">
<beans:property name="loginFormUrl" value="/login.htm" />
</beans:bean>
<beans:bean id="successHandler" class="com.me.reporting.security.CustomSavedRequestAwareAuthenticationSuccessHandler">
<beans:property name="defaultTargetUrl" value="/home.htm" />
</beans:bean>
<beans:bean id="failureHandler" class="com.me.reporting.security.CustomSimpleUrlAuthenticationFailureHandler">
<beans:property name="defaultFailureUrl" value="/loginfailed.htm" />
</beans:bean>

you probably are thinking about session in different context.
take a look at JSESSION cookie in firebug while clicking around your application, maybe it will give you some answers :)
HttpSessionListener probably is invoked each time JSESSIONID changes, so:
You get to login.jsp page - session is created, JSESSIONID changes, sessionCreated is invoked. You are loggin out: sessionDestroyed is invoked, session is invalidated ( not sure here, just guessing ), counter is decreased. But what happens after login out? You are probably redirected to /logout.htm and new session is created.

Related

Remember-me not working in Spring MVC in spring-security, how can I check why cookie is not getting created

I created remember-me in spring-security and also button in front end, but cookie is not getting created.
my spring security.xml
<logout success-handler-ref="logoutSuccessHandler" />
<remember-me key="_spring_security_remember_me"
user-service-ref="userDetailsService" />

Spring Mvc Session Creation only after login

In my project i am using session and my deafult url is "index". problem is when i run project session is created. But i want to create session only after the user is logged in to the project.
This is my code
<form-login login-page="/index" default-target-url="/"
authentication-failure-url="/login?error"
username-parameter="username"
password-parameter="password" />
<logout logout-success-url="/login?logout" delete-cookies="JSESSIONID" />
<access-denied-handler error-page="/Access_Denied" />
<session-management invalid-session-url="/login?timeout"/>
And in web.xml i give timeout like
<session-config>
<session-timeout>5</session-timeout>
</session-config>
i used ifrequired too Then to spring is creating session after my default url is hit.
What should i do?
what changed i need to do?
need valuable guidance
By default the jsp page sets the session flag to true. Set this in your index page jsp and the session won't get created.
<%# page session="false" %>

Spring OAuth 2 Call /oauth/token Resulted in 401 (Unauthorized)

Greeting everyone, I try to configure simple authorization code flow via Spring Security OAuth.
I tested my authorisation and resource server configuration via following approaches:
Create a web application as client and use its page to fire http post call to /oauth/authorize.
After getting code, I use the same page to
fire another http post with code and get token.
At the end, I use
curl -H to place token inside header and get response from protected
resource.
But when I try to use rest template. It throw error message 401 Unauthorised error.
Server side - security configure:
<http auto-config="true" pattern="/protected/**"
authentication-manager-ref="authenticationManager">
<custom-filter ref="resourceFilter" before="PRE_AUTH_FILTER" />
<csrf disabled="true" />
</http>
<http auto-config="true">
<intercept-url pattern="/**" access="hasRole('ROLE_USER')" />
<form-login default-target-url="/admin.html" />
<logout logout-success-url="/welcome.html" logout-url="/logout"/>
<csrf disabled="true" />
</http>
<authentication-manager alias="authenticationManager">
<authentication-provider>
<user-service>
<user name="admin" password="123456" authorities="ROLE_USER,ROLE_ADMIN" />
</user-service>
</authentication-provider>
</authentication-manager>
Server side - authorisation and resource configure:
<oauth:authorization-server
client-details-service-ref="clientDetails" error-page="error">
<oauth:authorization-code />
</oauth:authorization-server>
<oauth:client-details-service id="clientDetails">
<oauth:client client-id="admin" secret="fooSecret" />
</oauth:client-details-service>
<oauth:resource-server id="resourceFilter" />
Client Side:
<oauth:client id="oauth2ClientContextFilter" />
<oauth:resource id="sso" client-id="admin"
access-token-uri="http://localhost:8080/tough/oauth/token"
user-authorization-uri="http://localhost:8080/tough/oauth/authorize"
use-current-uri="true" client-secret="secret"
client-authentication-scheme="header" type="authorization_code"
scope="trust" />
<oauth:rest-template id="template" resource="sso"/>
If anyone knows where goes wrong, please do let me know.
There were two issues with my configuration above.
I noticed my client used wrong secret to communicate with authorization server.
Token endpoint at authorization server use authentication manager which
serve user authentication. It result
client are rejected all times until I create new security realm for
token endpoint and configure it to use a authentication manger designed for
client.
Note client is different from user. Client is third party want to access resource belong to your user (also called resource owner).
I had the same problem. It helped to add a
org.springframework.security.oauth2.provider.client.ClientDetailsUserDetailsService
to spring securities authentication-manager, glueing the clientDetailsService to the authentication manager. So
<authentication-manager alias="authenticationManager">
...
<authentication-provider user-service-ref="clientDetailsUserDetailsService"/>
...
</authentication-manager>
nearly solved the problem for me. I had one more Issue: Since ClientDetailsUserDetailsService has no default constructor, spring threw Exceptions of the form
org.springframework.aop.framework.AopConfigException: Could not generate CGLIB subclass of class
[class org.springframework.security.oauth2.provider.client.ClientDetailsUserDetailsService]:
Common causes of this problem include using a final class or a non-visible class;
nested exception is java.lang.IllegalArgumentException: Superclass has no null constructors but no arguments were given
Which I could not solve without using a copy of that class receiving the clientDetailsService as property instead of a constructor arg.

Spring Security: access-denied-handler doesn't forward to error page

I'm fresh off the boat to Spring Security so excuse me if this seems awfully trivial..
I try to put the Spring Security mechanism in my MVC project, but for some reason the access-denied-handler doesn't send my unauthorized user to the denied access page and instead chooses to present the login page.
Here is my Http tag in the security-context.xml:
<http authentication-manager-ref="dao-auth"
access-decision-manager-ref="accessDecisionManager"
disable-url-rewriting="true">
<intercept-url pattern="/pages/home.html" access="USER"></intercept-url>
<intercept-url pattern="/home" method="GET" access="USER"></intercept-url>
<intercept-url pattern="/logout" access="USER"></intercept-url>
<intercept-url pattern="/denied" access="ROLE_ANONYMOUS"></intercept-url>
<intercept-url pattern="/error" access="ROLE_ANONYMOUS,USER"></intercept-url>
<intercept-url pattern="/" access="ROLE_ANONYMOUS,USER"></intercept-url>
<intercept-url pattern="/pages/**" access="ROLE_ANONYMOUS,USER"></intercept-url>
<intercept-url pattern="/resources/**" access="ROLE_ANONYMOUS,USER"></intercept-url>
<form-login login-page="/login" authentication-failure-url="/denied"
default-target-url="/home" />
<logout invalidate-session="true" logout-success-url="/"
logout-url="/logout" />
<access-denied-handler error-page="/denied" />
<session-management invalid-session-url="/login">
<concurrency-control max-sessions="1"
expired-url="/login" />
</session-management>
</http>
Basically the way I test it is I try to access the /home path from the ROLE_ANONYMOUS user and instead get thrown to the /login one.
Also, can't figure out how to debug this thing or where I find the logs (feels like there are somewhere out there..)
Thanks to all responders :)
1.Spring security looks for Authentication object in security context first. If there is no authentication object (basically a principal) found in the security context, it will direct you to the login page.
2.If it finds Authentication object, then it will use the principal's authorities to do authorization.
3.When Login screen is presented, the user entered credentials are authenticated and if not authenticated, then you can throw a bad credentials exception to show the access denied error.

After logout back button should always direct to login page

I'm using spring security and this is the configuration file,
<intercept-url pattern="/login.htm" access="permitAll"/>
<intercept-url pattern="/admin.htm" access="hasRole('ROLE_ADMIN')"/>
<intercept-url pattern="/common.htm" access="hasRole('ROLE_USER')"/>
<form-login
login-page="/login.htm"
authentication-failure-url="/login.htm?error=true"
default-target-url="/loginPlease.htm"/>
<logout
invalidate-session="true"
logout-success-url="/login.htm"
logout-url="/logout.htm"/>
<session-management >
<concurrency-control max-sessions="1"
error-if-maximum-exceeded="false"
expired-url="/login.htm"/>
</session-management>
After logging out if a person enters back button he is redirected to the last page, but I want him to be always redirected to the login page. This problem also arises if the user directly enters the link in the browser, even if he has logged out, he is redirected to that page.
I think you need to add
<intercept-url pattern="/login.htm*" filters="none"/>
which prevents execution of the SessionManagementFilter, as well as every other one. This also means and tags won't work.
Hope it helps.
The inverse of your problem (having people remain logged out when going back after logging out VS. having people remain logged in when going back after logging in) was solved by putting in a cache-management filter.
<mvc:annotation-driven/>
<mvc:interceptors>
<bean id="webContentInterceptor"
class="org.springframework.web.servlet.mvc.WebContentInterceptor">
<property name="cacheSeconds" value="0"/>
<property name="useExpiresHeader" value="true"/>
<property name="useCacheControlHeader" value="true"/>
<property name="useCacheControlNoStore" value="true"/>
</bean>
</mvc:interceptors>

Resources