Fixed authentication time format in authentication controller.

Change-Id: I9fab076ba1dcd02ce6f8cb69c9e435b6234da371
diff --git a/core/src/main/java/de/ids_mannheim/korap/utils/TimeUtils.java b/core/src/main/java/de/ids_mannheim/korap/utils/TimeUtils.java
index cd0a1ca..6ef4b56 100644
--- a/core/src/main/java/de/ids_mannheim/korap/utils/TimeUtils.java
+++ b/core/src/main/java/de/ids_mannheim/korap/utils/TimeUtils.java
@@ -9,6 +9,8 @@
 import org.joda.time.format.DateTimeFormatter;
 import org.joda.time.format.ISODateTimeFormat;
 
+import de.ids_mannheim.korap.config.Attributes;
+
 import java.math.BigDecimal;
 import java.math.RoundingMode;
 import java.text.DecimalFormat;
@@ -29,7 +31,7 @@
     private static DecimalFormat df = new DecimalFormat("#.#############");
     private static DateTimeFormatter dtf = DateTimeFormat
             .forPattern("dd/MM/yyyy");
-    private static final DateTimeZone dtz = DateTimeZone.forID("Europe/Berlin");
+    private static final DateTimeZone dtz = DateTimeZone.forID(Attributes.DEFAULT_TIME_ZONE);
     private static Logger jlog = LogManager.getLogger(TimeUtils.class);
 
 
diff --git a/full/Changes b/full/Changes
index 4b0dd20..f6f8688 100644
--- a/full/Changes
+++ b/full/Changes
@@ -1,5 +1,5 @@
 version 0.60.5
-09/07/2018
+11/07/2018
 	- Added service layer to the search controller (margaretha)
 	- Added OAuth2 scope checking in search and VC controllers (margaretha)
 	- Added handling OAuth2 bearer token for VC access and User group controllers (margaretha)
@@ -8,6 +8,7 @@
 	- Added store access token in openID token service (margaretha)
 	- Fixed empty scope in openID authorization and token service (margaretha)
 	- Implemented storing authorization code in cache (margaretha)
+	- Fixed authentication time in authentication controller (margaretha)
 	
 version 0.60.4
 05/07/2018
diff --git a/full/src/main/java/de/ids_mannheim/korap/authentication/APIAuthentication.java b/full/src/main/java/de/ids_mannheim/korap/authentication/APIAuthentication.java
index e984c11..77504a5 100644
--- a/full/src/main/java/de/ids_mannheim/korap/authentication/APIAuthentication.java
+++ b/full/src/main/java/de/ids_mannheim/korap/authentication/APIAuthentication.java
@@ -1,11 +1,18 @@
 package de.ids_mannheim.korap.authentication;
 
 import java.text.ParseException;
+import java.time.ZoneId;
+import java.time.ZonedDateTime;
+import java.util.Date;
 import java.util.Map;
 
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+
 import com.nimbusds.jose.JOSEException;
 import com.nimbusds.jwt.SignedJWT;
 
+import de.ids_mannheim.korap.config.Attributes;
 import de.ids_mannheim.korap.config.FullConfiguration;
 import de.ids_mannheim.korap.config.JWTSigner;
 import de.ids_mannheim.korap.constant.TokenType;
@@ -18,24 +25,31 @@
 import net.sf.ehcache.CacheManager;
 import net.sf.ehcache.Element;
 
