REST - Creating session - spring

I write application which use Spring Security. Below I wrote my TokenFilter and WebSecurityConfig.
My question is how long SecurityContext does contain logged users?
Next question: is my security configuration session stateless or no? Is SecurityContext replacment for Session?
Does my application fulfill the stateless principle?
public class TokenFilter extends OncePerRequestFilter {
#Autowired
private UserDetailsService userDetailsService;
#Autowired
private TokenHelper tokenHelper;
private String tokenHeader = "Auth";
#Override
protected void doFilterInternal(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse,
FilterChain filterChain) throws ServletException, IOException {
final String authToken = httpServletRequest.getHeader(this.tokenHeader);
final String username = tokenHelper.getUsernameFromToken(authToken);
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
final UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
if (tokenHelper.validateToken(authToken, userDetails)) {
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
userDetails,
null,
userDetails.getAuthorities()
);
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));
SecurityContextHolder.getContext().setAuthentication(authentication);
}
}
filterChain.doFilter(httpServletRequest, httpServletResponse);
}
}
And Security Config:
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private UnauthorizedHandler unauthorizedHandler;
#Autowired
private UserDetailsService userDetailsService;
#Autowired
public void configureAuthentication(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
authenticationManagerBuilder
.userDetailsService(this.userDetailsService)
.passwordEncoder(this.passwordEncoder);
}
#Autowired
public BCryptPasswordEncoder passwordEncoder;
#Autowired
public TokenFilter tokenFilter;
#Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.csrf().disable()
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler)
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers(HttpMethod.POST, "/login").permitAll()
.anyRequest().authenticated();
httpSecurity.addFilterBefore(
tokenFilter,
UsernamePasswordAuthenticationFilter.class
);
httpSecurity.headers().cacheControl();
}
}

SecurityContext is only used to access Authentication instance.
SecurityContext may be stored between your requests. This logic (storing and then restoring for new requests) is implemented in SecurityContextPersistenceFilter which, in turn, delegates this storage logic to SecurityContextRepository.
When you use SessionCreationPolicy.STATELESS, NullSecurityContextRepository is used (it is an implementation of SecurityContextRepository); it does NOT actually store SecurityContext anywhere, and it always 'restores' a fresh (empty) SecurityContext.
SessionCreationPolicy.STATELESS also forbids Spring Security to create http session in any of beans which form its machinery.
So when you use SessionCreationPolicy.STATELESS, the session is never created, and it is certainly not used to store SecurityContext. Each your request will have a fresh security context (with no Authentication in it), so each your request will perform a full-blown authentication.

Related

How to configure two security configs with two filters in spring boot correctly?

