use of org.pac4j.core.profile.ProfileManager in project cas by apereo.
the class TerminateSessionAction method destroyApplicationSession.
/**
* Destroy application session.
* Also kills all delegated authn profiles via pac4j.
*
* @param request the request
* @param response the response
*/
protected void destroyApplicationSession(final HttpServletRequest request, final HttpServletResponse response) {
LOGGER.debug("Destroying application session");
final ProfileManager manager = WebUtils.getPac4jProfileManager(request, response);
manager.logout();
final HttpSession session = request.getSession();
if (session != null) {
session.invalidate();
}
}
use of org.pac4j.core.profile.ProfileManager 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.pac4j.core.profile.ProfileManager in project cas by apereo.
the class OAuth20AuthorizeEndpointController 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
*/
@GetMapping(path = OAuthConstants.BASE_OAUTH20_URL + '/' + OAuthConstants.AUTHORIZE_URL)
public ModelAndView handleRequestInternal(final HttpServletRequest request, final HttpServletResponse response) throws Exception {
final J2EContext context = WebUtils.getPac4jJ2EContext(request, response);
final ProfileManager manager = WebUtils.getPac4jProfileManager(request, response);
if (!verifyAuthorizeRequest(request) || !isRequestAuthenticated(manager, context)) {
LOGGER.error("Authorize request verification failed");
return OAuthUtils.produceUnauthorizedErrorView();
}
final String clientId = context.getRequestParameter(OAuthConstants.CLIENT_ID);
final OAuthRegisteredService registeredService = getRegisteredServiceByClientId(clientId);
try {
RegisteredServiceAccessStrategyUtils.ensureServiceAccessIsAllowed(clientId, registeredService);
} catch (final Exception e) {
LOGGER.error(e.getMessage(), e);
return OAuthUtils.produceUnauthorizedErrorView();
}
final ModelAndView mv = this.consentApprovalViewResolver.resolve(context, registeredService);
if (!mv.isEmpty() && mv.hasView()) {
return mv;
}
return redirectToCallbackRedirectUrl(manager, registeredService, context, clientId);
}
use of org.pac4j.core.profile.ProfileManager in project cas by apereo.
the class AccessTokenPasswordGrantRequestExtractor method extract.
@Override
public AccessTokenRequestDataHolder extract(final HttpServletRequest request, final HttpServletResponse response) {
final String clientId = request.getParameter(OAuth20Constants.CLIENT_ID);
final Set<String> scopes = OAuth20Utils.parseRequestScopes(request);
LOGGER.debug("Locating OAuth registered service by client id [{}]", clientId);
final OAuthRegisteredService registeredService = OAuth20Utils.getRegisteredOAuthServiceByClientId(this.servicesManager, clientId);
LOGGER.debug("Located OAuth registered service [{}]", registeredService);
final J2EContext context = Pac4jUtils.getPac4jJ2EContext(request, response);
final ProfileManager manager = Pac4jUtils.getPac4jProfileManager(request, response);
final Optional<UserProfile> profile = manager.get(true);
if (!profile.isPresent()) {
throw new UnauthorizedServiceException("OAuth user profile cannot be determined");
}
final UserProfile uProfile = profile.get();
LOGGER.debug("Creating matching service request based on [{}]", registeredService);
final boolean requireServiceHeader = oAuthProperties.getGrants().getResourceOwner().isRequireServiceHeader();
if (requireServiceHeader) {
LOGGER.debug("Using request headers to identify and build the target service url");
}
final Service service = this.authenticationBuilder.buildService(registeredService, context, requireServiceHeader);
LOGGER.debug("Authenticating the OAuth request indicated by [{}]", service);
final Authentication authentication = this.authenticationBuilder.build(uProfile, registeredService, context, service);
final AuditableContext audit = AuditableContext.builder().service(service).authentication(authentication).registeredService(registeredService).retrievePrincipalAttributesFromReleasePolicy(Boolean.TRUE).build();
final AuditableExecutionResult accessResult = this.registeredServiceAccessStrategyEnforcer.execute(audit);
accessResult.throwExceptionIfNeeded();
final AuthenticationResult result = new DefaultAuthenticationResult(authentication, requireServiceHeader ? service : null);
final TicketGrantingTicket ticketGrantingTicket = this.centralAuthenticationService.createTicketGrantingTicket(result);
return new AccessTokenRequestDataHolder(service, authentication, registeredService, ticketGrantingTicket, getGrantType(), scopes);
}
use of org.pac4j.core.profile.ProfileManager in project knox by apache.
the class Pac4jIdentityAdapter method doFilter.
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
final HttpServletRequest request = (HttpServletRequest) servletRequest;
final HttpServletResponse response = (HttpServletResponse) servletResponse;
final J2EContext context = new J2EContext(request, response, ((Config) request.getAttribute(PAC4J_CONFIG)).getSessionStore());
final ProfileManager<CommonProfile> manager = new ProfileManager<CommonProfile>(context);
final Optional<CommonProfile> optional = manager.get(true);
if (optional.isPresent()) {
CommonProfile profile = optional.get();
logger.debug("User authenticated as: {}", profile);
manager.remove(true);
String id = null;
if (idAttribute != null) {
Object attribute = profile.getAttribute(idAttribute);
if (attribute != null) {
id = attribute.toString();
}
if (id == null) {
logger.error("Invalid attribute_id: {} configured to be used as principal" + " falling back to default id", idAttribute);
}
}
if (id == null) {
id = profile.getId();
}
testIdentifier = id;
PrimaryPrincipal pp = new PrimaryPrincipal(id);
Subject subject = new Subject();
subject.getPrincipals().add(pp);
auditService.getContext().setUsername(id);
String sourceUri = (String) request.getAttribute(AbstractGatewayFilter.SOURCE_REQUEST_CONTEXT_URL_ATTRIBUTE_NAME);
auditor.audit(Action.AUTHENTICATION, sourceUri, ResourceType.URI, ActionOutcome.SUCCESS);
doAs(request, response, chain, subject);
}
}
Aggregations