75 lines
3.0 KiB
Java
75 lines
3.0 KiB
Java
package pl.edu.amu.wmi.bookapi.security;
|
|
|
|
import com.auth0.jwt.JWT;
|
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
|
import org.springframework.security.authentication.AuthenticationManager;
|
|
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
|
import org.springframework.security.core.Authentication;
|
|
import org.springframework.security.core.AuthenticationException;
|
|
import org.springframework.security.core.userdetails.User;
|
|
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
|
import org.springframework.web.cors.CorsUtils;
|
|
import pl.edu.amu.wmi.bookapi.models.UserDocument;
|
|
|
|
import javax.servlet.FilterChain;
|
|
import javax.servlet.ServletException;
|
|
import javax.servlet.http.HttpServletRequest;
|
|
import javax.servlet.http.HttpServletResponse;
|
|
import java.io.IOException;
|
|
import java.util.ArrayList;
|
|
import java.util.Date;
|
|
|
|
import static com.auth0.jwt.algorithms.Algorithm.HMAC512;
|
|
|
|
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";
|
|
public static final String LOG_IN_URL = "/users/login";
|
|
|
|
@Override
|
|
public Authentication attemptAuthentication(HttpServletRequest req,
|
|
HttpServletResponse res) throws AuthenticationException {
|
|
try {
|
|
if (CorsUtils.isPreFlightRequest(req)) {
|
|
res.setStatus(HttpServletResponse.SC_OK);
|
|
return null;
|
|
}
|
|
|
|
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);
|
|
}
|
|
}
|