Spring Security Authentication Issue - spring

We need help with regard to Authentication using Spring Security. When we try to key in the login credentials for our application and click on submit, We are getting an invalid credentials error.
we have checked the database and the authentication details that we are using to login seems to be correct. But still getting the below exception
[DEBUG,LdapAuthenticationProvider,http-localhost%2F127.0.0.1-8080-1] Processing authentication request for user: admin
[DEBUG,FilterBasedLdapUserSearch,http-localhost%2F127.0.0.1-8080-1] Searching for user 'admin', with user search [ searchFilter: 'sAMAccountName={0}', searchBase: 'DC=ad,DC=infosys,DC=com', scope: subtree, searchTimeLimit: 0, derefLinkFlag: true ]
[INFO,SpringSecurityLdapTemplate,http-localhost%2F127.0.0.1-8080-1] Ignoring PartialResultException
[WARN,LoggerListener,http-localhost%2F127.0.0.1-8080-1] Authentication event AuthenticationFailureBadCredentialsEvent: admin; details: org.springframework.security.web.authentication.WebAuthenticationDetails#957e: RemoteIpAddress: 127.0.0.1; SessionId: DEC9042719AA53736897C4383DCF8FE8; exception: Bad credentials
[DEBUG,UsernamePasswordAuthenticationFilter,http-localhost%2F127.0.0.1-8080-1] Authentication request failed: org.springframework.security.authentication.BadCredentialsException: Bad credentials
Im trying to connect to the sqlserver2008 database and trying to login.Below is the security.xml file that we are using
<http auto-config='false' realm="MaskIT Realm" access-denied-page="/403.jsp">
<intercept-url pattern="/*.htm" access="ROLE_ADMIN,ROLE_REQUESTOR,ROLE_APPROVER" />
<intercept-url pattern="/login.jsp" access="IS_AUTHENTICATED_ANONYMOUSLY" />
<form-login login-page="/login.jsp"
authentication-failure-url="/login.jsp?login_error=1"
default-target-url="/redirect.jsp" />
<http-basic />
<intercept-url pattern="/securityService" access="IS_AUTHENTICATED_ANONYMOUSLY"
requires-channel="http" />
<logout logout-success-url="/login.jsp" />
</http>
<b:bean id="myAuthenticationProvider"
class="com.infosys.setl.himi.maskit.security.SwitchingAuthenticationProvider">
<b:constructor-arg ref="paramManager" />
<b:property name="providers">
<b:list>
<b:ref local="daoAuthenticationProvider" />
<b:ref local="ldapProvider" />
</b:list>
</b:property>
</b:bean>
<b:bean id="daoAuthenticationProvider"
class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
<b:property name="userDetailsService" ref="userDetailsService" />
<!-- <b:property name="passwordEncoder" ref="passwordEncoder" /> -->
</b:bean>
<b:bean id="userDetailsService"
class="org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl">
<b:property name="dataSource" ref="dataSourceMSSQL" />
<b:property name="usersByUsernameQuery">
<b:value>SELECT user_id ,password,active FROM sec_users
WHERE
user_id=?</b:value>
</b:property>
<b:property name="authoritiesByUsernameQuery">
<b:value>SELECT a.user_id AS user_id,b.roleName AS roleName FROM
sec_users a, emaskit_roles b
WHERE a.roleID = b.roleID AND
a.user_id=?</b:value>
</b:property>
</b:bean>
I would like to know how & when the sql query is getting executed for checking the authentication. Is it calling any java class( so that i can debug the code and check where it is failing) to perform the check or is it done internally by the Spring framework.
Please Assist. Thanks in Advance

What brothers me is that you logfile shows that you try to use an Ldap for authentication (LdapAuthenticationProvider) but you xml file shows that you try to use a DaoAuthenticationProvider.
I really think you massed up you deployment, either you looked/deployed on the wrong server or you did not deployed the (actual version) application at all.
In addition there is a mistake in you configuration: you have to tell spring security to use your daoAuthenticationProvider:
add this:
<authentication-manager alias="authenticationManager">
<authentication-provider ref="daoAuthenticationProvider"/>
</authentication-manager>

