Skip to content

Commit

Permalink
Coding done, oauth working
Browse files Browse the repository at this point in the history
  • Loading branch information
amontenegro committed Feb 27, 2025
1 parent c730b94 commit 92d8a20
Show file tree
Hide file tree
Showing 17 changed files with 305 additions and 111 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
import org.orcid.persistence.jpa.entities.EventEntity;
import org.orcid.persistence.jpa.entities.EventType;
import org.orcid.pojo.ajaxForm.PojoUtil;
import org.orcid.pojo.ajaxForm.RequestInfoForm;

/**
*
Expand All @@ -45,11 +44,7 @@ public void createEvent(EventType eventType, HttpServletRequest request) {

if (request != null) {
Boolean isOauth2ScreensRequest = (Boolean) request.getSession().getAttribute(OrcidOauth2Constants.OAUTH_2SCREENS);
RequestInfoForm requestInfoForm = (RequestInfoForm) request.getSession().getAttribute("requestInfoForm");
if (requestInfoForm != null) {
clientId = requestInfoForm.getClientId();
label = "OAuth " + requestInfoForm.getMemberName() + " " + requestInfoForm.getClientName();
} else if (isOauth2ScreensRequest != null && isOauth2ScreensRequest) {
if (isOauth2ScreensRequest != null && isOauth2ScreensRequest) {
String queryString = (String) request.getSession().getAttribute(OrcidOauth2Constants.OAUTH_QUERY_STRING);
clientId = getParameterValue(queryString, "client_id");
ClientDetailsEntity clientDetailsEntity = clientDetailsEntityCacheManager.retrieve(clientId);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -208,9 +208,7 @@ public Set<String> getResourceIds() {
Set<String> rids = new HashSet<String>();
if (clientResourceIds != null && !clientResourceIds.isEmpty()) {
for (ClientResourceIdEntity resourceIdEntity : clientResourceIds) {
if(resourceIdEntity.getId() != null) {
rids.add(resourceIdEntity.getId().getResourceId());
}
rids.add(resourceIdEntity.getResourceId());
}
}
return rids;
Expand Down Expand Up @@ -277,7 +275,7 @@ public String getClientSecretForJpa() {
if (clientSecrets == null || clientSecrets.isEmpty()) {
return null;
}
return clientSecrets.first().getId().getClientSecret();
return clientSecrets.first().getClientSecret();
}

public void setClientSecretForJpa(String clientSecret) {
Expand Down Expand Up @@ -327,7 +325,7 @@ public Set<String> getScope() {
Set<String> sps = new HashSet<String>();
if (clientScopes != null && !clientScopes.isEmpty()) {
for (ClientScopeEntity cse : clientScopes) {
sps.add(cse.getId().getScopeType());
sps.add(cse.getScopeType());
}
}
return sps;
Expand All @@ -344,9 +342,7 @@ public Set<String> getAuthorizedGrantTypes() {
Set<String> grants = new HashSet<String>();
if (clientAuthorizedGrantTypes != null && !clientAuthorizedGrantTypes.isEmpty()) {
for (ClientAuthorisedGrantTypeEntity cagt : clientAuthorizedGrantTypes) {
if(cagt.getId() != null) {
grants.add(cagt.getId().getGrantType());
}
grants.add(cagt.getGrantType());
}
}
return grants;
Expand All @@ -365,9 +361,7 @@ public Set<String> getRegisteredRedirectUri() {
if (clientRegisteredRedirectUris != null && !clientRegisteredRedirectUris.isEmpty()) {
redirects = new HashSet<String>();
for (ClientRedirectUriEntity cru : clientRegisteredRedirectUris) {
if(cru.getId() != null) {
redirects.add(cru.getId().getRedirectUri());
}
redirects.add(cru.getRedirectUri());
}
}
return redirects;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,12 @@ public void setClientId(String clientId) {

@Id
@Column(name = "granted_authority")
public void setAuthority(String authority) {
this.authority = authority;
public String getAuthority() {
return this.authority;
}

@Override
public String getAuthority() {
return this.getAuthority();
public void setAuthority(String authority) {
this.authority = authority;
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@
import org.orcid.core.oauth.service.OrcidAuthorizationEndpoint;
import org.orcid.core.oauth.service.OrcidOAuth2RequestValidator;
import org.orcid.core.togglz.Features;
import org.orcid.frontend.util.AuthorizationRequestLocalCache;
import org.orcid.frontend.util.OriginalAuthorizationRequestLocalCache;
import org.orcid.frontend.util.RequestInfoFormLocalCache;
import org.orcid.frontend.web.controllers.BaseControllerUtil;
import org.orcid.frontend.web.controllers.helper.OauthHelper;
import org.orcid.frontend.web.exception.OauthInvalidRequestException;
Expand Down Expand Up @@ -82,12 +85,23 @@ public class OauthController {
@Resource
private EventManager eventManager;

@Resource
private RequestInfoFormLocalCache requestInfoFormLocalCache;

@Resource
private AuthorizationRequestLocalCache authorizationRequestLocalCache;

@Resource
private OriginalAuthorizationRequestLocalCache originalAuthorizationRequestLocalCache;

@RequestMapping(value = { "/oauth/custom/init.json" }, method = RequestMethod.POST)
public @ResponseBody RequestInfoForm loginGetHandler(HttpServletRequest request, Map<String, Object> model, @RequestParam Map<String, String> requestParameters,
SessionStatus sessionStatus, Principal principal) throws UnsupportedEncodingException {
// Populate the request info form
RequestInfoForm requestInfoForm = generateRequestInfoForm(request, request.getQueryString(), model, requestParameters, sessionStatus, principal);
request.getSession().setAttribute(OauthHelper.REQUEST_INFO_FORM, requestInfoForm);
RequestInfoForm requestInfoForm = generateRequestInfoForm(request, request.getQueryString(), model, requestParameters, sessionStatus, principal);

// Store the request info form in the cache
requestInfoFormLocalCache.put(request.getSession().getId(), requestInfoForm);

boolean isResponseSet = false;

Expand Down Expand Up @@ -136,38 +150,38 @@ public class OauthController {
@RequestMapping(value = { "/oauth/custom/authorize.json" }, method = RequestMethod.GET)
public @ResponseBody RequestInfoForm requestInfoForm(HttpServletRequest request, Map<String, Object> model, @RequestParam Map<String, String> requestParameters,
SessionStatus sessionStatus, Principal principal) throws UnsupportedEncodingException {
RequestInfoForm requestInfoForm = oauthHelper.setUserRequestInfoForm((RequestInfoForm) request.getSession().getAttribute(OauthHelper.REQUEST_INFO_FORM));
request.getSession().setAttribute(OauthHelper.REQUEST_INFO_FORM, requestInfoForm);
RequestInfoForm requestInfoForm = requestInfoFormLocalCache.get(request.getSession().getId());
oauthHelper.setUserName(requestInfoForm);
requestInfoFormLocalCache.put(request.getSession().getId(), requestInfoForm);
return setAuthorizationRequest(request, model, requestParameters, sessionStatus, principal, requestInfoForm);
}

@RequestMapping(value = { "/oauth/custom/requestInfoForm.json" }, method = RequestMethod.GET)
public @ResponseBody RequestInfoForm customRequestInfoForm(HttpServletRequest request, Map<String, Object> model, @RequestParam Map<String, String> requestParameters,
SessionStatus sessionStatus, Principal principal) throws UnsupportedEncodingException {
RequestInfoForm requestInfoForm = new RequestInfoForm();

if(request.getSession() != null && request.getSession().getAttribute(OauthHelper.REQUEST_INFO_FORM) != null) {
requestInfoForm = oauthHelper.setUserRequestInfoForm((RequestInfoForm) request.getSession().getAttribute(OauthHelper.REQUEST_INFO_FORM));
if (requestParameters.isEmpty() && request.getSession().getAttribute(OrcidOauth2Constants.OAUTH_QUERY_STRING) != null) {
try {
String url = URLDecoder.decode((String) request.getSession().getAttribute(OrcidOauth2Constants.OAUTH_QUERY_STRING), "UTF-8").trim();
if (url.startsWith("oauth=&")) {
url = url.replaceFirst("oauth=&", "");
}
String[] pairs = url.split("&");
for (int i = 0; i < pairs.length; i++) {
String pair = pairs[i];
String[] keyValue = pair.split("=");
requestParameters.put(keyValue[0], keyValue[1]);
}
setAuthorizationRequest(request, model, requestParameters, sessionStatus, principal, requestInfoForm);
} catch (NullPointerException | ArrayIndexOutOfBoundsException e) {
requestInfoForm.setError("oauth_error");
requestInfoForm.setErrorDescription("Invalid request");
if(requestInfoFormLocalCache.containsKey(request.getSession().getId())) {
requestInfoForm = requestInfoFormLocalCache.get(request.getSession().getId());
oauthHelper.setUserName(requestInfoForm);
if (requestParameters.isEmpty() && request.getSession().getAttribute(OrcidOauth2Constants.OAUTH_QUERY_STRING) != null) {
try {
String url = URLDecoder.decode((String) request.getSession().getAttribute(OrcidOauth2Constants.OAUTH_QUERY_STRING), "UTF-8").trim();
if (url.startsWith("oauth=&")) {
url = url.replaceFirst("oauth=&", "");
}
String[] pairs = url.split("&");
for (int i = 0; i < pairs.length; i++) {
String pair = pairs[i];
String[] keyValue = pair.split("=");
requestParameters.put(keyValue[0], keyValue[1]);
}
}
setAuthorizationRequest(request, model, requestParameters, sessionStatus, principal, requestInfoForm);
} catch (NullPointerException | ArrayIndexOutOfBoundsException e) {
requestInfoForm.setError("oauth_error");
requestInfoForm.setErrorDescription("Invalid request");
}
}
}
request.getSession().setAttribute(OauthHelper.REQUEST_INFO_FORM, requestInfoForm);
return requestInfoForm;
}

Expand All @@ -184,7 +198,6 @@ private RequestInfoForm generateRequestInfoForm(HttpServletRequest request, Stri
requestInfoForm.setErrorDescription(e.getMessage());
return requestInfoForm;
} catch (OauthInvalidRequestException e) {
requestInfoForm = e.getRequestInfoForm();
requestInfoForm.setError("oauth_error");
requestInfoForm.setErrorDescription(e.getMessage());
return requestInfoForm;
Expand Down Expand Up @@ -302,7 +315,7 @@ private RequestInfoForm generateRequestInfoForm(HttpServletRequest request, Stri
boolean tokenLongLifeAlreadyExists = tokenServices.longLifeTokenExist(requestInfoForm.getClientId(), baseControllerUtil.getCurrentUser(sci).getUsername(), OAuth2Utils.parseParameterList(requestInfoForm.getScopesAsString()));
if (tokenLongLifeAlreadyExists) {
setAuthorizationRequest(request, model, requestParameters, sessionStatus, principal, requestInfoForm);
AuthorizationRequest authorizationRequest = (AuthorizationRequest) request.getSession().getAttribute("authorizationRequest");
AuthorizationRequest authorizationRequest = authorizationRequestLocalCache.get(request.getSession().getId());
if (authorizationRequest != null) {
Map<String, String> requestParams = new HashMap<String, String>();
copyRequestParameters(request, requestParams);
Expand Down Expand Up @@ -334,7 +347,7 @@ private RequestInfoForm generateRequestInfoForm(HttpServletRequest request, Stri
Map<String, Object> modelAuth = new HashMap<String, Object>();
modelAuth.put("authorizationRequest", authorizationRequest);

Map<String, Object> originalRequest = (Map<String, Object>) request.getSession().getAttribute(OrcidOauth2Constants.ORIGINAL_AUTHORIZATION_REQUEST);
Map<String, Object> originalRequest = originalAuthorizationRequestLocalCache.get(request.getSession().getId());
if(originalRequest != null) {
modelAuth.put(OrcidOauth2Constants.ORIGINAL_AUTHORIZATION_REQUEST, originalRequest);
}
Expand All @@ -344,7 +357,7 @@ private RequestInfoForm generateRequestInfoForm(HttpServletRequest request, Stri
RedirectView view = (RedirectView) authorizationEndpoint.approveOrDeny(approvalParams, modelAuth, status, principal);
requestInfoForm.setRedirectUrl(view.getUrl());
// Oauth has been approved, hence, remove the oauth flag from the session
request.getSession().setAttribute(OauthHelper.REQUEST_INFO_FORM, null);
requestInfoFormLocalCache.remove(request.getSession().getId());
request.getSession().removeAttribute(OrcidOauth2Constants.OAUTH_2SCREENS);
}
}
Expand All @@ -355,7 +368,9 @@ private RequestInfoForm generateRequestInfoForm(HttpServletRequest request, Stri

private void populateSession(HttpServletRequest request, RequestInfoForm requestInfoForm) {
String url = request.getQueryString();
request.getSession().setAttribute(OauthHelper.REQUEST_INFO_FORM, requestInfoForm);

requestInfoFormLocalCache.put(request.getSession().getId(), requestInfoForm);

// Save also the original query string
request.getSession().setAttribute(OrcidOauth2Constants.OAUTH_QUERY_STRING, url);

Expand Down Expand Up @@ -397,13 +412,13 @@ private void populateSession(HttpServletRequest request, RequestInfoForm request
}

Map<String, Object> originalAuthorizationRequest = Map.copyOf(authorizationRequestMap);
request.getSession().setAttribute(OrcidOauth2Constants.ORIGINAL_AUTHORIZATION_REQUEST, originalAuthorizationRequest);
originalAuthorizationRequestLocalCache.put(request.getSession().getId(), originalAuthorizationRequest);
}

private RequestInfoForm setAuthorizationRequest(HttpServletRequest request, Map<String, Object> model, @RequestParam Map<String, String> requestParameters,
SessionStatus sessionStatus, Principal principal, RequestInfoForm requestInfoForm) {
SecurityContext sci = getSecurityContext(request);
request.getSession().setAttribute("authorizationRequest", null);
authorizationRequestLocalCache.remove(request.getSession().getId());
if (baseControllerUtil.getCurrentUser(sci) != null) {
// Authorize the request
try {
Expand All @@ -419,7 +434,7 @@ private RequestInfoForm setAuthorizationRequest(HttpServletRequest request, Map<
}

AuthorizationRequest authRequest = (AuthorizationRequest) mav.getModel().get("authorizationRequest");
request.getSession().setAttribute("authorizationRequest", authRequest);
authorizationRequestLocalCache.put(request.getSession().getId(), authRequest);
} catch (RedirectMismatchException e ) {
requestInfoForm.setError("invalid_grant");
requestInfoForm.setErrorDescription("Redirect URI doesn't match your registered redirect URIs.");
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package org.orcid.frontend.util;
import org.ehcache.Cache;
import org.ehcache.CacheManager;
import org.ehcache.config.builders.CacheConfigurationBuilder;
import org.ehcache.config.builders.CacheManagerBuilder;
import org.ehcache.config.builders.ResourcePoolsBuilder;
import org.ehcache.expiry.Duration;
import org.ehcache.expiry.Expirations;
import org.orcid.pojo.ajaxForm.RequestInfoForm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.oauth2.provider.AuthorizationRequest;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.TimeUnit;

@Component
public class AuthorizationRequestLocalCache {

@Value("${org.orcid.core.session.localCache.ttl:900}")
private int cacheTTLInSeconds;

@Value("${org.orcid.core.session.localCache.heap:10000}")
private int heapSize;

private CacheManager cacheManager;
private Cache<String, AuthorizationRequest> cache;

public AuthorizationRequestLocalCache() {
cacheManager = CacheManagerBuilder
.newCacheManagerBuilder().build();
cacheManager.init();
}

@PostConstruct
public void initCache() {
cache = cacheManager
.createCache("squaredNumber", CacheConfigurationBuilder
.newCacheConfigurationBuilder(
String.class, AuthorizationRequest.class,
ResourcePoolsBuilder.heap(heapSize)).withExpiry(Expirations.timeToLiveExpiration(Duration.of(cacheTTLInSeconds, TimeUnit.SECONDS))));
}

public AuthorizationRequest get(String key) {
return cache.get(key);
}

public void put(String key, AuthorizationRequest value) {
cache.put(key, value);
}

public void remove(String key) {
cache.remove(key);
}

public boolean containsKey(String key) {
return cache.containsKey(key);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package org.orcid.frontend.util;
import org.ehcache.Cache;
import org.ehcache.CacheManager;
import org.ehcache.config.builders.CacheConfigurationBuilder;
import org.ehcache.config.builders.CacheManagerBuilder;
import org.ehcache.config.builders.ResourcePoolsBuilder;
import org.ehcache.expiry.Duration;
import org.ehcache.expiry.Expirations;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.oauth2.provider.AuthorizationRequest;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class OriginalAuthorizationRequestLocalCache {

@Value("${org.orcid.core.session.localCache.ttl:900}")
private int cacheTTLInSeconds;

@Value("${org.orcid.core.session.localCache.heap:10000}")
private int heapSize;

private CacheManager cacheManager;
private Cache<String, Map> cache;

public OriginalAuthorizationRequestLocalCache() {
cacheManager = CacheManagerBuilder
.newCacheManagerBuilder().build();
cacheManager.init();
}

@PostConstruct
public void initCache() {
cache = cacheManager
.createCache("squaredNumber", CacheConfigurationBuilder
.newCacheConfigurationBuilder(
String.class, Map.class,
ResourcePoolsBuilder.heap(heapSize)).withExpiry(Expirations.timeToLiveExpiration(Duration.of(cacheTTLInSeconds, TimeUnit.SECONDS))));
}

public Map get(String key) {
return cache.get(key);
}

public void put(String key, Map value) {
cache.put(key, value);
}

public void remove(String key) {
cache.remove(key);
}

public boolean containsKey(String key) {
return cache.containsKey(key);
}
}
Loading

0 comments on commit 92d8a20

Please sign in to comment.