use of org.apereo.cas.support.oauth.profile.OAuthUserProfile in project cas by apereo.
the class OAuth20AccessTokenEndpointController method handleRequestInternal.
/**
* Handle request internal model and view.
*
* @param request the request
* @param response the response
* @return the model and view
* @throws Exception the exception
*/
@PostMapping(path = OAuthConstants.BASE_OAUTH20_URL + '/' + OAuthConstants.ACCESS_TOKEN_URL)
public ModelAndView handleRequestInternal(final HttpServletRequest request, final HttpServletResponse response) throws Exception {
try {
response.setContentType(MediaType.TEXT_PLAIN_VALUE);
if (!verifyAccessTokenRequest(request, response)) {
LOGGER.error("Access token request verification fails");
return OAuthUtils.writeTextError(response, OAuthConstants.INVALID_REQUEST);
}
final String grantType = request.getParameter(OAuthConstants.GRANT_TYPE);
final Service service;
final Authentication authentication;
final boolean generateRefreshToken;
final OAuthRegisteredService registeredService;
final J2EContext context = WebUtils.getPac4jJ2EContext(request, response);
final ProfileManager manager = WebUtils.getPac4jProfileManager(request, response);
if (isGrantType(grantType, OAuth20GrantTypes.AUTHORIZATION_CODE) || isGrantType(grantType, OAuth20GrantTypes.REFRESH_TOKEN)) {
final Optional<UserProfile> profile = manager.get(true);
final String clientId = profile.get().getId();
registeredService = OAuthUtils.getRegisteredOAuthService(getServicesManager(), clientId);
// we generate a refresh token if requested by the service but not from a refresh token
generateRefreshToken = registeredService != null && registeredService.isGenerateRefreshToken() && isGrantType(grantType, OAuth20GrantTypes.AUTHORIZATION_CODE);
final String parameterName;
if (isGrantType(grantType, OAuth20GrantTypes.AUTHORIZATION_CODE)) {
parameterName = OAuthConstants.CODE;
} else {
parameterName = OAuthConstants.REFRESH_TOKEN;
}
final OAuthToken token = getToken(request, parameterName);
if (token == null) {
LOGGER.error("No token found for authorization_code or refresh_token grant types");
return OAuthUtils.writeTextError(response, OAuthConstants.INVALID_GRANT);
}
service = token.getService();
authentication = token.getAuthentication();
} else {
final String clientId = request.getParameter(OAuthConstants.CLIENT_ID);
registeredService = OAuthUtils.getRegisteredOAuthService(getServicesManager(), clientId);
generateRefreshToken = registeredService != null && registeredService.isGenerateRefreshToken();
try {
// resource owner password grant type
final Optional<OAuthUserProfile> profile = manager.get(true);
if (!profile.isPresent()) {
throw new UnauthorizedServiceException("OAuth user profile cannot be determined");
}
service = createService(registeredService, context);
authentication = createAuthentication(profile.get(), registeredService, context, service);
RegisteredServiceAccessStrategyUtils.ensurePrincipalAccessIsAllowedForService(service, registeredService, authentication);
} catch (final Exception e) {
LOGGER.error(e.getMessage(), e);
return OAuthUtils.writeTextError(response, OAuthConstants.INVALID_GRANT);
}
}
final AccessToken accessToken = generateAccessToken(service, authentication, context);
RefreshToken refreshToken = null;
if (generateRefreshToken) {
refreshToken = this.refreshTokenFactory.create(service, authentication);
getTicketRegistry().addTicket(refreshToken);
}
LOGGER.debug("access token: [{}] / timeout: [{}] / refresh token: [{}]", accessToken, casProperties.getTicket().getTgt().getTimeToKillInSeconds(), refreshToken);
final String responseType = context.getRequestParameter(OAuthConstants.RESPONSE_TYPE);
final OAuth20ResponseTypes type = Arrays.stream(OAuth20ResponseTypes.values()).filter(t -> t.getType().equalsIgnoreCase(responseType)).findFirst().orElse(OAuth20ResponseTypes.CODE);
this.accessTokenResponseGenerator.generate(request, response, registeredService, service, accessToken, refreshToken, casProperties.getTicket().getTgt().getTimeToKillInSeconds(), type);
getTicketRegistry().addTicket(accessToken);
response.setStatus(HttpServletResponse.SC_OK);
return null;
} catch (final Exception e) {
LOGGER.error(e.getMessage(), e);
throw Throwables.propagate(e);
}
}
use of org.apereo.cas.support.oauth.profile.OAuthUserProfile in project cas by apereo.
the class OAuthUserAuthenticator method validate.
@Override
public void validate(final UsernamePasswordCredentials credentials, final WebContext context) throws CredentialsException {
final UsernamePasswordCredential casCredential = new UsernamePasswordCredential(credentials.getUsername(), credentials.getPassword());
try {
final String clientId = context.getRequestParameter(OAuthConstants.CLIENT_ID);
final Service service = this.webApplicationServiceFactory.createService(clientId);
final RegisteredService registeredService = OAuthUtils.getRegisteredOAuthService(this.servicesManager, clientId);
RegisteredServiceAccessStrategyUtils.ensureServiceAccessIsAllowed(registeredService);
final AuthenticationResult authenticationResult = this.authenticationSystemSupport.handleAndFinalizeSingleAuthenticationTransaction(null, casCredential);
final Authentication authentication = authenticationResult.getAuthentication();
final Principal principal = authentication.getPrincipal();
final OAuthUserProfile profile = new OAuthUserProfile();
final String id = registeredService.getUsernameAttributeProvider().resolveUsername(principal, service);
LOGGER.debug("Created profile id [{}]", id);
profile.setId(id);
final Map<String, Object> attributes = registeredService.getAttributeReleasePolicy().getAttributes(principal, registeredService);
profile.addAttributes(attributes);
LOGGER.debug("Authenticated user profile [{}]", profile);
credentials.setUserProfile(profile);
} catch (final Exception e) {
throw new CredentialsException("Cannot login user using CAS internal authentication", e);
}
}
use of org.apereo.cas.support.oauth.profile.OAuthUserProfile in project cas by apereo.
the class OAuth20AccessTokenEndpointController method verifyAccessTokenRequest.
/**
* Verify the access token request.
*
* @param request the HTTP request
* @param response the HTTP response
* @return true, if successful
*/
private boolean verifyAccessTokenRequest(final HttpServletRequest request, final HttpServletResponse response) {
// must have the right grant type
final String grantType = request.getParameter(OAuthConstants.GRANT_TYPE);
if (!checkGrantTypes(grantType, OAuth20GrantTypes.AUTHORIZATION_CODE, OAuth20GrantTypes.PASSWORD, OAuth20GrantTypes.REFRESH_TOKEN)) {
return false;
}
// must be authenticated (client or user)
final J2EContext context = WebUtils.getPac4jJ2EContext(request, response);
final ProfileManager manager = WebUtils.getPac4jProfileManager(request, response);
final Optional<UserProfile> profile = manager.get(true);
if (profile == null || !profile.isPresent()) {
return false;
}
final UserProfile uProfile = profile.get();
// authorization code grant type
if (isGrantType(grantType, OAuth20GrantTypes.AUTHORIZATION_CODE)) {
final String clientId = uProfile.getId();
final String redirectUri = request.getParameter(OAuthConstants.REDIRECT_URI);
final OAuthRegisteredService registeredService = OAuthUtils.getRegisteredOAuthService(getServicesManager(), clientId);
return uProfile instanceof OAuthClientProfile && getValidator().checkParameterExist(request, OAuthConstants.REDIRECT_URI) && getValidator().checkParameterExist(request, OAuthConstants.CODE) && getValidator().checkCallbackValid(registeredService, redirectUri);
} else if (isGrantType(grantType, OAuth20GrantTypes.REFRESH_TOKEN)) {
// refresh token grant type
return uProfile instanceof OAuthClientProfile && getValidator().checkParameterExist(request, OAuthConstants.REFRESH_TOKEN);
} else {
final String clientId = request.getParameter(OAuthConstants.CLIENT_ID);
final OAuthRegisteredService registeredService = OAuthUtils.getRegisteredOAuthService(getServicesManager(), clientId);
// resource owner password grant type
return uProfile instanceof OAuthUserProfile && getValidator().checkParameterExist(request, OAuthConstants.CLIENT_ID) && getValidator().checkServiceValid(registeredService);
}
}
Aggregations