Search in sources :

Example 1 with Approval

use of org.maxkey.authz.oauth2.provider.approval.Approval in project tutorials-java by Artister.

the class ConfirmAccessController method getAccessConfirmation.

@RequestMapping("/oauth/confirm_access")
public String getAccessConfirmation(Map<String, Object> model, Principal principal) {
    AuthorizationRequest clientAuth = (AuthorizationRequest) model.remove("authorizationRequest");
    ClientDetails client = clientDetailsService.loadClientByClientId(clientAuth.getClientId());
    model.put("auth_request", clientAuth);
    model.put("client", client);
    Map<String, String> scopes = new LinkedHashMap<String, String>();
    for (String scope : clientAuth.getScope()) {
        scopes.put(OAuth2Utils.SCOPE_PREFIX + scope, "false");
    }
    for (Approval approval : approvalStore.getApprovals(principal.getName(), client.getClientId())) {
        if (clientAuth.getScope().contains(approval.getScope())) {
            scopes.put(OAuth2Utils.SCOPE_PREFIX + approval.getScope(), approval.getStatus() == Approval.ApprovalStatus.APPROVED ? "true" : "false");
        }
    }
    model.put("scopes", scopes);
    return "access_confirmation";
}
Also used : AuthorizationRequest(org.springframework.security.oauth2.provider.AuthorizationRequest) ClientDetails(org.springframework.security.oauth2.provider.ClientDetails) Approval(org.springframework.security.oauth2.provider.approval.Approval) LinkedHashMap(java.util.LinkedHashMap) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 2 with Approval

use of org.maxkey.authz.oauth2.provider.approval.Approval in project theskeleton by codenergic.

the class UserOauth2ClientApprovalStoreTest method testRevokeApprovals.

@Test
public void testRevokeApprovals() {
    assertThatThrownBy(() -> {
        approvalStore.revokeApprovals(null);
    }).isInstanceOf(NullPointerException.class);
    when(approvalRepository.findByUserUsernameAndClientIdAndScope(anyString(), anyString(), eq("read"))).thenReturn(new UserOAuth2ClientApprovalEntity().setUser(new UserEntity().setId("1")).setClient(new OAuth2ClientEntity().setId("2")).setScope("read").setApprovalStatus(ApprovalStatus.APPROVED));
    when(approvalRepository.findByUserUsernameAndClientIdAndScope(anyString(), anyString(), eq("write"))).thenReturn(null);
    List<Approval> approvals = new ArrayList<>();
    approvals.add(new Approval("", "", "write", new Date(), ApprovalStatus.APPROVED));
    for (int i = 0; i < 3; i++) {
        approvals.add(new Approval("", "", "read", new Date(), ApprovalStatus.APPROVED));
    }
    approvalStore.revokeApprovals(approvals);
    verify(approvalRepository, times(1)).findByUserUsernameAndClientIdAndScope(anyString(), anyString(), eq("write"));
    verify(approvalRepository, times(3)).findByUserUsernameAndClientIdAndScope(anyString(), anyString(), eq("read"));
    verify(approvalRepository, times(3)).delete(any(UserOAuth2ClientApprovalEntity.class));
}
Also used : OAuth2ClientEntity(org.codenergic.theskeleton.client.OAuth2ClientEntity) ArrayList(java.util.ArrayList) Approval(org.springframework.security.oauth2.provider.approval.Approval) Date(java.util.Date) Test(org.junit.Test)

Example 3 with Approval

use of org.maxkey.authz.oauth2.provider.approval.Approval in project theskeleton by codenergic.

the class UserOauth2ClientApprovalStoreTest method testGetApprovals.

@Test
@SuppressWarnings("serial")
public void testGetApprovals() {
    when(approvalRepository.findByUserUsernameAndClientId(anyString(), anyString())).thenReturn(Arrays.asList(new UserOAuth2ClientApprovalEntity() {

        {
            setCreatedDate(new Date());
        }
    }.setApprovalStatus(ApprovalStatus.APPROVED).setUser(new UserEntity()).setClient(new OAuth2ClientEntity()), new UserOAuth2ClientApprovalEntity() {

        {
            setCreatedDate(new Date());
        }
    }.setApprovalStatus(ApprovalStatus.DENIED).setUser(new UserEntity()).setClient(new OAuth2ClientEntity())));
    List<Approval> approvals = new ArrayList<>(approvalStore.getApprovals("1", "2"));
    assertThat(approvals.size()).isEqualTo(2);
    assertThat(approvals.get(0).getStatus()).isEqualTo(ApprovalStatus.APPROVED);
    assertThat(approvals.get(1).getStatus()).isEqualTo(ApprovalStatus.DENIED);
    verify(approvalRepository).findByUserUsernameAndClientId(anyString(), anyString());
}
Also used : OAuth2ClientEntity(org.codenergic.theskeleton.client.OAuth2ClientEntity) ArrayList(java.util.ArrayList) Approval(org.springframework.security.oauth2.provider.approval.Approval) Date(java.util.Date) Test(org.junit.Test)

Example 4 with Approval

use of org.maxkey.authz.oauth2.provider.approval.Approval in project MaxKey by dromara.

the class AuthorizationEndpoint method authorize.

