56 lines
1.8 KiB
Java
56 lines
1.8 KiB
Java
package pl.edu.amu.wmi.bookapi.security;
|
|
|
|
import com.auth0.jwt.*;
|
|
import com.auth0.jwt.algorithms.*;
|
|
import org.springframework.security.authentication.*;
|
|
import org.springframework.security.core.context.*;
|
|
import org.springframework.security.web.authentication.www.*;
|
|
|
|
import javax.servlet.*;
|
|
import javax.servlet.http.*;
|
|
import java.io.*;
|
|
import java.util.*;
|
|
|
|
import static pl.edu.amu.wmi.bookapi.security.JWTAuthenticationFilter.*;
|
|
|
|
public class JWTAuthorizationFilter extends BasicAuthenticationFilter {
|
|
|
|
public JWTAuthorizationFilter(AuthenticationManager authManager) {
|
|
super(authManager);
|
|
}
|
|
|
|
@Override
|
|
protected void doFilterInternal(HttpServletRequest req,
|
|
HttpServletResponse res,
|
|
FilterChain chain) throws IOException, ServletException {
|
|
String header = req.getHeader(HEADER_STRING);
|
|
|
|
if (header == null || !header.startsWith(TOKEN_PREFIX)) {
|
|
chain.doFilter(req, res);
|
|
return;
|
|
}
|
|
|
|
UsernamePasswordAuthenticationToken authentication = getAuthentication(req);
|
|
|
|
SecurityContextHolder.getContext().setAuthentication(authentication);
|
|
chain.doFilter(req, res);
|
|
}
|
|
|
|
private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
|
|
String token = request.getHeader(HEADER_STRING);
|
|
if (token != null) {
|
|
String user = JWT.require(Algorithm.HMAC512(SECRET.getBytes()))
|
|
.build()
|
|
.verify(token.replace(TOKEN_PREFIX, ""))
|
|
.getSubject();
|
|
|
|
System.out.println();
|
|
if (user != null) {
|
|
return new UsernamePasswordAuthenticationToken(user, null, new ArrayList<>());
|
|
}
|
|
return null;
|
|
}
|
|
return null;
|
|
}
|
|
}
|