verify signature and claims

This commit is contained in:
DOHA 2018-02-20 18:34:11 +02:00
parent c18dd299c6
commit 5f9e03c6a1
3 changed files with 45 additions and 18 deletions

View File

@ -46,6 +46,11 @@
<version>1.0.9.RELEASE</version> <version>1.0.9.RELEASE</version>
</dependency> </dependency>
<dependency>
<groupId>com.auth0</groupId>
<artifactId>jwks-rsa</artifactId>
<version>0.3.0</version>
</dependency>
</dependencies> </dependencies>
<repositories> <repositories>

View File

@ -1,14 +1,16 @@
package org.baeldung.security; package org.baeldung.security;
import java.io.IOException; import java.io.IOException;
import java.math.BigInteger; import java.net.URL;
import java.security.interfaces.RSAPublicKey;
import java.util.Date;
import java.util.Map; import java.util.Map;
import javax.servlet.ServletException; import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import org.apache.commons.codec.binary.Base64; import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
@ -20,13 +22,24 @@ import org.springframework.security.jwt.crypto.sign.RsaVerifier;
import org.springframework.security.oauth2.client.OAuth2RestOperations; import org.springframework.security.oauth2.client.OAuth2RestOperations;
import org.springframework.security.oauth2.client.OAuth2RestTemplate; import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.security.oauth2.common.OAuth2AccessToken; import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception; import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter; import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import com.auth0.jwk.Jwk;
import com.auth0.jwk.JwkProvider;
import com.auth0.jwk.UrlJwkProvider;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
public class OpenIdConnectFilter extends AbstractAuthenticationProcessingFilter { public class OpenIdConnectFilter extends AbstractAuthenticationProcessingFilter {
@Value("${google.clientId}")
private String clientId;
@Value("${google.issuer}")
private String issuer;
@Value("${google.jwkUrl}")
private String jwkUrl;
public OAuth2RestOperations restTemplate; public OAuth2RestOperations restTemplate;
public OpenIdConnectFilter(String defaultFilterProcessesUrl) { public OpenIdConnectFilter(String defaultFilterProcessesUrl) {
@ -45,33 +58,40 @@ public class OpenIdConnectFilter extends AbstractAuthenticationProcessingFilter
} }
try { try {
final String idToken = accessToken.getAdditionalInformation().get("id_token").toString(); final String idToken = accessToken.getAdditionalInformation().get("id_token").toString();
final Jwt tokenDecoded = JwtHelper.decodeAndVerify(idToken, verifier()); String kid = JwtHelper.headers(idToken)
System.out.println("===== : " + tokenDecoded.getClaims()); .get("kid");
final Jwt tokenDecoded = JwtHelper.decodeAndVerify(idToken, verifier(kid));
final Map<String, String> authInfo = new ObjectMapper().readValue(tokenDecoded.getClaims(), Map.class); final Map<String, String> authInfo = new ObjectMapper().readValue(tokenDecoded.getClaims(), Map.class);
verifyClaims(authInfo);
final OpenIdConnectUserDetails user = new OpenIdConnectUserDetails(authInfo, accessToken); final OpenIdConnectUserDetails user = new OpenIdConnectUserDetails(authInfo, accessToken);
return new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities()); return new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
} catch (final InvalidTokenException e) { } catch (final Exception e) {
throw new BadCredentialsException("Could not obtain user details from token", e); throw new BadCredentialsException("Could not obtain user details from token", e);
} }
} }
public void verifyClaims(Map claims) {
int exp = (int) claims.get("exp");
Date expireDate = new Date(exp * 1000L);
Date now = new Date();
if (expireDate.before(now) || !claims.get("iss").equals(issuer) || !claims.get("aud").equals(clientId)) {
throw new RuntimeException("Invalid claims");
}
}
private RsaVerifier verifier(String kid) throws Exception {
JwkProvider provider = new UrlJwkProvider(new URL(jwkUrl));
Jwk jwk = provider.get(kid);
return new RsaVerifier((RSAPublicKey) jwk.getPublicKey());
}
public void setRestTemplate(OAuth2RestTemplate restTemplate2) { public void setRestTemplate(OAuth2RestTemplate restTemplate2) {
restTemplate = restTemplate2; restTemplate = restTemplate2;
} }
// details can be found at https://www.googleapis.com/oauth2/v2/certs
private RsaVerifier verifier() {
byte[] nbytes = Base64.decodeBase64("vmyoDT6ND_YJa1ItdvULuTJr2pw4MvN3Z5kmSiJBm9glVoakcDEBGF4b5crKiPW7WDh2PZ0_yXY9ikDaTux7hxtgUtmm96KjmdBn_FYwv3SlsBRnzZw1oAG-2OdjlFWvlx4rXOhAzZ04ngPb3ELywwtKoO90hCy2DrNOMMSCuSu8zrFLw5oREawPcUFEQReipy_KRFf02VxFbK4Tj2FHVdBPPLW3W1KJD4S-NNwPnoeDrI6zWMv7WWAeSLAT0hX36r5FM9dM2uXTxPRCZzs-nqrUiHxn4duFIGgzuxCVbyigDrnfsmHx-B5tG1m7ts74xwf2P_PJwNNJ8qRihMsS2Q==");
byte[] ebytes = Base64.decodeBase64("AQAB");
BigInteger n = new BigInteger(1, nbytes);
BigInteger e = new BigInteger(1, ebytes);
return new RsaVerifier(n, e);
}
private static class NoopAuthenticationManager implements AuthenticationManager { private static class NoopAuthenticationManager implements AuthenticationManager {
@Override @Override

View File

@ -3,4 +3,6 @@ google.clientId=TODO
google.clientSecret=TODO google.clientSecret=TODO
google.accessTokenUri=https://www.googleapis.com/oauth2/v3/token google.accessTokenUri=https://www.googleapis.com/oauth2/v3/token
google.userAuthorizationUri=https://accounts.google.com/o/oauth2/auth google.userAuthorizationUri=https://accounts.google.com/o/oauth2/auth
google.redirectUri=http://localhost:8081/google-login google.redirectUri=http://localhost:8081/google-login
google.issuer=accounts.google.com
google.jwkUrl=https://www.googleapis.com/oauth2/v2/certs