I've implmemented security in my spring boot microservices project, the requirment is to have
two types of configurations, one for user request (from angular) and one from other services.
The design is to use JWT token for user request and API key for system calls.
Here is the config file (one file) but have also try to split it to two files with no impact:
#Configuration
#EnableWebSecurity
public class SecurityConfig {
#Configuration
#Order(1)
public static class APISecurityConfig extends WebSecurityConfigurerAdapter {
#Value("${my.api.key.header}")
private String principalRequestHeader;
#Value("${my.api.key.token}")
private String principalRequestValue;
#Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.cors().disable().csrf().disable();
httpSecurity
.antMatcher("/api/users/**")
.authorizeRequests() //
.anyRequest().authenticated()
.and()
.addFilterBefore(new APIKeyAuthFilter(principalRequestHeader, principalRequestValue), UsernamePasswordAuthenticationFilter.class);
}
}
#Order(2)
#Configuration
public static class MySecurityConfiguration extends WebSecurityConfigurerAdapter {
#Autowired
UserDetailsService userDetailsService;
#Bean
public AuthTokenFilter authenticationJwtTokenFilter() {
return new AuthTokenFilter();
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
#Bean
#Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
#Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/api/users/**");
}
#Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.cors().disable().csrf().disable();
httpSecurity
.authorizeRequests()
.antMatchers("/users/UserEmailExist", "/users/User/Add", "/users/Authenticate",
"/users/User/ChangePassword")
.permitAll()
.and()
.authorizeRequests()
.antMatchers("/users/**").hasAnyRole(ROLE_ADMIN_USER, ROLE_MANAGER_USER)
.anyRequest().authenticated()
.and()
.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
}
}
}
Each config has a filter attached to it, here the api one:
public class APIKeyAuthFilter extends GenericFilterBean {
private String principalRequestHeader;
private String principalRequestValue;
public APIKeyAuthFilter(String principalRequestHeader, String principalRequestValue) {
super();
this.principalRequestHeader = principalRequestHeader;
this.principalRequestValue = principalRequestValue;
}
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
if(request instanceof HttpServletRequest && response instanceof HttpServletResponse) {
String apiKey = getApiKey((HttpServletRequest) request);
if(apiKey != null) {
if(apiKey.equals(principalRequestValue)) {
ApiKeyAuthenticationToken apiToken = new ApiKeyAuthenticationToken(apiKey, AuthorityUtils.NO_AUTHORITIES);
SecurityContextHolder.getContext().setAuthentication(apiToken);
} else {
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.setStatus(401);
httpResponse.getWriter().write("Invalid API Key");
return;
}
}
}
chain.doFilter(request, response);
}
}
Here is the filter for jwt (normal user from angular):
public class AuthTokenFilter extends OncePerRequestFilter {
#Autowired
private JwtUtils jwtUtils;
#Autowired
private MyUserDetailsService userDetailsService;
#Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
try {
String jwt = parseJwt(request);
if (jwt != null && jwtUtils.validateJwtToken(jwt)) {
String username = jwtUtils.getUserNameFromJwtToken(jwt);
MSUserDetails userDetails = userDetailsService.loadUserByUsername(username);
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
userDetails, null, userDetails.getAuthorities());
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authentication);
}
} catch (Exception e) {
logger.error("Cannot set user authentication: {}", e);
}
filterChain.doFilter(request, response);
}
}
I've created two different controllers, one with prefix /api/users and second /users.
Here is what happen in two different scenarios:
The user login from Angular, get jwt token and process request which end up in the Jwt filter,
this scenarion looking good with no issues as the user is able to process request as long
he is authenticate.
Microservice send a request with api-key to url with /api/users prefix, it ended up on the same
filter the normal user ended which is not correct and without JWT token he is actually
able to proceed to the controller and process the request without going
to the correct filter.
The only solution I have is to have only one filter and process the header
for api-key and jwt but it doesn't seem right.
I've looked online and try to figure out what I'm doing wrong but no clue as of now.
An update on this issue so I hope it will help to the community.
Firstly, I removed the following code and this mainly fix the problem:
// #Override
// public void configure(WebSecurity web) throws Exception {
// web.ignoring().antMatchers("/api/users/**");
// }
The way the solution work as a whole is that the first configuration #Order(1) you
define .antMatcher which means the configuration will work only for urls that match
the prefix.
So now, scenario 1. User from Angular go the the JWT filter only.
scenario 2. API user will lend in the API filter first! But once it's done (After succesfull authentication) it still
continue to the JWT filter but becuase it doesn't have JWT the filter not doing anything.
I would like to avoid to other filter in case of API call but the solution work,
problem solved.
I must say that security in spring boot is the most complex I came across so far from other features.
Because the AuthTokenFilter is instantiated with #Bean, which causes the filter to be added to the ApplicationFilterChain, after the APIKeyAuthFilter is processed, it can also enter the AuthTokenFilter.

Why SecurityContextHolder.getContext() == null?

