OAuthState.java

  1. package no.nav.data.common.security.dto;

  2. import lombok.AccessLevel;
  3. import lombok.Data;
  4. import lombok.NoArgsConstructor;
  5. import no.nav.data.common.security.Encryptor;
  6. import no.nav.data.common.utils.JsonUtils;
  7. import org.springframework.util.Assert;
  8. import org.springframework.web.util.HtmlUtils;
  9. import org.springframework.web.util.UriComponentsBuilder;

  10. import static org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames.ERROR;
  11. import static org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames.ERROR_DESCRIPTION;
  12. import static org.springframework.security.web.util.UrlUtils.isValidRedirectUrl;

  13. /**
  14.  * Encrypted json to ensure origin of state and code
  15.  */
  16. @Data
  17. @NoArgsConstructor(access = AccessLevel.PRIVATE)
  18. public class OAuthState {

  19.     private String sessionId;
  20.     private String redirectUri;
  21.     private String errorUri;

  22.     public OAuthState(String redirectUri) {
  23.         this(null, redirectUri, null);
  24.     }

  25.     public OAuthState(String sessionId, String redirectUri, String errorUri) {
  26.         this.sessionId = sessionId;
  27.         this.redirectUri = redirectUri;
  28.         this.errorUri = errorUri != null ? errorUri : redirectUri;
  29.         validate();
  30.     }

  31.     public String errorRedirect(String error, String errorDesc) {
  32.         return UriComponentsBuilder.fromUriString(getErrorUri())
  33.                 .queryParam(ERROR, HtmlUtils.htmlEscape(error))
  34.                 .queryParam(ERROR_DESCRIPTION, HtmlUtils.htmlEscape(errorDesc.replaceAll("[\\r\\n]", " ")))
  35.                 .build().toUriString();
  36.     }

  37.     public static OAuthState fromJson(String encryptedJson, Encryptor encryptor) {
  38.         var json = encryptor.decrypt(encryptedJson);
  39.         OAuthState state = JsonUtils.toObject(json, OAuthState.class);
  40.         state.validate();
  41.         Assert.isTrue(state.getSessionId() != null, "SessionId is null");
  42.         return state;
  43.     }

  44.     public String toJson(Encryptor encryptor) {
  45.         String json = JsonUtils.toJson(this);
  46.         return encryptor.encrypt(json).saltedCipher();
  47.     }

  48.     private void validate() {
  49.         Assert.isTrue(isValidRedirectUrl(redirectUri), "Invalid redirectUri");
  50.         Assert.isTrue(isValidRedirectUrl(errorUri), "Invalid errorUri");
  51.     }
  52. }