Related

Why is my Spring oauth server always returning the same access token?

I'm using Spring 4.3.8.RELEASE and spring-boot 1.5.3.RELEASE. I want to serve oauth access tokens to applications with the proper credentials. I'm using the org.springframework.security.oauth2.provider.token.store.JdbcTokenStore class to do this. However, I'm noticing that each time I connect with a client to my server that I have set up with OAuth, the server repeatedly returns the same access token, even after server restarts. My OAuth server configuration is below
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:oauth="http://www.springframework.org/schema/security/oauth2"
xmlns:sec="http://www.springframework.org/schema/security" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/security/oauth2 http://www.springframework.org/schema/security/spring-security-oauth2-2.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<http pattern="/oauth/token" create-session="stateless" authentication-manager-ref="clientAuthenticationManager" xmlns="http://www.springframework.org/schema/security">
<intercept-url pattern="/oauth/token" access="IS_AUTHENTICATED_FULLY" />
<anonymous enabled="false" />
<http-basic entry-point-ref="clientAuthenticationEntryPoint" />
<!-- include this only if you need to authenticate clients via request parameters -->
<custom-filter ref="clientCredentialsTokenEndpointFilter" after="BASIC_AUTH_FILTER" />
<access-denied-handler ref="oauthAccessDeniedHandler" />
</http>
<!-- The OAuth2 protected resources are separated out into their own block
so we can deal with authorization and error handling separately. This isn't
mandatory, but it makes it easier to control the behaviour. -->
<http pattern="/oauth/(users|clients)/.*" request-matcher="regex"
create-session="stateless" entry-point-ref="oauthAuthenticationEntryPoint"
use-expressions="true" xmlns="http://www.springframework.org/schema/security">
<anonymous enabled="false" />
<intercept-url pattern="/oauth/users/([^/].*?)/tokens/.*"
access="#oauth2.clientHasRole('ROLE_CLIENT') and (hasRole('ROLE_USER') or #oauth2.isClient()) and #oauth2.hasScope('write')"
method="DELETE" />
<intercept-url pattern="/oauth/users/.*"
access="#oauth2.clientHasRole('ROLE_CLIENT') and (hasRole('ROLE_USER') or #oauth2.isClient()) and #oauth2.hasScope('read')"
method="GET" />
<intercept-url pattern="/oauth/clients/.*"
access="#oauth2.clientHasRole('ROLE_CLIENT') and #oauth2.isClient() and #oauth2.hasScope('read')"
method="GET" />
<custom-filter ref="resourceServerFilter" before="PRE_AUTH_FILTER" />
<access-denied-handler ref="oauthAccessDeniedHandler" />
<expression-handler ref="oauthWebExpressionHandler" />
</http>
<!-- The OAuth2 protected resources are separated out into their own block
so we can deal with authorization and error handling separately. This isn't
mandatory, but it makes it easier to control the behaviour. -->
<http pattern="/me/**" create-session="never"
entry-point-ref="oauthAuthenticationEntryPoint"
access-decision-manager-ref="accessDecisionManager"
xmlns="http://www.springframework.org/schema/security">
<anonymous enabled="false" />
<intercept-url pattern="/me" access="ROLE_USER,SCOPE_READ" />
<custom-filter ref="resourceServerFilter" before="PRE_AUTH_FILTER" />
<access-denied-handler ref="oauthAccessDeniedHandler" />
</http>
<bean id="oauthAuthenticationEntryPoint"
class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint">
<property name="realmName" value="sparklr2" />
</bean>
<bean id="clientAuthenticationEntryPoint"
class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint">
<property name="realmName" value="sparklr2/client" />
<property name="typeName" value="Basic" />
</bean>
<bean id="oauthAccessDeniedHandler"
class="org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler" />
<bean id="clientCredentialsTokenEndpointFilter"
class="org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter">
<property name="authenticationManager" ref="clientAuthenticationManager" />
</bean>
<bean id="accessDecisionManager" class="org.springframework.security.access.vote.UnanimousBased"
xmlns="http://www.springframework.org/schema/beans">
<constructor-arg>
<list>
<bean class="org.springframework.security.oauth2.provider.vote.ScopeVoter" />
<bean class="org.springframework.security.access.vote.RoleVoter" />
<bean class="org.springframework.security.access.vote.AuthenticatedVoter" />
</list>
</constructor-arg>
</bean>
<authentication-manager id="clientAuthenticationManager"
xmlns="http://www.springframework.org/schema/security">
<authentication-provider user-service-ref="clientDetailsUserService" />
</authentication-manager>
<authentication-manager alias="authenticationManager"
xmlns="http://www.springframework.org/schema/security">
<authentication-provider>
<user-service id="userDetailsService">
<user name="marissa" password="koala" authorities="ROLE_USER" />
<user name="paul" password="emu" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager>
<bean id="clientDetailsUserService"
class="org.springframework.security.oauth2.provider.client.ClientDetailsUserDetailsService">
<constructor-arg ref="clientDetails" />
</bean>
<bean id="tokenStore" class="org.springframework.security.oauth2.provider.token.store.JdbcTokenStore">
<constructor-arg ref="dataSource" />
<property name="authenticationKeyGenerator">
<bean class="org.springframework.security.oauth2.UniqueAuthenticationKeyGenerator" />
</property>
</bean>
<bean id="tokenServices"
class="org.springframework.security.oauth2.provider.token.DefaultTokenServices">
<property name="tokenStore" ref="tokenStore" />
<property name="tokenEnhancer" ref="tokenEnhancer" />
<property name="supportRefreshToken" value="true" />
<property name="clientDetailsService" ref="clientDetails" />
</bean>
<bean id="tokenEnhancer"
class="org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter" />
<bean id="requestFactory"
class="org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory">
<constructor-arg name="clientDetailsService" ref="clientDetails" />
</bean>
<bean id="approvalStore"
class="org.springframework.security.oauth2.provider.approval.TokenApprovalStore">
<property name="tokenStore" ref="tokenStore" />
</bean>
<oauth:authorization-server
client-details-service-ref="clientDetails" token-services-ref="tokenServices">
<oauth:client-credentials />
</oauth:authorization-server>
<oauth:resource-server id="resourceServerFilter" entry-point-ref="entry"
resource-id="myclientAssignment" token-services-ref="tokenServices" />
<bean id="entry" class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint">
<constructor-arg value="/assignment" />
</bean>
<context:property-placeholder location="classpath:application.properties"/>
<oauth:client-details-service id="clientDetails">
<oauth:client client-id="${myclient.client.id}"
authorized-grant-types="client_credentials" authorities="ROLE_CLIENT"
access-token-validity="30"
scope="read,write" secret="${myclient.client.secret}" />
</oauth:client-details-service>
<mvc:default-servlet-handler />
<oauth:expression-handler id="oauthExpressionHandler" />
<oauth:web-expression-handler id="oauthWebExpressionHandler" />
<http pattern="/api/**"
create-session="never"
entry-point-ref="oauthAuthenticationEntryPoint"
access-decision-manager-ref="accessDecisionManager"
xmlns="http://www.springframework.org/schema/security">
<anonymous enabled="false" />
<intercept-url pattern="/**"
access="IS_AUTHENTICATED_FULLY"/>
<custom-filter ref="resourceServerFilter"
before="PRE_AUTH_FILTER" />
<access-denied-handler ref="oauthAccessDeniedHandler" />
</http>
</beans>
Here's the shell script I'm using to connect to my local server to retrieve the token ...
#!/bin/bash
ret=$(curl http://localhost:8080/myproject/oauth/token \
-u "myclientid:mysecret" \
-d "grant_type=client_credentials")
echo $ret > /tmp/out
cat /tmp/out
access_token=$( sed -e 's/^.*"access_token":"\([^"]*\)".*$/\1/' /tmp/out )
echo $access_token
Edit:
Per Hans' request, here is an example access token
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzY29wZSI6WyJyZWFkIiwid3JpdGUiXSwiZXhwIjoxNDk2ODQ4NDAzLCJhdXRob3JpdGllcyI6WyJST0xFX0NMSUVOVCJdLCJqdGkiOiI4OGMxZjkzZC0wNmRhLTRmYTAtOTM1OS0yZWMxYzU5MWJlMGIiLCJjbGllbnRfaWQiOiJ6aW5jbGVhcm5pbmcifQ.Pf-rjPDj0ZhrNOYuhA0tK8lPLLCzlkqUuFFjb48xskA
and here is a second access token
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzY29wZSI6WyJyZWFkIiwid3JpdGUiXSwiZXhwIjoxNDk2OTUzNTg0LCJhdXRob3JpdGllcyI6WyJST0xFX0NMSUVOVCJdLCJqdGkiOiIxM2I5M2M4Ni05MmIwLTQyY2UtYjFkNS1lZjRiNmZhNzJkMzgiLCJjbGllbnRfaWQiOiJ6aW5jbGVhcm5pbmcifQ.GfSHA_JcQg2WHYCI81lunMFIhxdX6REc4goshB2Lck0
This is sample regular access token which when issued will have 30 seconds expiration for your configuration.
You should see the info message (Failed to find access token for token) at the time a new token is issued.
{
"access_token": "e057a4f3-9872-4b97-803e-938ad6ef32db",
"token_type": "bearer",
"refresh_token": "f9a7ea9a-0fd1-45a9-b8ae-de87eaf61787",
"expires_in": 30,
"scope": "read write"
}
This is expected behavior as spring looks into database to verify if the access token for the authentication is already issued.
Subsequent requests until the expiry of token (30s) will not show the message. This message will show up again after old access token is expired and when new token is issued and it continues.
The below line is where that info message is displayed from
https://github.com/spring-projects/spring-security-oauth/blob/master/spring-security-oauth2/src/main/java/org/springframework/security/oauth2/provider/token/store/JdbcTokenStore.java#L168
Refresh token is set to expire in 30 days by default. The similar log message will appear again when the refresh token expires.
It should work similar for JWT access token too.
This is the sequences of log messages when a new token is issued when you run the application in DEBUG logging level.
2017-06-06 14:06:51.339 DEBUG 28732 --- [nio-9191-exec-1] o.s.s.o.p.token.store.JdbcTokenStore : Failed to find access token for authentication org.springframework.security.oauth2.provider.OAuth2Authentication#8e69d9c0: Principal: org.springframework.security.core.userdetails.User#586034f: Username: admin; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_ADMIN,ROLE_USER; Credentials: [PROTECTED]; Authenticated: true; Details: null; Granted Authorities: ROLE_ADMIN, ROLE_USER
2017-06-06 14:06:51.346 DEBUG 28732 --- [nio-9191-exec-1] o.s.jdbc.core.JdbcTemplate : Executing prepared SQL query
2017-06-06 14:06:51.346 DEBUG 28732 --- [nio-9191-exec-1] o.s.jdbc.core.JdbcTemplate : Executing prepared SQL statement [select token_id, token from oauth_access_token where token_id = ?]
2017-06-06 14:06:51.347 INFO 28732 --- [nio-9191-exec-1] o.s.s.o.p.token.store.JdbcTokenStore : Failed to find access token for token e057a4f3-9872-4b97-803e-938ad6ef32db
2017-06-06 14:06:51.442 DEBUG 28732 --- [nio-9191-exec-1] o.s.jdbc.core.JdbcTemplate : Executing prepared SQL update
2017-06-06 14:06:51.443 DEBUG 28732 --- [nio-9191-exec-1] o.s.jdbc.core.JdbcTemplate : Executing prepared SQL statement [insert into oauth_access_token (token_id, token, authentication_id, user_name, client_id, authentication, refresh_token) values (?, ?, ?, ?, ?, ?, ?)]
2017-06-06 14:06:51.450 DEBUG 28732 --- [nio-9191-exec-1] o.s.jdbc.core.JdbcTemplate : SQL update affected 1 rows
2017-06-06 14:06:51.452 DEBUG 28732 --- [nio-9191-exec-1] o.s.jdbc.core.JdbcTemplate : Executing prepared SQL update
2017-06-06 14:06:51.452 DEBUG 28732 --- [nio-9191-exec-1] o.s.jdbc.core.JdbcTemplate : Executing prepared SQL statement [insert into oauth_refresh_token (token_id, token, authentication) values (?, ?, ?)]
2017-06-06 14:06:51.455 DEBUG 28732 --- [nio-9191-exec-1] o.s.jdbc.core.JdbcTemplate : SQL update affected 1 rows
Why i am getting same access token for multiple login request?
Ashwani has given answer like below in this post
Access Tokens have fixed Life-Time.
Until that period has not expires, access token remains the same.
During that period if you request access token you will receive the same string but will have reset expiration. It would only happen if
Location, Password etc are exactly same as previous request.
Otherwise new token generated. Sometimes Salesforce resets the
expiration time for last expired token and return in response.
Short-lived access tokens and long-lived refresh tokens
There is no way to expire those tokens directly, so instead, the tokens are issued with a short expiration time so that the application is forced to continually refresh them, giving the service a chance to revoke an application’s access if needed.
#Dave, As you have told that, there is no expiry field, so it is non-expiring access token.
Non-expiring access tokens
Non-expiring access tokens are the easiest method for developers. If you choose this option, it is important to consider the trade-offs you are making.
It isn’t practical to use self-encoded tokens if you want to be able to revoke them arbitrarily. As such, you’ll need to store these tokens in some sort of database, so they can be deleted or marked as invalid as needed.
Note that even if the service intends on issuing non-expiring access tokens for normal use, you’ll still need to provide a mechanism to expire them under exceptional circumstances, such as if the user explicitly wants to revoke an application’s access, or if a user account is deleted.
Non-expiring access tokens are much easier for developers testing their own applications. You can even pre-generate one or more non-expiring access tokens for developers and show it to them on the application details screen. This way they can immediately start making API requests with the token, and not worry about setting up an OAuth flow in order to start testing your API.
In summary, use non-expiring access tokens when:
you have a mechanism to revoke access tokens arbitrarily
you don’t have a huge risk if tokens are leaked
you want to provide an easy authentication mechanism to your
developers
you want third-party applications to have offline access to users’
data
Resource Link: Acess token lifetime
How to refresh access token? Rules are given here: https://www.oauth.com/oauth2-servers/access-tokens/refreshing-access-tokens/
How to issue an access token are given here:
+----------+
| Resource |
| Owner |
| |
+----------+
v
| Resource Owner
(A) Password Credentials
|
v
+---------+ +---------------+
| |>--(B)---- Resource Owner ------->| |
| | Password Credentials | Authorization |
| Client | | Server |
| |<--(C)---- Access Token ---------<| |
| | (w/ Optional Refresh Token) | |
+---------+ +---------------+
Figure 5: Resource Owner Password Credentials Flow
The flow illustrated in Figure 5 includes the following steps:
(A) The resource owner provides the client with its username and
password.
(B) The client requests an access token from the authorization
server's token endpoint by including the credentials received
from the resource owner. When making the request, the client
authenticates with the authorization server.
(C) The authorization server authenticates the client and validates
the resource owner credentials, and if valid, issues an access
token.
The authorization server MUST follow the rules:
o require client authentication for confidential clients or for any
client that was issued client credentials (or with other
authentication requirements),
o authenticate the client if client authentication is included, and
o validate the resource owner password credentials using its
existing password validation algorithm.
Resource Link: https://www.rfc-editor.org/rfc/rfc6749#page-47
In your configuration you use a JdbcTokenStore :
So, you have to check the table oauth_client_details : you must have a row with a column access_token_validity where you can change in live the duration in seconds.
Another solution is to delete that row and redeploy your application. Your configuration will create the row again with the value you specified in your configuration and that you were speaking about in the conversation.
I know it is very late to post an answer to this question but here is what I think should be considered.
When configuring an Authorization server, one of the parameters is the accessTokenValiditySeconds.
the point here is that it is your solution:
Here is an example of configuring the Authorization server.
#Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients
.inMemory()
.withClient(ParamsConfig.TRUSTED_CLIENT_ID)
.secret(passwordEncoder.encode(ParamsConfig.TRUSTED_CLIENT_SECRET))
.accessTokenValiditySeconds(10)
.scopes(ParamsConfig.OAUTH_SECURITY_SCOPE)
.authorizedGrantTypes(ParamsConfig.OAUTH_AUTHORIZATION_GRANT_TYPE)
.authorities(ParamsConfig.OAUTH_SECURITY_AUTHORITIES)
.resourceIds(ParamsConfig.OAUTH_SECURITY_RESOURCE_ID);
}
See the accessTokenValiditySeconds that describes two things:
1 - till what time this access token will be valid.
2 - till what time you will be getting the same Access token if you request for an access token.
Note:
This configuration is in Java not xml.
In your case, it should be access-token-validity.