@Operation(summary = "OAuth 2.0 认证接口", description = "传递参数client_id,response_type,redirect_uri等", method = "GET")
@RequestMapping(value = { OAuth2Constants.ENDPOINT.ENDPOINT_AUTHORIZE, OAuth2Constants.ENDPOINT.ENDPOINT_TENCENT_IOA_AUTHORIZE }, method = RequestMethod.GET)
public ModelAndView authorize(Map<String, Object> model, @RequestParam Map<String, String> parameters, SessionStatus sessionStatus) {
    Principal principal = (Principal) WebContext.getAuthentication();
    // 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(OAuth2Constants.PARAMETER.TOKEN) && !responseTypes.contains(OAuth2Constants.PARAMETER.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(), true);
        // 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(OAuth2Constants.PARAMETER.REDIRECT_URI);
        String resolvedRedirect = redirectResolver.resolveRedirect(redirectUriParameter, client);
        if (!StringUtils.hasText(resolvedRedirect)) {
            logger.info("Client redirectUri " + resolvedRedirect);
            logger.info("Parameter redirectUri " + redirectUriParameter);
            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);
        // 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(OAuth2Constants.PARAMETER.TOKEN)) {
                return getImplicitGrantResponse(authorizationRequest);
            }
            if (responseTypes.contains(OAuth2Constants.PARAMETER.CODE)) {
                return new ModelAndView(getAuthorizationCodeResponse(authorizationRequest, (Authentication) principal));
            }
        }
        Apps app = (Apps) WebContext.getAttribute(WebConstants.AUTHORIZE_SIGN_ON_APP);
        // session中为空或者id不一致重新加载
        if (app == null || !app.getId().equalsIgnoreCase(authorizationRequest.getClientId())) {
            app = appsService.get(authorizationRequest.getClientId());
            WebContext.setAttribute(WebConstants.AUTHORIZE_SIGN_ON_APP, app);
        }
        // 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;
    }
}
Also used : AuthorizationRequest(org.maxkey.authz.oauth2.provider.AuthorizationRequest) ModelAndView(org.springframework.web.servlet.ModelAndView) InsufficientAuthenticationException(org.springframework.security.authentication.InsufficientAuthenticationException) Apps(org.maxkey.entity.apps.Apps) ClientDetails(org.maxkey.entity.apps.oauth2.provider.ClientDetails) Authentication(org.springframework.security.core.Authentication) OAuth2Authentication(org.maxkey.authz.oauth2.provider.OAuth2Authentication) InvalidClientException(org.maxkey.authz.oauth2.common.exceptions.InvalidClientException) RedirectMismatchException(org.maxkey.authz.oauth2.common.exceptions.RedirectMismatchException) UnsupportedResponseTypeException(org.maxkey.authz.oauth2.common.exceptions.UnsupportedResponseTypeException) Principal(java.security.Principal) Operation(io.swagger.v3.oas.annotations.Operation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 5 with Approval

use of org.maxkey.authz.oauth2.provider.approval.Approval in project MaxKey by dromara.

the class JwtTokenStore method remove.

private void remove(String token) {
    if (approvalStore != null) {
        OAuth2Authentication auth = readAuthentication(token);
        String clientId = auth.getOAuth2Request().getClientId();
        Authentication user = auth.getUserAuthentication();
        if (user != null) {
            Collection<Approval> approvals = new ArrayList<Approval>();
            for (String scope : auth.getOAuth2Request().getScope()) {
                approvals.add(new Approval(user.getName(), clientId, scope, new Date(), ApprovalStatus.APPROVED));
            }
            approvalStore.revokeApprovals(approvals);
        }
    }
}
Also used : OAuth2Authentication(org.maxkey.authz.oauth2.provider.OAuth2Authentication) Authentication(org.springframework.security.core.Authentication) OAuth2Authentication(org.maxkey.authz.oauth2.provider.OAuth2Authentication) ArrayList(java.util.ArrayList) Approval(org.maxkey.authz.oauth2.provider.approval.Approval) Date(java.util.Date)

Aggregations

Approval (org.springframework.security.oauth2.provider.approval.Approval)15 Date (java.util.Date)11 OAuth2Authentication (org.maxkey.authz.oauth2.provider.OAuth2Authentication)8 Test (org.junit.Test)7 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)6 OAuth2AccessToken (org.maxkey.authz.oauth2.common.OAuth2AccessToken)5 ClientDetails (org.maxkey.entity.apps.oauth2.provider.ClientDetails)5 Authentication (org.springframework.security.core.Authentication)5 ArrayList (java.util.ArrayList)4 LinkedHashMap (java.util.LinkedHashMap)4 Approval (org.maxkey.authz.oauth2.provider.approval.Approval)4 ModelAndView (org.springframework.web.servlet.ModelAndView)4 HashSet (java.util.HashSet)3 OAuth2ClientEntity (org.codenergic.theskeleton.client.OAuth2ClientEntity)3 AuthorizationRequest (org.maxkey.authz.oauth2.provider.AuthorizationRequest)3 ClientRegistrationException (org.maxkey.authz.oauth2.provider.ClientRegistrationException)3 DefaultOAuth2RefreshToken (org.springframework.security.oauth2.common.DefaultOAuth2RefreshToken)3 AuthorizationRequest (org.springframework.security.oauth2.provider.AuthorizationRequest)3 ClientDetails (org.springframework.security.oauth2.provider.ClientDetails)3 Principal (java.security.Principal)2