I don't run my app, because auth == null. Why? I use spring boot 2.2.7.RELEASE and spring-security-oauth2-autoconfigure.
When starting SecurityContextHolder.getContext() always equal null
#Component
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
DataSource dataSource;
#Autowired
UserRepository userRepository;
#Autowired
PasswordEncoder passwordEncoder;
#Bean
public PasswordEncoder encoder() {
return new BCryptPasswordEncoder();
}
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/addPet").authenticated()
.antMatchers("/", "/**").access("permitAll")
.and().oauth2Login().loginPage("/login").defaultSuccessUrl("/", true).and().logout().logoutSuccessUrl("/")
.and().formLogin().loginPage("/login").loginProcessingUrl("/login").usernameParameter("login").passwordParameter("password")
.defaultSuccessUrl("/", true).and().logout().logoutSuccessUrl("/").deleteCookies("JSESSIONID").and().csrf().disable();
}
#Autowired
public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(dataSource)
.usersByUsernameQuery(
"select login, password, enabled from users where login=?")
.authoritiesByUsernameQuery(
"select login, role from users where login=?");
}
}
I assume that you're referring to this line,
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
In this case, you don't need this line, it's not being used anywhere. In the bigger answer, SecurityContextHolder.getContext() will never be null, according to the documentation. The call to getAuthentication(), however, will be null unless there's an authenticated principal associated to the session.

Vue Js and Spring Boot Basic Authentication

