63 lines
2.4 KiB
Java
63 lines
2.4 KiB
Java
package pl.edu.amu.wmi.bookapi.security;
|
|
|
|
import com.auth0.jwt.*;
|
|
import com.fasterxml.jackson.databind.*;
|
|
import org.springframework.security.authentication.*;
|
|
import org.springframework.security.core.*;
|
|
import org.springframework.security.core.userdetails.*;
|
|
import org.springframework.security.web.authentication.*;
|
|
import pl.edu.amu.wmi.bookapi.models.*;
|
|
|
|
import javax.servlet.*;
|
|
import javax.servlet.http.*;
|
|
import java.io.*;
|
|
import java.util.*;
|
|
|
|
import static com.auth0.jwt.algorithms.Algorithm.*;
|
|
|
|
public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
|
|
private AuthenticationManager authenticationManager;
|
|
|
|
public JWTAuthenticationFilter(AuthenticationManager authenticationManager) {
|
|
this.authenticationManager = authenticationManager;
|
|
}
|
|
|
|
public static final String SECRET = "SecretKeyToGenJWTs";
|
|
public static final long EXPIRATION_TIME = 864_000_000; // 10 days
|
|
public static final String TOKEN_PREFIX = "Bearer ";
|
|
public static final String HEADER_STRING = "Authorization";
|
|
public static final String SIGN_UP_URL = "/users/sign-up";
|
|
|
|
@Override
|
|
public Authentication attemptAuthentication(HttpServletRequest req,
|
|
HttpServletResponse res) throws AuthenticationException {
|
|
try {
|
|
UserDocument creds = new ObjectMapper()
|
|
.readValue(req.getInputStream(), UserDocument.class);
|
|
|
|
return authenticationManager.authenticate(
|
|
new UsernamePasswordAuthenticationToken(
|
|
creds.getUsername(),
|
|
creds.getPassword(),
|
|
new ArrayList<>())
|
|
);
|
|
} catch (IOException e) {
|
|
throw new RuntimeException(e);
|
|
}
|
|
}
|
|
|
|
@Override
|
|
protected void successfulAuthentication(HttpServletRequest req,
|
|
HttpServletResponse res,
|
|
FilterChain chain,
|
|
Authentication auth) throws IOException, ServletException {
|
|
|
|
String token = JWT.create()
|
|
.withSubject(((User) auth.getPrincipal()).getUsername())
|
|
.withExpiresAt(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
|
|
.sign(HMAC512(SECRET.getBytes()));
|
|
|
|
res.addHeader(HEADER_STRING, TOKEN_PREFIX + token);
|
|
}
|
|
}
|