Search in sources :

Example 21 with J2EContext

use of org.pac4j.core.context.J2EContext in project cas by apereo.

the class RegisteredServiceResource method authenticateRequest.

private Authentication authenticateRequest(final HttpServletRequest request, final HttpServletResponse response) {
    final BasicAuthExtractor extractor = new BasicAuthExtractor();
    final WebContext webContext = new J2EContext(request, response);
    final UsernamePasswordCredentials credentials = extractor.extract(webContext);
    if (credentials != null) {
        LOGGER.debug("Received basic authentication request from credentials [{}]", credentials);
        final Credential c = new UsernamePasswordCredential(credentials.getUsername(), credentials.getPassword());
        final Service serviceRequest = this.serviceFactory.createService(request);
        final AuthenticationResult result = authenticationSystemSupport.handleAndFinalizeSingleAuthenticationTransaction(serviceRequest, c);
        return result.getAuthentication();
    }
    throw new BadRestRequestException("Could not authenticate request");
}
Also used : BasicAuthExtractor(org.pac4j.core.credentials.extractor.BasicAuthExtractor) UsernamePasswordCredential(org.apereo.cas.authentication.UsernamePasswordCredential) Credential(org.apereo.cas.authentication.Credential) WebContext(org.pac4j.core.context.WebContext) RegisteredService(org.apereo.cas.services.RegisteredService) Service(org.apereo.cas.authentication.principal.Service) BadRestRequestException(org.apereo.cas.rest.BadRestRequestException) J2EContext(org.pac4j.core.context.J2EContext) UsernamePasswordCredential(org.apereo.cas.authentication.UsernamePasswordCredential) UsernamePasswordCredentials(org.pac4j.core.credentials.UsernamePasswordCredentials) AuthenticationResult(org.apereo.cas.authentication.AuthenticationResult)

Example 22 with J2EContext

use of org.pac4j.core.context.J2EContext in project cas by apereo.

the class OAuth20AccessTokenEndpointController method handleRequest.

/**
 * Handle request internal model and view.
 *
 * @param request  the request
 * @param response the response
 * @throws Exception the exception
 */
@PostMapping(path = { OAuth20Constants.BASE_OAUTH20_URL + '/' + OAuth20Constants.ACCESS_TOKEN_URL, OAuth20Constants.BASE_OAUTH20_URL + '/' + OAuth20Constants.TOKEN_URL })
@SneakyThrows
public void handleRequest(final HttpServletRequest request, final HttpServletResponse response) throws Exception {
    response.setContentType(MediaType.TEXT_PLAIN_VALUE);
    try {
        if (!verifyAccessTokenRequest(request, response)) {
            throw new IllegalArgumentException("Access token validation failed");
        }
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
        OAuth20Utils.writeTextError(response, OAuth20Constants.INVALID_REQUEST);
        return;
    }
    final AccessTokenRequestDataHolder requestHolder;
    try {
        requestHolder = examineAndExtractAccessTokenGrantRequest(request, response);
        LOGGER.debug("Creating access token for [{}]", requestHolder);
    } catch (final Exception e) {
        LOGGER.error("Could not identify and extract access token request", e);
        OAuth20Utils.writeTextError(response, OAuth20Constants.INVALID_GRANT);
        return;
    }
    final J2EContext context = Pac4jUtils.getPac4jJ2EContext(request, response);
    final Pair<AccessToken, RefreshToken> accessToken = accessTokenGenerator.generate(requestHolder);
    LOGGER.debug("Access token generated is: [{}]. Refresh token generated is [{}]", accessToken.getKey(), accessToken.getValue());
    generateAccessTokenResponse(request, response, requestHolder, context, accessToken.getKey(), accessToken.getValue());
    response.setStatus(HttpServletResponse.SC_OK);
}
Also used : RefreshToken(org.apereo.cas.ticket.refreshtoken.RefreshToken) AccessToken(org.apereo.cas.ticket.accesstoken.AccessToken) J2EContext(org.pac4j.core.context.J2EContext) AccessTokenRequestDataHolder(org.apereo.cas.support.oauth.web.response.accesstoken.ext.AccessTokenRequestDataHolder) PostMapping(org.springframework.web.bind.annotation.PostMapping) SneakyThrows(lombok.SneakyThrows)