spring security session times out

I am using spring security 4.1, the issue that i face is when i try to login i am sent back to the session expired page several times. I have tried multiple things like adding my own HttpSessionListener also by adding
org.springframework.security.web.session.HttpSessionEventPublisher
but the session keeps expiring. I read in one of the questions the explanation for such behavior
"It's possible for Spring Security to invalidate session in some cases (for example, after logging in, the user gets a new HttpSession)."
I used Fiddler tool to see what is happening, i see user is authenticated but is redirected to session expired page instantly. I want to allow same user to login as many times as he wants. I also read in some places that it will help to move to spring 3.x but i assume it might be for cases when older version of spring was used.
please suggest. Thank You
<http auto-config="true" use-expressions="true"
authentication-manager-ref="authenticationManager">
<session-management
invalid-session-url="/login?eventType=sessionTimedOut"
session-fixation-protection="none"
/>
<intercept-url pattern="/login" access="permitAll" />
<intercept-url pattern="/*" access="hasAnyAuthority('FF_USER','FF_ADMIN')" />
<form-login login-page="/login"
authentication-success-handler-ref="authenticationSuccessHandler"
authentication-failure-handler-ref="customAuthenticationFailureHandler"
login-processing-url="/j_spring_security_check"
username-parameter="j_username"
password-parameter="j_password"
/>
<logout invalidate-session="false" logout-success-url="/login?eventType=logout"
logout-url="/j_spring_security_logout" delete-cookies="JSESSIONID"/>
<csrf token-repository-ref="csrfTokenRepository" />
</http>
<beans:bean id="csrfTokenRepository"
class="org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository">
<beans:property name="headerName" value="X-XSRF-TOKEN" />
</beans:bean>
<beans:bean id="authenticationSuccessHandler" class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">
<beans:property name="defaultTargetUrl" value="/home"/>
<beans:property name="alwaysUseDefaultTargetUrl" value="true"/>
</beans:bean>
<beans:bean id="customAuthenticationFailureHandler" class="*.*.CustomAuthenticationFailureHandler">
<beans:property name="defaultFailureUrl" value="/login?eventType=error"></beans:property>
<beans:property name="baseFailureUrl" value="/login?eventType=error"></beans:property>
</beans:bean>
<beans:bean id="authenticationManager"
class="org.springframework.security.authentication.ProviderManager">
<beans:constructor-arg>
<beans:list>
<beans:ref bean="ldapAuthenticationProvider" />
</beans:list>
</beans:constructor-arg>
<beans:property name="eraseCredentialsAfterAuthentication"
value="true" />
</beans:bean>
<http>
<logout delete-cookies="JSESSIONID" />
</http>
Unfortunately this can't be guaranteed to work with every servlet container, so you will need to test it in your environment[8].
So you need to add a customer logout handler that implements LogoutHandler to LogoutFilter handlers.
<http auto-config="true" use-expressions="true" authentication-manager-ref="authenticationManager">
...
<custom-filter ref="logoutFilter" position="LOGOUT_FILTER" />
...
</http>
<bean id="logoutFilter" class="org.springframework.security.web.authentication.logout.LogoutFilter">
<constructor-arg name="logoutSuccessUrl" value="/login?eventType=logout" />
<!-- implement LogoutHandler, Websphere log out -->
<constructor-arg name="handlers" ref="{customer logout }" />
<property name="filterProcessesUrl" value="/j_spring_security_logout" />
</bean>