-/** EM: there is no authentication here, just implementation for creating token context etc.
+/**
+ * EM: there is no authentication here, just implementation for
+ * creating token context etc.
  * 
  * Created by hanl on 5/23/14.
  */
 public class APIAuthentication implements AuthenticationIface {
 
+    private static Logger jlog = LogManager.getLogger(APIAuthentication.class);
+
     private JWTSigner signedToken;
     private Cache invalided =
             CacheManager.getInstance().getCache("id_tokens_inv");
-    //private Cache id_tokens = CacheManager.getInstance().getCache("id_tokens");
+    // private Cache id_tokens =
+    // CacheManager.getInstance().getCache("id_tokens");
 
 
     public APIAuthentication (FullConfiguration config) throws JOSEException {
         this.signedToken = new JWTSigner(config.getSharedSecret(),
                 config.getIssuer(), config.getTokenTTL());
     }
-    
-    /** EM: for testing
+
+    /**
+     * EM: for testing
+     * 
      * @param signedToken
      */
     public APIAuthentication (JWTSigner signedToken) {
@@ -46,7 +60,7 @@
     public TokenContext getTokenContext (String authToken)
             throws KustvaktException {
         TokenContext context;
-        //Element ein = invalided.get(authToken);
+        // Element ein = invalided.get(authToken);
         try {
             context = signedToken.getTokenContext(authToken);
             context.setTokenType(getTokenType());
@@ -54,8 +68,8 @@
         catch (JOSEException | ParseException ex) {
             throw new KustvaktException(StatusCodes.ILLEGAL_ARGUMENT);
         }
-        //context = (TokenContext) e.getObjectValue();
-        //throw new KustvaktException(StatusCodes.EXPIRED);
+        // context = (TokenContext) e.getObjectValue();
+        // throw new KustvaktException(StatusCodes.EXPIRED);
         return context;
     }
 
@@ -67,20 +81,28 @@
         c.setUsername(user.getUsername());
         SignedJWT jwt = signedToken.createJWT(user, attr);
         try {
-            c.setExpirationTime(jwt.getJWTClaimsSet().getExpirationTime().getTime());
+            c.setExpirationTime(
+                    jwt.getJWTClaimsSet().getExpirationTime().getTime());
+            jlog.debug(jwt.getJWTClaimsSet().getClaim(Attributes.AUTHENTICATION_TIME));
+            Date authTime = jwt.getJWTClaimsSet()
+                    .getDateClaim(Attributes.AUTHENTICATION_TIME);
+            ZonedDateTime time = ZonedDateTime.ofInstant(authTime.toInstant(),
+                    ZoneId.of(Attributes.DEFAULT_TIME_ZONE));
+            c.setAuthenticationTime(time);
         }
         catch (ParseException e) {
             throw new KustvaktException(StatusCodes.ILLEGAL_ARGUMENT);
         }
         c.setTokenType(getTokenType());
         c.setToken(jwt.serialize());
-        //id_tokens.put(new Element(c.getToken(), c));
+        // id_tokens.put(new Element(c.getToken(), c));
         return c;
     }
 
 
-    // todo: cache and set expiration to token expiration. if token in that cache, it is not to be used anymore!
-    //    @CacheEvict(value = "id_tokens", key = "#token")
+    // todo: cache and set expiration to token expiration. if token in
+    // that cache, it is not to be used anymore!
+    // @CacheEvict(value = "id_tokens", key = "#token")
     @Override
     public void removeUserSession (String token) throws KustvaktException {
         // invalidate token!
@@ -93,7 +115,7 @@
             throws KustvaktException {
         return null;
     }
-    
+
 
     @Override
     public TokenType getTokenType () {
diff --git a/full/src/main/java/de/ids_mannheim/korap/config/JWTSigner.java b/full/src/main/java/de/ids_mannheim/korap/config/JWTSigner.java
index 49f8183..dee393f 100644
--- a/full/src/main/java/de/ids_mannheim/korap/config/JWTSigner.java
+++ b/full/src/main/java/de/ids_mannheim/korap/config/JWTSigner.java
@@ -3,10 +3,14 @@
 import java.net.MalformedURLException;
 import java.net.URL;
 import java.text.ParseException;
+import java.time.Instant;
+import java.time.ZoneId;
 import java.time.ZonedDateTime;
 import java.util.List;
 import java.util.Map;
 
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
 import org.joda.time.DateTime;
 
 import com.nimbusds.jose.JOSEException;
@@ -34,6 +38,8 @@
  */
 public class JWTSigner {
 
+    private static Logger jlog = LogManager.getLogger(JWTSigner.class);
+    
     private URL issuer;
     private JWSSigner signer;
     private JWSVerifier verifier;
@@ -84,8 +90,11 @@
         csBuilder.expirationTime(TimeUtils.getNow().plusSeconds(ttl).toDate());
         csBuilder.claim(Attributes.AUTHENTICATION_TIME,
                 attr.get(Attributes.AUTHENTICATION_TIME));
-        SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.HS256),
-                csBuilder.build());
+        
+        JWTClaimsSet jwtClaimsSet = csBuilder.build();
+        jlog.debug(jwtClaimsSet.getClaim(Attributes.AUTHENTICATION_TIME));
+        SignedJWT signedJWT =
+                new SignedJWT(new JWSHeader(JWSAlgorithm.HS256), jwtClaimsSet);
         try {
             signedJWT.sign(signer);
         }
@@ -191,8 +200,12 @@
                     signedJWT.getJWTClaimsSet().getAudience().get(0));
         c.setExpirationTime(
                 signedJWT.getJWTClaimsSet().getExpirationTime().getTime());
-        c.setAuthenticationTime((ZonedDateTime) signedJWT.getJWTClaimsSet()
+
+        Instant instant = Instant.ofEpochMilli((long) signedJWT.getJWTClaimsSet()
                 .getClaim(Attributes.AUTHENTICATION_TIME));
+        ZonedDateTime zonedAuthTime = ZonedDateTime.ofInstant(
+                instant, ZoneId.of(Attributes.DEFAULT_TIME_ZONE));
+        c.setAuthenticationTime(zonedAuthTime);
         c.setToken(idtoken);
         c.addParams(signedJWT.getJWTClaimsSet().getClaims());
         return c;
diff --git a/full/src/main/java/de/ids_mannheim/korap/oauth2/oltu/service/OltuAuthorizationService.java b/full/src/main/java/de/ids_mannheim/korap/oauth2/oltu/service/OltuAuthorizationService.java
index f1bb28c..3a7a294 100644
--- a/full/src/main/java/de/ids_mannheim/korap/oauth2/oltu/service/OltuAuthorizationService.java
+++ b/full/src/main/java/de/ids_mannheim/korap/oauth2/oltu/service/OltuAuthorizationService.java
@@ -53,9 +53,6 @@
             ZonedDateTime authenticationTime)
             throws OAuthSystemException, KustvaktException {
 
-        String code = oauthIssuer.authorizationCode();
-        checkResponseType(authzRequest.getResponseType());
-
         String clientId = authzRequest.getClientId();
         OAuth2Client client = clientService.authenticateClientId(clientId);
 
@@ -71,8 +68,10 @@
                     "Invalid redirect URI", OAuth2Error.INVALID_REQUEST);
         }
 
-        String scope;
+        String scope, code;
         try {
+            code = oauthIssuer.authorizationCode();
+            checkResponseType(authzRequest.getResponseType());
             scope = createAuthorization(username, authzRequest.getClientId(),
                     redirectUri, authzRequest.getScopes(), code,
                     authenticationTime, null);
diff --git a/full/src/main/java/de/ids_mannheim/korap/web/controller/AuthenticationController.java b/full/src/main/java/de/ids_mannheim/korap/web/controller/AuthenticationController.java
index 0371c9e..0545cf0 100644
--- a/full/src/main/java/de/ids_mannheim/korap/web/controller/AuthenticationController.java
+++ b/full/src/main/java/de/ids_mannheim/korap/web/controller/AuthenticationController.java
@@ -1,7 +1,6 @@
 package de.ids_mannheim.korap.web.controller;
 
-import java.time.ZoneId;
-import java.time.ZonedDateTime;
+import java.util.Date;
 import java.util.HashMap;
 import java.util.Iterator; // 07.02.17/FB
 import java.util.List;
@@ -44,6 +43,7 @@
 import de.ids_mannheim.korap.user.User;
 import de.ids_mannheim.korap.utils.JsonUtils;
 import de.ids_mannheim.korap.utils.ServiceInfo;
+import de.ids_mannheim.korap.utils.TimeUtils;
 import de.ids_mannheim.korap.web.KustvaktResponseHandler;
 import de.ids_mannheim.korap.web.filter.AuthenticationFilter;
 import de.ids_mannheim.korap.web.filter.BlockingFilter;
@@ -259,8 +259,7 @@
             //            attr.putAll(data.fields());
             
             // EM: add authentication time
-            ZonedDateTime authenticationTime =
-                    ZonedDateTime.now(ZoneId.of(Attributes.DEFAULT_TIME_ZONE));
+            Date authenticationTime = TimeUtils.getNow().toDate();
             attr.put(Attributes.AUTHENTICATION_TIME, authenticationTime);
             // -- EM
             
diff --git a/full/src/main/resources/ehcache.xml b/full/src/main/resources/ehcache.xml
index be4e71e..d2be647 100644
--- a/full/src/main/resources/ehcache.xml
+++ b/full/src/main/resources/ehcache.xml
@@ -11,6 +11,13 @@
            maxEntriesLocalHeap="50"
            overflowToDisk='true'/>
 
+	<cache name='id_tokens_inv'
+           eternal='true'
+           maxElementsOnDisk="10000000"
+           memoryStoreEvictionPolicy="LRU"
+           maxEntriesLocalHeap="50"
+           overflowToDisk='true'/>
+           
     <cache name='auth_codes'
            timeToIdleSeconds="600"
            eternal='false'
diff --git a/full/src/test/resources/kustvakt-test.conf b/full/src/test/resources/kustvakt-test.conf
index 99c295c..cc53e79 100644
--- a/full/src/test/resources/kustvakt-test.conf
+++ b/full/src/test/resources/kustvakt-test.conf
@@ -79,6 +79,7 @@
 security.jwt.issuer=https://korap.ids-mannheim.de
 
 ## JWK
+## must be set for openid
 rsa.private = kustvakt_rsa.key
 rsa.public = kustvakt_rsa_public.key
 rsa.key.id = 74caa3a9-217c-49e6-94e9-2368fdd02c35