I have a basic Spring Boot API with Spring Security enabled. When accessing a secured resource from within Vue (using axios), the browser will request me for username and password with an "Authorization Required" pop-up. After that, the credentials seem to be stored by the browser and I can just keep on making requests.
How should I bypass the authentication process made by the browser and replace it with one made and controlled directly by Vue Js?
First, add security configuration (Assuming you are using Spring Security):
#Configuration
public class ApiSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private UserDetailsService userDetailsService;
#Autowired
private PasswordEncoder passwordEncoder;
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/api/**").authenticated()
.anyRequest().permitAll()
.and().httpBasic().authenticationEntryPoint(apiAwareLoginUrlAuthenticationEntryPoint())
.and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
}
#Bean
public ApiBasicAuthenticationEntryPoint apiAwareLoginUrlAuthenticationEntryPoint() {
ApiBasicAuthenticationEntryPoint entryPoint = new ApiBasicAuthenticationEntryPoint();
entryPoint.setRealmName("Api Server");
return entryPoint;
}
public static class ApiBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoint {
#Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
response.addHeader("WWW-Authenticate", "Basic realm=\"" + getRealmName() + "\"");
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
//response.setContentType("");
PrintWriter writer = response.getWriter();
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(writer, ApiDataGenerator.buildResult(
ErrorCode.AUTHORIZATION_REQUIRED, "Authorization failed"));
}
}
}
Second, Add authentication in the http request header in following format:
Authorization: Basic qwerasdfzxcv
qwerasdfzxcv is base64 hash that encode by username:password

PermitAll not working in Spring Security

I have two rules, the first one every url from oauth/** should be without security and and other url have to security. But now all urls are secure include url from oauth/**.
This is my security config rule.
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
// JWT dont need CSRF
httpSecurity.csrf().disable().exceptionHandling().and().sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests()
.antMatchers("oauth/**").permitAll().and()
.addFilterBefore(new JwtAuthenticationTokenFilter(), BasicAuthenticationFilter.class);
// disable page caching
httpSecurity.headers().cacheControl();
}
}
when I request the url http://localhost:8080/oauth/fb that is enter my JwtAuthenticationTokenFilter, and I want this url don't enter this filter.
You can override configure method with WebSecurity parameter.
#Override
public void configure(final WebSecurity web) throws Exception
{
web.ignoring().antMatchers("oauth/**");
}
This method should be used when serving static content such as css/* js/*, suggested in the documentation, however I couldn't find another way to permit URL mapping with custom filter in Spring Security.
<security:http pattern="/support/**" security="none"/>
You would probably need to write the Java equivalent of the above XML configuration. Basically, you are setting a new filter chain with no security for the above pattern.
I faced a similar problem. My security config:
// ... imports
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private final UserDetailsService userDetailsService;
private final PasswordEncoder passwordEncoder;
private final JwtFilter jwtFilter;
#Autowired
public SecurityConfig(#Qualifier("userDetailsServiceImpl") UserDetailsService userDetailsService,
PasswordEncoder passwordEncoder,
JwtProvider jwtProvider) {
this.userDetailsService = userDetailsService;
this.passwordEncoder = passwordEncoder;
this.jwtFilter = new JwtFilter(jwtProvider);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.httpBasic().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers(HttpMethod.POST, "/auth/**").permitAll()
.and()
.authorizeRequests()
.anyRequest().authenticated()
.and()
.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class);
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(daoAuthenticationProvider());
}
protected DaoAuthenticationProvider daoAuthenticationProvider() {
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setUserDetailsService(userDetailsService);
provider.setPasswordEncoder(passwordEncoder);
return provider;
}
}
And my security filter:
// ... imports
public class JwtFilter extends GenericFilterBean {
public static final String AUTHORIZATION_HEADER = "Authorization";
public static final String TOKEN_PREFIX = "Bearer ";
public static final int TOKEN_START_POSITION = 7;
private final JwtProvider jwtProvider;
#Autowired
public JwtFilter(JwtProvider jwtProvider) {
this.jwtProvider = jwtProvider;
}
#Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
String token = getTokenFromRequest((HttpServletRequest) servletRequest);
if (token != null && jwtProvider.validateToken(token)) {
Map<String, Object> properties = jwtProvider.getUserPropertiesFromToken(token);
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(
properties.get("login"),
null,
(Set<GrantedAuthority>) properties.get("authirities"));
SecurityContextHolder.getContext().setAuthentication(auth);
}
filterChain.doFilter(servletRequest, servletResponse);
}
private String getTokenFromRequest(HttpServletRequest request) {
String bearer = request.getHeader(AUTHORIZATION_HEADER);
if (bearer != null && bearer.startsWith(TOKEN_PREFIX)) {
return bearer.substring(TOKEN_START_POSITION);
}
return null;
}
}
The reason my code didn't work for me was that I skipped the line filterChain.doFilter(servletRequest, servletResponse); in my filter, i.e. I didn't pass on the request and response to the next entity in the chain.

Spring Security with JWT - Authenticated at every tenth call

I've some strange problem with my spring security configuration.
I use it with an simple JWT implementation.
I use "GlobalMethodSecurity" and annotated my method with #PreAuthorize
Here a secured sample method:
#PreAuthorize("hasAnyRole('ROLE_USER')")
#RequestMapping(value = "/user/ok", method = RequestMethod.GET)
public ResponseEntity ok( ) {
return new ResponseEntity( "{text:\"ok\"}", HttpStatus.OK );
}
if I call this without a security token I get an "UNAUTHORIZED" nine times (as expected). At the exact tenth time I will get the "ok" json from the method. (The 11th to 19th call is "UNAUTHORIZED" and at the 20th I will became the "ok" message again and so on)
Here are my SecurityConfiguration:
#Configuration
#EnableGlobalMethodSecurity( prePostEnabled = true )
#EnableWebSecurity
#EnableTransactionManagement
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private UserDetailsService userDetailsService;
#Autowired
private AuthenticationEntryPoint authenticationEntryPoint;
#Autowired
public void configureAuthentication( AuthenticationManagerBuilder authenticationManagerBuilder ) throws Exception {
authenticationManagerBuilder
.userDetailsService( userDetailsService )
.passwordEncoder( new BCryptPasswordEncoder() );
}
#Bean
#Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
#Bean(name = "authenticationTokenFilter")
public AuthenticationTokenFilter authenticationTokenFilterBean() throws Exception {
AuthenticationTokenFilter authenticationTokenFilter = new AuthenticationTokenFilter();
authenticationTokenFilter.setAuthenticationManager( super.authenticationManagerBean() );
return authenticationTokenFilter;
}
#Override
protected void configure( HttpSecurity httpSecurity ) throws Exception {
// Custom JWT based authentication
httpSecurity
.addFilterBefore( authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class )
.exceptionHandling()
.authenticationEntryPoint( authenticationEntryPoint )
.and()
.sessionManagement()
.sessionCreationPolicy( SessionCreationPolicy.STATELESS )
.and()
.authorizeRequests()
.anyRequest()
.authenticated();
}
and my Filter Class:
public class AuthenticationTokenFilter extends UsernamePasswordAuthenticationFilter {
#Autowired
private TokenUtils tokenUtils;
#Autowired
private UserDetailsService userDetailsService;
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
tokenUtils = WebApplicationContextUtils
.getRequiredWebApplicationContext(this.getServletContext())
.getBean(TokenUtils.class);
userDetailsService = WebApplicationContextUtils
.getRequiredWebApplicationContext(this.getServletContext())
.getBean(UserDetailsService.class);
HttpServletResponse resp = (HttpServletResponse) response;
resp.setHeader("Access-Control-Allow-Origin", "*");
resp.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE, PATCH");
resp.setHeader("Access-Control-Max-Age", "3600");
resp.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Authorization, Accept, " + AppConstant.tokenHeader);
HttpServletRequest httpRequest = (HttpServletRequest) request;
String authToken = httpRequest.getHeader(AppConstant.tokenHeader);
String username = this.tokenUtils.getUsernameFromToken(authToken);
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
if (this.tokenUtils.validateToken(authToken, userDetails)) {
UsernamePasswordAuthenticationToken authentication =
new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpRequest));
SecurityContextHolder.getContext().setAuthentication(authentication);
}
}
chain.doFilter(request, response);
}
}
Edit
I found out that this only happen if a user was logged in once.
So in the example ok() method I had the previously logged in user in the security context although I haven't sent any token in the header.
But as I said - not in every request - There must be a kind of Thread or session thing I miss.
For a advice I would be very grateful
Thanks!
Take a look at this example: https://github.com/bfwg/springboot-jwt-starter
Live Demo: http://fanjin.computer:8080
SecurityConfiguration:
#Configuration
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Bean
public TokenAuthenticationFilter jwtAuthenticationTokenFilter() throws Exception {
return new TokenAuthenticationFilter();
}
#Bean
public JwtLogoutHandler jwtLogoutHandler() {
return new JwtLogoutHandler();
}
#Autowired
CustomUserDetailsService jwtUserDetailsService;
#Autowired
RestAuthenticationEntryPoint restAuthenticationEntryPoint;
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(jwtUserDetailsService);
}
#Autowired
private AuthenticationSuccessHandler authenticationSuccessHandler;
#Autowired
private AuthenticationFailureHandler authenticationFailureHandler;
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf()
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()).and()
.sessionManagement().sessionCreationPolicy( SessionCreationPolicy.STATELESS ).and()
.exceptionHandling().authenticationEntryPoint( restAuthenticationEntryPoint ).and()
.addFilterBefore(jwtAuthenticationTokenFilter(), BasicAuthenticationFilter.class)
.authorizeRequests()
.antMatchers("/", "/index.html", "/login.html", "/home.html").permitAll()
.anyRequest()
.authenticated().and()
.formLogin()
.successHandler(authenticationSuccessHandler)
.failureHandler(authenticationFailureHandler).and()
.logout()
.addLogoutHandler(jwtLogoutHandler())
.logoutSuccessHandler((new HttpStatusReturningLogoutSuccessHandler(HttpStatus.OK))) ;
}
}
Filter Class:
#Override
public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
String authToken = getToken( request );
// get username from token
String username = tokenHelper.getUsernameFromToken( authToken );
if ( username != null ) {
// get user
UserDetails userDetails = userDetailsService.loadUserByUsername( username );
// create authentication
TokenBasedAuthentication authentication = new TokenBasedAuthentication( userDetails );
authentication.setToken( authToken );
authentication.setAuthenticated( true );
SecurityContextHolder.getContext().setAuthentication(authentication);
}
chain.doFilter(request, response);
}
Hope this helps.

Resources