Spring Security Pre-Authentication / Login

I did a proof of concept with Spring Security in order to perform pre authentication by using the PRE_AUTH_FILTER filter. It worked OK, but I'd like to know if I can redirect to the login page if the this filter does not work, because I get HTTP 403.
I mean, if the initial request does not contain the SM_USER field in the header, how can I redirect to the login page? I need to consider these two scenarios (when it contains the field - SM_USER -, and when not) and I was not able to get it working. Any ideas about it?
Pra-authentication works smoothly with login authentication in Spring Security. You just setup a working login form configuration, and add the PRE_AUTH_FILTER filter.
Spring only redirects to login page, if after passing the authentication filters, it detects that user is not authenticated when he should be. So if the request contains the expected field in header, the user will be authenticated by the PRE_AUTH_FILTER filter, and will not go to the login page. But if it does not contain one, Spring security will detect a lack of authentication and redirect to login page.
These are my settings:
<http auto-config="true" use-expressions="true" entry-point-ref="http403EntryPoint">
<intercept-url pattern="/login" access="permitAll" />
<intercept-url pattern="/logout" access="permitAll" />
<intercept-url pattern="/accessdenied" access="permitAll" />
<intercept-url pattern="/**" access="hasRole('ROLE_USER')" />
<custom-filter before="PRE_AUTH_FILTER" ref="siteminderFilter" />
<form-login login-page="/login" default-target-url="/list" authentication-failure-url="/accessdenied" />
<logout logout-success-url="/logout" />
</http>
<beans:bean id="siteminderFilter" class="org.springframework.security.web.authentication.preauth.RequestHeaderAuthenticationFilter">
<beans:property name="principalRequestHeader" value="SM_USER"/>
<beans:property name="authenticationManager" ref="authenticationManager" />
<beans:property name="exceptionIfHeaderMissing" value="false" />
</beans:bean>
<beans:bean id="preauthAuthProvider" class="org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider">
<beans:property name="preAuthenticatedUserDetailsService">
<beans:bean id="userDetailsServiceWrapper" class="org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper">
<beans:property name="userDetailsService" ref="customUserDetailsService"/>
</beans:bean>
</beans:property>
</beans:bean>
<authentication-manager alias="authenticationManager">
<authentication-provider user-service-ref="employeeDAO" />
<authentication-provider ref="preauthAuthProvider" />
</authentication-manager>
<beans:bean id="customUserDetailsService" class="com.test.security.CustomUserDetailsService"></beans:bean>
<beans:bean id="http403EntryPoint" class="org.springframework.security.web.authentication.Http403ForbiddenEntryPoint"></beans:bean>