Example 23 with J2EContext

use of org.pac4j.core.context.J2EContext in project cas by apereo.

the class OAuth20AuthorizeEndpointController method handleRequest.

/**
 * Handle request via GET.
 *
 * @param request  the request
 * @param response the response
 * @return the model and view
 * @throws Exception the exception
 */
@GetMapping(path = OAuth20Constants.BASE_OAUTH20_URL + '/' + OAuth20Constants.AUTHORIZE_URL)
public ModelAndView handleRequest(final HttpServletRequest request, final HttpServletResponse response) throws Exception {
    final J2EContext context = Pac4jUtils.getPac4jJ2EContext(request, response);
    final ProfileManager manager = Pac4jUtils.getPac4jProfileManager(request, response);
    if (!verifyAuthorizeRequest(context) || !isRequestAuthenticated(manager, context)) {
        LOGGER.error("Authorize request verification failed. Either the authorization request is missing required parameters, " + "or the request is not authenticated and contains no authenticated profile/principal.");
        return OAuth20Utils.produceUnauthorizedErrorView();
    }
    final String clientId = context.getRequestParameter(OAuth20Constants.CLIENT_ID);
    final OAuthRegisteredService registeredService = getRegisteredServiceByClientId(clientId);
    try {
        RegisteredServiceAccessStrategyUtils.ensureServiceAccessIsAllowed(clientId, registeredService);
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
        return OAuth20Utils.produceUnauthorizedErrorView();
    }
    final ModelAndView mv = this.consentApprovalViewResolver.resolve(context, registeredService);
    if (!mv.isEmpty() && mv.hasView()) {
        return mv;
    }
    return redirectToCallbackRedirectUrl(manager, registeredService, context, clientId);
}
Also used : ProfileManager(org.pac4j.core.profile.ProfileManager) OAuthRegisteredService(org.apereo.cas.support.oauth.services.OAuthRegisteredService) ModelAndView(org.springframework.web.servlet.ModelAndView) J2EContext(org.pac4j.core.context.J2EContext) PrincipalException(org.apereo.cas.authentication.PrincipalException) UnauthorizedServiceException(org.apereo.cas.services.UnauthorizedServiceException) GetMapping(org.springframework.web.bind.annotation.GetMapping)

Example 24 with J2EContext

use of org.pac4j.core.context.J2EContext in project cas by apereo.

the class OAuth20CallbackAuthorizeEndpointController method handleRequest.

/**
 * Handle request.
 *
 * @param request  the request
 * @param response the response
 * @return the model and view
 */
@GetMapping(path = OAuth20Constants.BASE_OAUTH20_URL + '/' + OAuth20Constants.CALLBACK_AUTHORIZE_URL)
public ModelAndView handleRequest(final HttpServletRequest request, final HttpServletResponse response) {
    final J2EContext context = new J2EContext(request, response, this.oauthConfig.getSessionStore());
    final DefaultCallbackLogic callback = new DefaultCallbackLogic();
    callback.perform(context, oauthConfig, J2ENopHttpActionAdapter.INSTANCE, null, true, false, false, Authenticators.CAS_OAUTH_CLIENT);
    final String url = StringUtils.remove(response.getHeader("Location"), "redirect:");
    final ProfileManager manager = Pac4jUtils.getPac4jProfileManager(request, response);
    return oAuth20CallbackAuthorizeViewResolver.resolve(context, manager, url);
}
Also used : ProfileManager(org.pac4j.core.profile.ProfileManager) J2EContext(org.pac4j.core.context.J2EContext) DefaultCallbackLogic(org.pac4j.core.engine.DefaultCallbackLogic) GetMapping(org.springframework.web.bind.annotation.GetMapping)

Example 25 with J2EContext

use of org.pac4j.core.context.J2EContext in project cas by apereo.

the class OAuth20UserProfileEndpointController method handleRequest.

/**
 * Handle request internal response entity.
 *
 * @param request  the request
 * @param response the response
 * @return the response entity
 * @throws Exception the exception
 */
