use of org.springframework.security.authentication.InsufficientAuthenticationException in project dhis2-core by dhis2.
the class SpringSecurityActionAccessResolver method hasAccess.
// -------------------------------------------------------------------------
// ActionAccessResolver implementation
// -------------------------------------------------------------------------
@Override
public boolean hasAccess(String module, String name) {
// ---------------------------------------------------------------------
// Get ObjectDefinitionSource
// ---------------------------------------------------------------------
Configuration config = Dispatcher.getInstance().getConfigurationManager().getConfiguration();
PackageConfig packageConfig = config.getPackageConfig(module);
if (packageConfig == null) {
throw new IllegalArgumentException("Module doesn't exist: '" + module + "'");
}
ActionConfig actionConfig = packageConfig.getActionConfigs().get(name);
if (actionConfig == null) {
throw new IllegalArgumentException("Module " + module + " doesn't have an action named: '" + name + "'");
}
SecurityMetadataSource securityMetadataSource = requiredAuthoritiesProvider.createSecurityMetadataSource(actionConfig);
// ---------------------------------------------------------------------
// Test access
// ---------------------------------------------------------------------
SecurityContext securityContext = SecurityContextHolder.getContext();
Authentication authentication = securityContext.getAuthentication();
try {
if (securityMetadataSource.getAttributes(actionConfig) != null) {
if (authentication == null || !authentication.isAuthenticated()) {
return false;
}
accessDecisionManager.decide(authentication, actionConfig, securityMetadataSource.getAttributes(actionConfig));
}
log.debug("Access to [" + module + ", " + name + "]: TRUE");
return true;
} catch (AccessDeniedException e) {
log.debug("Access to [" + module + ", " + name + "]: FALSE (access denied)");
return false;
} catch (InsufficientAuthenticationException e) {
log.debug("Access to [" + module + ", " + name + "]: FALSE (insufficient authentication)");
return false;
}
}
use of org.springframework.security.authentication.InsufficientAuthenticationException in project dhis2-core by dhis2.
the class LogicalOrAccessDecisionManager method decide.
// -------------------------------------------------------------------------
// Interface implementation
// -------------------------------------------------------------------------
@Override
public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
AccessDeniedException ade = null;
InsufficientAuthenticationException iae = null;
for (AccessDecisionManager accessDecisionManager : accessDecisionManagers) {
if (accessDecisionManager.supports(object.getClass())) {
try {
accessDecisionManager.decide(authentication, object, configAttributes);
LOG.debug("ACCESS GRANTED [" + object.toString() + "]");
return;
} catch (AccessDeniedException e) {
ade = e;
} catch (InsufficientAuthenticationException e) {
iae = e;
}
}
}
LOG.debug("ACCESS DENIED [" + object.toString() + "]");
if (ade != null) {
throw ade;
}
if (iae != null) {
throw iae;
}
}
use of org.springframework.security.authentication.InsufficientAuthenticationException in project ORCID-Source by ORCID.
the class OrcidClientCredentialEndPointDelegatorImpl method obtainOauth2Token.
@Transactional
public Response obtainOauth2Token(String authorization, MultivaluedMap<String, String> formParams) {
String code = formParams.getFirst("code");
String clientId = formParams.getFirst(OrcidOauth2Constants.CLIENT_ID_PARAM);
String state = formParams.getFirst(OrcidOauth2Constants.STATE_PARAM);
String redirectUri = formParams.getFirst(OrcidOauth2Constants.REDIRECT_URI_PARAM);
String refreshToken = formParams.getFirst(OrcidOauth2Constants.REFRESH_TOKEN);
String scopeList = formParams.getFirst(OrcidOauth2Constants.SCOPE_PARAM);
String grantType = formParams.getFirst(OrcidOauth2Constants.GRANT_TYPE);
Boolean revokeOld = formParams.containsKey(OrcidOauth2Constants.REVOKE_OLD) ? Boolean.valueOf(formParams.getFirst(OrcidOauth2Constants.REVOKE_OLD)) : true;
Long expiresIn = calculateExpiresIn(formParams);
String bearerToken = null;
Set<String> scopes = new HashSet<String>();
if (StringUtils.isNotEmpty(scopeList)) {
scopes = OAuth2Utils.parseParameterList(scopeList);
}
if (OrcidOauth2Constants.REFRESH_TOKEN.equals(grantType)) {
if (!PojoUtil.isEmpty(authorization)) {
if ((authorization.toLowerCase().startsWith(OAuth2AccessToken.BEARER_TYPE.toLowerCase()))) {
String authHeaderValue = authorization.substring(OAuth2AccessToken.BEARER_TYPE.length()).trim();
int commaIndex = authHeaderValue.indexOf(',');
if (commaIndex > 0) {
authHeaderValue = authHeaderValue.substring(0, commaIndex);
}
bearerToken = authHeaderValue;
if (PojoUtil.isEmpty(bearerToken)) {
throw new IllegalArgumentException("Refresh token request doesnt include the authorization");
}
}
}
}
LOGGER.info("OAuth2 authorization requested: clientId={}, grantType={}, refreshToken={}, code={}, scopes={}, state={}, redirectUri={}", new Object[] { clientId, grantType, refreshToken, code, scopes, state, redirectUri });
Authentication client = getClientAuthentication();
if (!client.isAuthenticated()) {
LOGGER.info("Not authenticated for OAuth2: clientId={}, grantType={}, refreshToken={}, code={}, scopes={}, state={}, redirectUri={}", new Object[] { clientId, grantType, refreshToken, code, scopes, state, redirectUri });
throw new InsufficientAuthenticationException(localeManager.resolveMessage("apiError.client_not_authenticated.exception"));
}
/**
* Patch, update any orcid-grants scope to funding scope
* */
for (String scope : scopes) {
if (scope.contains("orcid-grants")) {
String newScope = scope.replace("orcid-grants", "funding");
LOGGER.info("Client {} provided a grants scope {} which will be updated to {}", new Object[] { clientId, scope, newScope });
scopes.remove(scope);
scopes.add(newScope);
}
}
try {
if (scopes != null) {
List<String> toRemove = new ArrayList<String>();
for (String scope : scopes) {
ScopePathType scopeType = ScopePathType.fromValue(scope);
if (scopeType.isInternalScope()) {
// You should not allow any internal scope here! go away!
String message = localeManager.resolveMessage("apiError.9015.developerMessage", new Object[] {});
throw new OrcidInvalidScopeException(message);
} else if (OrcidOauth2Constants.GRANT_TYPE_CLIENT_CREDENTIALS.equals(grantType)) {
if (!scopeType.isClientCreditalScope())
toRemove.add(scope);
} else {
if (scopeType.isClientCreditalScope())
toRemove.add(scope);
}
}
for (String remove : toRemove) {
scopes.remove(remove);
}
}
} catch (IllegalArgumentException iae) {
String message = localeManager.resolveMessage("apiError.9015.developerMessage", new Object[] {});
throw new OrcidInvalidScopeException(message);
}
OAuth2AccessToken token = generateToken(client, scopes, code, redirectUri, grantType, refreshToken, state, bearerToken, revokeOld, expiresIn);
return getResponse(token);
}
use of org.springframework.security.authentication.InsufficientAuthenticationException in project spring-security-oauth by spring-projects.
the class OAuthConsumerProcessingFilter method doFilter.
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
Set<String> accessTokenDeps = getAccessTokenDependencies(request, response, chain);
if (!accessTokenDeps.isEmpty()) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (isRequireAuthenticated() && !authentication.isAuthenticated()) {
throw new InsufficientAuthenticationException("An authenticated principal must be present.");
}
OAuthSecurityContext context = OAuthSecurityContextHolder.getContext();
if (context == null) {
throw new IllegalStateException("No OAuth security context has been established. Unable to access resources.");
}
Map<String, OAuthConsumerToken> accessTokens = context.getAccessTokens();
for (String dependency : accessTokenDeps) {
if (!accessTokens.containsKey(dependency)) {
throw new AccessTokenRequiredException(getProtectedResourceDetailsService().loadProtectedResourceDetailsById(dependency));
}
}
chain.doFilter(request, response);
} else {
if (LOG.isDebugEnabled()) {
LOG.debug("No access token dependencies for request.");
}
chain.doFilter(servletRequest, servletResponse);
}
}
use of org.springframework.security.authentication.InsufficientAuthenticationException in project spring-security-oauth by spring-projects.
the class AuthorizationEndpoint method approveOrDeny.
@RequestMapping(value = "/oauth/authorize", method = RequestMethod.POST, params = OAuth2Utils.USER_OAUTH_APPROVAL)
public View approveOrDeny(@RequestParam Map<String, String> approvalParameters, Map<String, ?> model, SessionStatus sessionStatus, Principal principal) {
if (!(principal instanceof Authentication)) {
sessionStatus.setComplete();
throw new InsufficientAuthenticationException("User must be authenticated with Spring Security before authorizing an access token.");
}
AuthorizationRequest authorizationRequest = (AuthorizationRequest) model.get("authorizationRequest");
if (authorizationRequest == null) {
sessionStatus.setComplete();
throw new InvalidRequestException("Cannot approve uninitialized authorization request.");
}
try {
Set<String> responseTypes = authorizationRequest.getResponseTypes();
authorizationRequest.setApprovalParameters(approvalParameters);
authorizationRequest = userApprovalHandler.updateAfterApproval(authorizationRequest, (Authentication) principal);
boolean approved = userApprovalHandler.isApproved(authorizationRequest, (Authentication) principal);
authorizationRequest.setApproved(approved);
if (authorizationRequest.getRedirectUri() == null) {
sessionStatus.setComplete();
throw new InvalidRequestException("Cannot approve request when no redirect URI is provided.");
}
if (!authorizationRequest.isApproved()) {
return new RedirectView(getUnsuccessfulRedirect(authorizationRequest, new UserDeniedAuthorizationException("User denied access"), responseTypes.contains("token")), false, true, false);
}
if (responseTypes.contains("token")) {
return getImplicitGrantResponse(authorizationRequest).getView();
}
return getAuthorizationCodeResponse(authorizationRequest, (Authentication) principal);
} finally {
sessionStatus.setComplete();
}
}
Aggregations