use of org.springframework.security.authentication.InsufficientAuthenticationException in project spring-security-oauth by spring-projects.
the class AuthorizationEndpoint method authorize.
@RequestMapping(value = "/oauth/authorize")
public ModelAndView authorize(Map<String, Object> model, @RequestParam Map<String, String> parameters, SessionStatus sessionStatus, Principal principal) {
// Pull out the authorization request first, using the OAuth2RequestFactory. All further logic should
// query off of the authorization request instead of referring back to the parameters map. The contents of the
// parameters map will be stored without change in the AuthorizationRequest object once it is created.
AuthorizationRequest authorizationRequest = getOAuth2RequestFactory().createAuthorizationRequest(parameters);
Set<String> responseTypes = authorizationRequest.getResponseTypes();
if (!responseTypes.contains("token") && !responseTypes.contains("code")) {
throw new UnsupportedResponseTypeException("Unsupported response types: " + responseTypes);
}
if (authorizationRequest.getClientId() == null) {
throw new InvalidClientException("A client id must be provided");
}
try {
if (!(principal instanceof Authentication) || !((Authentication) principal).isAuthenticated()) {
throw new InsufficientAuthenticationException("User must be authenticated with Spring Security before authorization can be completed.");
}
ClientDetails client = getClientDetailsService().loadClientByClientId(authorizationRequest.getClientId());
// The resolved redirect URI is either the redirect_uri from the parameters or the one from
// clientDetails. Either way we need to store it on the AuthorizationRequest.
String redirectUriParameter = authorizationRequest.getRequestParameters().get(OAuth2Utils.REDIRECT_URI);
String resolvedRedirect = redirectResolver.resolveRedirect(redirectUriParameter, client);
if (!StringUtils.hasText(resolvedRedirect)) {
throw new RedirectMismatchException("A redirectUri must be either supplied or preconfigured in the ClientDetails");
}
authorizationRequest.setRedirectUri(resolvedRedirect);
// We intentionally only validate the parameters requested by the client (ignoring any data that may have
// been added to the request by the manager).
oauth2RequestValidator.validateScope(authorizationRequest, client);
// Some systems may allow for approval decisions to be remembered or approved by default. Check for
// such logic here, and set the approved flag on the authorization request accordingly.
authorizationRequest = userApprovalHandler.checkForPreApproval(authorizationRequest, (Authentication) principal);
// TODO: is this call necessary?
boolean approved = userApprovalHandler.isApproved(authorizationRequest, (Authentication) principal);
authorizationRequest.setApproved(approved);
// Validation is all done, so we can check for auto approval...
if (authorizationRequest.isApproved()) {
if (responseTypes.contains("token")) {
return getImplicitGrantResponse(authorizationRequest);
}
if (responseTypes.contains("code")) {
return new ModelAndView(getAuthorizationCodeResponse(authorizationRequest, (Authentication) principal));
}
}
// Place auth request into the model so that it is stored in the session
// for approveOrDeny to use. That way we make sure that auth request comes from the session,
// so any auth request parameters passed to approveOrDeny will be ignored and retrieved from the session.
model.put("authorizationRequest", authorizationRequest);
return getUserApprovalPageResponse(model, authorizationRequest, (Authentication) principal);
} catch (RuntimeException e) {
sessionStatus.setComplete();
throw e;
}
}
use of org.springframework.security.authentication.InsufficientAuthenticationException in project spring-security-oauth by spring-projects.
the class ImplicitTokenGranter method getOAuth2Authentication.
@Override
protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest clientToken) {
Authentication userAuth = SecurityContextHolder.getContext().getAuthentication();
if (userAuth == null || !userAuth.isAuthenticated()) {
throw new InsufficientAuthenticationException("There is no currently logged in user");
}
Assert.state(clientToken instanceof ImplicitTokenRequest, "An ImplicitTokenRequest is required here. Caller needs to wrap the TokenRequest.");
OAuth2Request requestForStorage = ((ImplicitTokenRequest) clientToken).getOAuth2Request();
return new OAuth2Authentication(requestForStorage, userAuth);
}
use of org.springframework.security.authentication.InsufficientAuthenticationException in project ORCID-Source by ORCID.
the class OAuthErrorUtilsTest method testGetOAuthErrorForInsufficientAuthenticationException.
@Test
public void testGetOAuthErrorForInsufficientAuthenticationException() {
OAuthError error = OAuthErrorUtils.getOAuthError(new InsufficientAuthenticationException("message here"));
assertEquals(OAuthError.UNAUTHORIZED_CLIENT, error.getError());
assertEquals(Status.UNAUTHORIZED, error.getResponseStatus());
assertEquals("message here", error.getErrorDescription());
}
use of org.springframework.security.authentication.InsufficientAuthenticationException in project ORCID-Source by ORCID.
the class InternalClientCredentialEndPointDelegatorImpl method obtainOauth2Token.
@Override
@Transactional
public Response obtainOauth2Token(String authorization, MultivaluedMap<String, String> formParams) {
String clientId = formParams.getFirst("client_id");
String scopeList = formParams.getFirst("scope");
String grantType = formParams.getFirst("grant_type");
// Verify it is a client_credentials grant type request
if (!OrcidOauth2Constants.GRANT_TYPE_CLIENT_CREDENTIALS.equals(grantType)) {
Object[] params = { grantType };
throw new UnsupportedGrantTypeException(localeManager.resolveMessage("apiError.unsupported_client_type.exception", params));
}
Authentication client = getClientAuthentication();
if (!client.isAuthenticated()) {
LOGGER.info("Not authenticated for OAuth2: clientId={}, grantType={}, scope={}", new Object[] { clientId, grantType, scopeList });
throw new InsufficientAuthenticationException(localeManager.resolveMessage("apiError.client_not_authenticated.exception"));
}
Set<String> scopes = new HashSet<String>();
if (StringUtils.isNotEmpty(scopeList)) {
scopes = OAuth2Utils.parseParameterList(scopeList);
}
// Verify it is requesting an internal scope
HashSet<String> filteredScopes = new HashSet<String>();
for (String scope : scopes) {
ScopePathType scopeType = ScopePathType.fromValue(scope);
if (scopeType.isInternalScope()) {
filteredScopes.add(scope);
}
}
if (filteredScopes.isEmpty()) {
String message = localeManager.resolveMessage("apiError.9015.developerMessage", new Object[] {});
throw new OrcidInvalidScopeException(message);
}
OAuth2AccessToken token = generateToken(client, scopes, null, null, grantType, null, null, null, false, 0L);
return getResponse(token);
}
use of org.springframework.security.authentication.InsufficientAuthenticationException in project libresonic by Libresonic.
the class JWTAuthenticationProvider method authenticate.
@Override
public Authentication authenticate(Authentication auth) throws AuthenticationException {
JWTAuthenticationToken authentication = (JWTAuthenticationToken) auth;
if (authentication.getCredentials() == null || !(authentication.getCredentials() instanceof String)) {
logger.error("Credentials not present");
return null;
}
String rawToken = (String) auth.getCredentials();
DecodedJWT token = JWTSecurityService.verify(jwtKey, rawToken);
Claim path = token.getClaim(JWTSecurityService.CLAIM_PATH);
authentication.setAuthenticated(true);
// TODO:AD This is super unfortunate, but not sure there is a better way when using JSP
if (StringUtils.contains(authentication.getRequestedPath(), "/WEB-INF/jsp/")) {
logger.warn("BYPASSING AUTH FOR WEB-INF page");
} else if (!roughlyEqual(path.asString(), authentication.getRequestedPath())) {
throw new InsufficientAuthenticationException("Credentials not valid for path " + authentication.getRequestedPath() + ". They are valid for " + path.asString());
}
List<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority("IS_AUTHENTICATED_FULLY"));
authorities.add(new SimpleGrantedAuthority("ROLE_TEMP"));
return new JWTAuthenticationToken(authorities, rawToken, authentication.getRequestedPath());
}
Aggregations