@GetMapping(path = OAuth20Constants.BASE_OAUTH20_URL + '/' + OAuth20Constants.PROFILE_URL, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> handleRequest(final HttpServletRequest request, final HttpServletResponse response) throws Exception {
    response.setContentType(MediaType.APPLICATION_JSON_VALUE);
    final J2EContext context = Pac4jUtils.getPac4jJ2EContext(request, response);
    final String accessToken = getAccessTokenFromRequest(request);
    if (StringUtils.isBlank(accessToken)) {
        LOGGER.error("Missing [{}] from the request", OAuth20Constants.ACCESS_TOKEN);
        return buildUnauthorizedResponseEntity(OAuth20Constants.MISSING_ACCESS_TOKEN);
    }
    final AccessToken accessTokenTicket = this.ticketRegistry.getTicket(accessToken, AccessToken.class);
    if (accessTokenTicket == null) {
        LOGGER.error("Access token [{}] cannot be found in the ticket registry.", accessToken);
        return buildUnauthorizedResponseEntity(OAuth20Constants.EXPIRED_ACCESS_TOKEN);
    }
    if (accessTokenTicket.isExpired()) {
        LOGGER.error("Access token [{}] has expired and will be removed from the ticket registry", accessToken);
        this.ticketRegistry.deleteTicket(accessToken);
        return buildUnauthorizedResponseEntity(OAuth20Constants.EXPIRED_ACCESS_TOKEN);
    }
    if (casProperties.getLogout().isRemoveDescendantTickets()) {
        final TicketGrantingTicket ticketGrantingTicket = accessTokenTicket.getTicketGrantingTicket();
        if (ticketGrantingTicket == null || ticketGrantingTicket.isExpired()) {
            LOGGER.error("Ticket granting ticket [{}] parenting access token [{}] has expired or is not found", ticketGrantingTicket, accessTokenTicket);
            this.ticketRegistry.deleteTicket(accessToken);
            return buildUnauthorizedResponseEntity(OAuth20Constants.EXPIRED_ACCESS_TOKEN);
        }
    }
    updateAccessTokenUsage(accessTokenTicket);
    final Map<String, Object> map = this.userProfileDataCreator.createFrom(accessTokenTicket, context);
    final String value = this.userProfileViewRenderer.render(map, accessTokenTicket);
    return new ResponseEntity<>(value, HttpStatus.OK);
}
Also used : ResponseEntity(org.springframework.http.ResponseEntity) AccessToken(org.apereo.cas.ticket.accesstoken.AccessToken) TicketGrantingTicket(org.apereo.cas.ticket.TicketGrantingTicket) J2EContext(org.pac4j.core.context.J2EContext) GetMapping(org.springframework.web.bind.annotation.GetMapping)

Aggregations

J2EContext (org.pac4j.core.context.J2EContext)32 RedirectAction (org.pac4j.core.redirect.RedirectAction)13 Test (org.junit.Test)11 WebContext (org.pac4j.core.context.WebContext)11 ProfileManager (org.pac4j.core.profile.ProfileManager)11 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)11 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)11 HttpServletRequest (javax.servlet.http.HttpServletRequest)6 HttpServletResponse (javax.servlet.http.HttpServletResponse)6 UnauthorizedServiceException (org.apereo.cas.services.UnauthorizedServiceException)6 OAuthRegisteredService (org.apereo.cas.support.oauth.services.OAuthRegisteredService)6 UserProfile (org.pac4j.core.profile.UserProfile)6 GetMapping (org.springframework.web.bind.annotation.GetMapping)6 Service (org.apereo.cas.authentication.principal.Service)5 Authentication (org.apereo.cas.authentication.Authentication)4 AccessToken (org.apereo.cas.ticket.accesstoken.AccessToken)4 TicketGrantingTicket (org.apereo.cas.ticket.TicketGrantingTicket)3 CentralAuthenticationService (org.apereo.cas.CentralAuthenticationService)2 AuthenticationResult (org.apereo.cas.authentication.AuthenticationResult)2 PrincipalException (org.apereo.cas.authentication.PrincipalException)2