Fail to locate j_spring_security_check in Spring Security

I am working on spring Security, I am facing the issue "Problem accessing /CustomRole/j_spring_security_check"
My web.xml file is as follow
<sec:http auto-config="true" disable-url-rewriting="true"
use-expressions="true">
<!-- When access is refused, will go to the 403.jsp -->
<sec:intercept-url pattern="/login.jsp" filters="none" />
<sec:form-login login-page="/login.jsp"
authentication-failure-url="/login.jsp?error=true"
login-processing-url="/j_spring_security_check.action"
default-target-url="/index.jsp"
always-use-default-target="true" />
<sec:logout logout-success-url="/login.jsp" />
<sec:http-basic />
<!-- An increase in filter and Acegi, this is not the same, can not modify
the default filter, the filter is located in the FILTER_SECURITY_INTERCEPTOR
before> -->
<sec:custom-filter before="FILTER_SECURITY_INTERCEPTOR"
ref="myFilter" />
</sec:http>
<!-- A custom filter, you must include the authenticationManager, accessDecisionManager,
securityMetadataSource three attributes, All control we will achieve in the
three class, explain the specific configuration, see> -->
<beans:bean id="myFilter"
class="com.demo.security.MyFilterSecurityInterceptor">
<beans:property name="authenticationManager" ref="authenticationManager" />
<beans:property name="accessDecisionManager" ref="myAccessDecisionManagerBean" />
<beans:property name="securityMetadataSource" ref="securityMetadataSource" />
</beans:bean>
<!-- The authentication manager, entrance for user authentication, which
implements the UserDetailsService interface can be -->
<authentication-manager alias="authenticationManager">
<authentication-provider user-service-ref="myUserDetailService">
<!-- If the user's password using encryption, you can add a little salt
"" <password-encoder hash="md5"/> -->
</authentication-provider>
</authentication-manager>
<beans:bean id="myUserDetailService" class="com.demo.security.MyUserDetailService" />
<!-- Access decision device, determines whether a user has a role, that
you have sufficient permissions to access a resource -->
<beans:bean id="myAccessDecisionManagerBean" class="com.demo.security.MyAccessDecisionManager">
</beans:bean>
<!-- Resource source data definition, the definition of a resource can be
what role access -->
<beans:bean id="securityMetadataSource"
class="com.demo.security.MyInvocationSecurityMetadataSource" />
After hitting the launch page it open login page successfully.But when i provide login credential and try to hit login it fails and throw error related to "j_spring_security_check"
I have created code as per the available on http://www.programering.com/a/MTNygjMwATY.html

