Skip to content

Instantly share code, notes, and snippets.

@MrMjauh
Created June 30, 2019 21:04
Show Gist options
  • Save MrMjauh/c3bd7d9deb134243e8f8497b5b380d83 to your computer and use it in GitHub Desktop.
Save MrMjauh/c3bd7d9deb134243e8f8497b5b380d83 to your computer and use it in GitHub Desktop.
TokenAuthenticationFilter.java
public class TokenAuthenticationFilter extends OncePerRequestFilter {
private ITokenService tokenService;
public TokenAuthenticationFilter(ITokenService tokenService) {
Assert.notNull(tokenService, "Can not be null");
this.tokenService = tokenService;
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
String data = request.getHeader(SecurityResource.X_AUTH_KEY);
if (!StringUtils.hasText(data)) {
filterChain.doFilter(request,response);
return;
}
User user = this.tokenService.getUserFromToken(data);
if (user == null) {
filterChain.doFilter(request,response);
return;
}
AuthenticatedUser authenticatedUser = AuthenticatedUser.from(user);
String[] authorities;
if (user.getRoles() == null) {
authorities = new String[]{};
} else {
authorities = user.getRoles().toArray(new String[]{});
}
Authentication authentication = new PreAuthenticatedAuthenticationToken(
authenticatedUser,
data,
AuthorityUtils.createAuthorityList(authorities)
);
SecurityContext context = SecurityContextHolder.createEmptyContext();
context.setAuthentication(authentication);
SecurityContextHolder.setContext(context);
filterChain.doFilter(request, response);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment