Java tutorial
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.jevontech.wabl.security; /** * * @author jeroen */ import com.jevontech.wabl.config.AuthenticationConfiguration; import java.io.IOException; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; import org.springframework.stereotype.Component; public class AuthenticationTokenFilter extends UsernamePasswordAuthenticationFilter { private static final Logger log = LoggerFactory.getLogger(AuthenticationTokenFilter.class); @Value("${wabl.token.header}") private String tokenHeader; @Autowired private TokenUtils tokenUtils; @Autowired private UserDetailsService userDetailsService; @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { //log.debug("doFilter"); HttpServletRequest httpRequest = (HttpServletRequest) request; String authToken = httpRequest.getHeader(this.tokenHeader); String username = this.tokenUtils.getUsernameFromToken(authToken); log.debug("doFilter: this.tokenHeader=" + this.tokenHeader); log.debug("doFilter: authToken=" + authToken + " , username=" + username); if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) { UserDetails userDetails = this.userDetailsService.loadUserByUsername(username); log.debug("doFilter: userDetails=" + userDetails.toString()); 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); } }