Spring security remember me not working, getting SecurityContex tHolder not populated with remember-me token

i have below code to enable remember me authentication in configuration xml
<remember-me services-ref="rememberMeServices" key="testKeyForBlog" />
<beans:bean id="rememberMeServices" class="com.ringee.web.login.security.controller.CustomTokenBasedRememberMeServices">
<beans:constructor-arg name="key" value="testKeyForBlog"/>
<beans:constructor-arg name="manageUserServiceImpl" ref="manageUserServiceImpl" />
<beans:constructor-arg name="tokenRepository" ref="managePersistentTokenServiceImpl" />
</beans:bean>
i have implemented AbstractRememberMeServices to have custom remember me authentication.
when i enter my login id and password with remember me check box enabled, RememberMeAuthenticationFilter filter is invoked, but below line
SecurityContextHolder.getContext().getAuthentication() == null
where authentication object is not null, which eventually make remember me service not invoked, after running in debug mode , i see below debug message
DEBUG [org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter] (http--127.0.0.1-8080-6) SecurityContex
tHolder not populated with remember-me token, as it already contained: 'com.ringee.web.login.security.controller.CustomUserAuthentication#6ee367b0'
my application doesnt has form login, instead does ajax login, hence i have customized. i have custom entry point.
<http pattern="/**" entry-point-ref="customEntryPoint">
<custom-filter ref="ajaxTimeoutRedirectFilter" after="EXCEPTION_TRANSLATION_FILTER" />
<remember-me services-ref="rememberMeServices" key="testKeyForBlog" />
<custom-filter position="PRE_AUTH_FILTER" ref="ringeeFilter" />
<intercept-url pattern="/index.jsp" access="ROLE_ANONYMOUS" />
<intercept-url pattern="/menu/registration" access="ROLE_ANONYMOUS" />
<custom-filter ref="logOutFilter" position="LOGOUT_FILTER" />
<access-denied-handler ref="accessDeniedHandler" />
</http>
when login with remember me check box enable.. no cookie is been set because remember service is not getting invoked, since it authentication object has present already. dont know what is wrong with my configuration, thanks for you answers

Resources