当前位置: 首页>>代码示例>>Java>>正文


Java InvalidGrantException类代码示例

本文整理汇总了Java中org.springframework.security.oauth2.common.exceptions.InvalidGrantException的典型用法代码示例。如果您正苦于以下问题:Java InvalidGrantException类的具体用法?Java InvalidGrantException怎么用?Java InvalidGrantException使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


InvalidGrantException类属于org.springframework.security.oauth2.common.exceptions包,在下文中一共展示了InvalidGrantException类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: login

import org.springframework.security.oauth2.common.exceptions.InvalidGrantException; //导入依赖的package包/类
@GetMapping(value = "/v2/idp/login")
public ResponseEntity login(@RequestParam(value = "redirectUrl", required = false) String redirectUrl) {
    if (!idpConfig.getIdpEnabled()) {
        log.debug("IDP authentication is disabled. Property cuba.rest.idp.enabled is false");

        throw new InvalidGrantException("IDP is not supported");
    }

    if (redirectUrl == null) {
        redirectUrl = idpDefaultRedirectUrl;
    }

    if (redirectUrl == null) {
        log.debug("IDP defaultRedirectUrl is not set. Client did not provide redirectUrl parameter");

        return ResponseEntity
                .status(HttpStatus.BAD_REQUEST)
                .body(new OAuth2Exception("Client did not provide redirectUrl parameter"));
    }

    return ResponseEntity
            .status(HttpStatus.FOUND)
            .location(URI.create(getIdpLoginUrl(redirectUrl)))
            .build();
}
 
开发者ID:cuba-platform,项目名称:cuba,代码行数:26,代码来源:IdpAuthController.java

示例2: testConsumeRemovesCode

import org.springframework.security.oauth2.common.exceptions.InvalidGrantException; //导入依赖的package包/类
@Test
public void testConsumeRemovesCode() {
    OAuth2Request storedOAuth2Request = RequestTokenFactory.createOAuth2Request("id", false);
    OAuth2Authentication expectedAuthentication = new OAuth2Authentication(storedOAuth2Request,
            new TestAuthentication("test2", false));
    String code = getAuthorizationCodeServices().createAuthorizationCode(expectedAuthentication);
    assertNotNull(code);

    OAuth2Authentication actualAuthentication = getAuthorizationCodeServices().consumeAuthorizationCode(code);
    assertEquals(expectedAuthentication, actualAuthentication);

    try {
        getAuthorizationCodeServices().consumeAuthorizationCode(code);
        fail("Should have thrown exception");
    } catch (InvalidGrantException e) {
        // good we expected this
    }
}
 
开发者ID:cedac-software,项目名称:spring-security-mongodb,代码行数:19,代码来源:AuthorizationCodeServicesBaseTests.java

示例3: getOAuth2Authentication

import org.springframework.security.oauth2.common.exceptions.InvalidGrantException; //导入依赖的package包/类
@Override
protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {

	Map<String, String> parameters = tokenRequest.getRequestParameters();
	String username = parameters.get("username");
	String password = parameters.get("password");

	Authentication userAuth = new UsernamePasswordAuthenticationToken(username, password);
	try {
		userAuth = authenticationManager.authenticate(userAuth);
	}
	catch (AccountStatusException ase) {
		//covers expired, locked, disabled cases (mentioned in section 5.2, draft 31)
		throw new InvalidGrantException(ase.getMessage());
	}
	catch (BadCredentialsException e) {
		// If the username/password are wrong the spec says we should send 400/invlid grant
		throw new InvalidGrantException(e.getMessage());
	}
	if (userAuth == null || !userAuth.isAuthenticated()) {
		throw new InvalidGrantException("Could not authenticate user: " + username);
	}
	
	OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);		
	return new OAuth2Authentication(storedOAuth2Request, userAuth);
}
 
开发者ID:jungyang,项目名称:oauth-client-master,代码行数:27,代码来源:ResourceOwnerPasswordTokenGranter.java

示例4: resolveRedirect

import org.springframework.security.oauth2.common.exceptions.InvalidGrantException; //导入依赖的package包/类
public String resolveRedirect(String requestedRedirect, ClientDetails client) throws OAuth2Exception {

		Set<String> authorizedGrantTypes = client.getAuthorizedGrantTypes();
		if (authorizedGrantTypes.isEmpty()) {
			throw new InvalidGrantException("A client must have at least one authorized grant type.");
		}
		if (!containsRedirectGrantType(authorizedGrantTypes)) {
			throw new InvalidGrantException(
					"A redirect_uri can only be used by implicit or authorization_code grant types.");
		}

		Set<String> redirectUris = client.getRegisteredRedirectUri();

		if (redirectUris != null && !redirectUris.isEmpty()) {
			return obtainMatchingRedirect(redirectUris, requestedRedirect);
		}
		else if (StringUtils.hasText(requestedRedirect)) {
			return requestedRedirect;
		}
		else {
			throw new InvalidRequestException("A redirect_uri must be supplied.");
		}

	}
 
开发者ID:jungyang,项目名称:oauth-client-master,代码行数:25,代码来源:DefaultRedirectResolver.java

示例5: getOAuth2Authentication

import org.springframework.security.oauth2.common.exceptions.InvalidGrantException; //导入依赖的package包/类
@Override
protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {

    Map<String, String> parameters = tokenRequest.getRequestParameters();
    String authorizationCode = parameters.get("code");
    String redirectUri = parameters.get(OAuth2Utils.REDIRECT_URI);
    String codeVerifier = parameters.get("code_verifier");

    if (authorizationCode == null) {
        throw new InvalidRequestException("An authorization code must be supplied.");
    }

    OAuth2Authentication storedAuth = authorizationCodeServices.consumeAuthorizationCode(authorizationCode);
    if (storedAuth == null) {
        throw new InvalidGrantException("Invalid authorization code: " + authorizationCode);
    }

    OAuth2Request pendingOAuth2Request = storedAuth.getOAuth2Request();




    // Validates code verifier
    Map<String, String> pendingOauth2RequestParams = pendingOAuth2Request.getRequestParameters();
    String codeChallenge = pendingOauth2RequestParams.get("code_challenge");
    String codeChallengeMethod = pendingOauth2RequestParams.get("code_challenge_method");

    if (codeVerifier == null && codeChallenge != null) {
        // client is using PKCE but did not send the codeVerifier
        throw new InvalidRequestException(
                "Invalid authorization code for current token request.");
    }

    if (codeVerifier != null && codeChallenge != null) {
        String hashed = codeVerifier;
        if ("S256".equals(codeChallengeMethod)) {
            hashed = DigestUtils.sha256Hex(codeVerifier);
        }

        if (!hashed.equalsIgnoreCase(codeChallenge)) {
            throw new InvalidRequestException(
                    "Invalid authorization code for current token request.");
        }
    }



    // https://jira.springsource.org/browse/SECOAUTH-333
    // This might be null, if the authorization was done without the redirect_uri parameter
    String redirectUriApprovalParameter = pendingOAuth2Request.getRequestParameters().get(
            OAuth2Utils.REDIRECT_URI);

    if ((redirectUri != null || redirectUriApprovalParameter != null)
            && !pendingOAuth2Request.getRedirectUri().equals(redirectUri)) {
        throw new RedirectMismatchException("Redirect URI mismatch.");
    }

    String pendingClientId = pendingOAuth2Request.getClientId();
    String clientId = tokenRequest.getClientId();
    if (clientId != null && !clientId.equals(pendingClientId)) {
        // just a sanity check.
        throw new InvalidClientException("Client ID mismatch");
    }

    // Secret is not required in the authorization request, so it won't be available
    // in the pendingAuthorizationRequest. We do want to check that a secret is provided
    // in the token request, but that happens elsewhere.

    Map<String, String> combinedParameters = new HashMap<String, String>(pendingOAuth2Request
            .getRequestParameters());
    // Combine the parameters adding the new ones last so they override if there are any clashes
    combinedParameters.putAll(parameters);

    // Make a new stored request with the combined parameters
    OAuth2Request finalStoredOAuth2Request = pendingOAuth2Request.createOAuth2Request(combinedParameters);

    Authentication userAuth = storedAuth.getUserAuthentication();

    return new OAuth2Authentication(finalStoredOAuth2Request, userAuth);

}
 
开发者ID:PacktPublishing,项目名称:OAuth-2.0-Cookbook,代码行数:82,代码来源:CustomAuthCodeTokenGranter.java

示例6: checkIfTokenIsIssuedToClient

import org.springframework.security.oauth2.common.exceptions.InvalidGrantException; //导入依赖的package包/类
private void checkIfTokenIsIssuedToClient(final Authentication clientAuth,
                                          final OAuth2Authentication authToRevoke) {
    final String requestingClientId = clientAuth.getName();
    final String tokenClientId = authToRevoke.getOAuth2Request().getClientId();
    if (!requestingClientId.equals(tokenClientId)) {
        logger.debug("Revoke FAILED: requesting client = {}, token's client = {}.", requestingClientId, tokenClientId);
        throw new InvalidGrantException("Cannot revoke tokens issued to other clients.");
    }
    logger.debug("OK to revoke; token is issued to client \"{}\"", requestingClientId);
}
 
开发者ID:gravitee-io,项目名称:graviteeio-access-management,代码行数:11,代码来源:RevokeTokenEndpoint.java

示例7: shouldNotConsumeNonExistingCode

import org.springframework.security.oauth2.common.exceptions.InvalidGrantException; //导入依赖的package包/类
@Test(expected = InvalidGrantException.class)
public void shouldNotConsumeNonExistingCode() {
    // prepare OAuth2Authentication
    final String clientId = "test-client";
    when(oAuth2Request.getClientId()).thenReturn(clientId);
    when(oAuth2Authentication.getOAuth2Request()).thenReturn(oAuth2Request);

    // Run
    String code = authorizationCodeServices.createAuthorizationCode(RepositoryProviderUtils.convert(oAuth2Authentication));
    assertNotNull(code);
    when(authorizationCodeRepository.remove(code)).thenReturn(Optional.ofNullable(null));
    authorizationCodeServices.consumeAuthorizationCode(code);
}
 
开发者ID:gravitee-io,项目名称:graviteeio-access-management,代码行数:14,代码来源:RepositoryAuthorizationCodeServicesTest.java

示例8: checkIfTokenIsIssuedToClient

import org.springframework.security.oauth2.common.exceptions.InvalidGrantException; //导入依赖的package包/类
protected void checkIfTokenIsIssuedToClient(Authentication clientAuth,
                                            OAuth2Authentication authToRevoke) {
    String requestingClientId = clientAuth.getName();
    String tokenClientId = authToRevoke.getOAuth2Request().getClientId();
    if (!requestingClientId.equals(tokenClientId)) {
        log.debug("Revoke FAILED: requesting client = {}, token's client = {}", requestingClientId, tokenClientId);
        throw new InvalidGrantException("Cannot revoke tokens issued to other clients");
    }
}
 
开发者ID:cuba-platform,项目名称:cuba,代码行数:10,代码来源:OAuthTokenRevoker.java

示例9: postAccessToken

import org.springframework.security.oauth2.common.exceptions.InvalidGrantException; //导入依赖的package包/类
@PostMapping(value = "/v2/idp/token")
public ResponseEntity<OAuth2AccessToken> postAccessToken(Principal principal,
                                                         @RequestParam Map<String, String> parameters,
                                                         HttpServletRequest request)
        throws HttpRequestMethodNotSupportedException {

    if (!idpConfig.getIdpEnabled()) {
        log.debug("IDP authentication is disabled. Property cuba.rest.idp.enabled is false");

        throw new InvalidGrantException("IDP is not supported");
    }

    if (!(principal instanceof Authentication)) {
        throw new InsufficientAuthenticationException(
                "There is no client authentication. Try adding an appropriate authentication filter.");
    }

    // we cannot perform brute-force check here, since we don't know username

    String idpTicket = parameters.get("idp_ticket");
    String ipAddress = request.getRemoteAddr();

    OAuth2AccessTokenResult tokenResult =
            authenticate(idpTicket, request.getLocale(), ipAddress, parameters);

    return ResponseEntity.ok(tokenResult.getAccessToken());
}
 
开发者ID:cuba-platform,项目名称:cuba,代码行数:28,代码来源:IdpAuthController.java

示例10: status

import org.springframework.security.oauth2.common.exceptions.InvalidGrantException; //导入依赖的package包/类
@GetMapping(value = "/v2/idp/status")
public ResponseEntity status() {
    if (!idpConfig.getIdpEnabled()) {
        log.debug("IDP authentication is disabled. Property cuba.rest.idp.enabled is false");

        throw new InvalidGrantException("IDP is not supported");
    }

    return ResponseEntity
            .status(HttpStatus.FOUND)
            .location(URI.create(getIdpStatusUrl()))
            .build();
}
 
开发者ID:cuba-platform,项目名称:cuba,代码行数:14,代码来源:IdpAuthController.java

示例11: postAccessToken

import org.springframework.security.oauth2.common.exceptions.InvalidGrantException; //导入依赖的package包/类
@RequestMapping(value = "/v2/ldap/token", method = RequestMethod.POST)
public ResponseEntity<OAuth2AccessToken> postAccessToken(Principal principal,
                                                         @RequestParam Map<String, String> parameters,
                                                         HttpServletRequest request)
        throws HttpRequestMethodNotSupportedException {

    if (!ldapConfig.getLdapEnabled()) {
        log.debug("LDAP authentication is disabled. Property cuba.rest.ldap.enabled is false");

        throw new InvalidGrantException("LDAP is not supported");
    }

    if (!(principal instanceof Authentication)) {
        throw new InsufficientAuthenticationException(
                "There is no client authentication. Try adding an appropriate authentication filter.");
    }

    String grantType = parameters.get(OAuth2Utils.GRANT_TYPE);
    if (!"password".equals(grantType)) {
        throw new InvalidGrantException("grant type not supported for ldap/token endpoint");
    }

    String username = parameters.get("username");

    if (restApiConfig.getStandardAuthenticationUsers().contains(username)) {
        log.info("User {} is not allowed to use external login in REST API", username);
        throw new BadCredentialsException("Bad credentials");
    }

    String ipAddress = request.getRemoteAddr();

    String password = parameters.get("password");

    OAuth2AccessTokenResult tokenResult =
            authenticate(username, password, request.getLocale(), ipAddress, parameters);

    return ResponseEntity.ok(tokenResult.getAccessToken());
}
 
开发者ID:cuba-platform,项目名称:cuba,代码行数:39,代码来源:LdapAuthController.java

示例12: testConsumeNonExistingCode

import org.springframework.security.oauth2.common.exceptions.InvalidGrantException; //导入依赖的package包/类
@Test
public void testConsumeNonExistingCode() {
    try {
        getAuthorizationCodeServices().consumeAuthorizationCode("doesnt exist");
        fail("Should have thrown exception");
    } catch (InvalidGrantException e) {
        // good we expected this
    }
}
 
开发者ID:cedac-software,项目名称:spring-security-mongodb,代码行数:10,代码来源:AuthorizationCodeServicesBaseTests.java

示例13: refreshAccessToken

import org.springframework.security.oauth2.common.exceptions.InvalidGrantException; //导入依赖的package包/类
public OAuth2AccessToken refreshAccessToken(String refreshTokenValue, TokenRequest request)
		throws AuthenticationException {

	if (!supportRefreshToken) {
		throw new InvalidGrantException("Invalid refresh token: " + refreshTokenValue);
	}

	OAuth2Authentication authentication = loadAuthentication(refreshTokenValue);
	String clientId = authentication.getOAuth2Request().getClientId();
	if (clientId == null || !clientId.equals(request.getClientId())) {
		throw new InvalidGrantException("Wrong client for this refresh token: " + refreshTokenValue);
	}

	OAuth2AccessToken refreshTokenData = readAccessToken(refreshTokenValue);
	if (isExpired(refreshTokenData)) {
		throw new InvalidTokenException("Invalid refresh token (expired): " + refreshTokenValue);
	}

	authentication = createRefreshedAuthentication(authentication, request.getScope());

	OAuth2AccessToken accessToken = createAccessToken(authentication);
	if (!reuseRefreshToken) {
		OAuth2RefreshToken refreshToken = createRefreshToken(authentication);
		DefaultOAuth2AccessToken result = new DefaultOAuth2AccessToken(accessToken);
		result.setRefreshToken(refreshToken);
	}

	return accessToken;
}
 
开发者ID:jungyang,项目名称:oauth-client-master,代码行数:30,代码来源:JwtTokenServices.java

示例14: consumeAuthorizationCode

import org.springframework.security.oauth2.common.exceptions.InvalidGrantException; //导入依赖的package包/类
public OAuth2Authentication consumeAuthorizationCode(String code)
		throws InvalidGrantException {
	OAuth2Authentication auth = this.remove(code);
	if (auth == null) {
		throw new InvalidGrantException("Invalid authorization code: " + code);
	}
	return auth;
}
 
开发者ID:jungyang,项目名称:oauth-client-master,代码行数:9,代码来源:RandomValueAuthorizationCodeServices.java

示例15: writeInvalidGrant

import org.springframework.security.oauth2.common.exceptions.InvalidGrantException; //导入依赖的package包/类
@Test
public void writeInvalidGrant() throws Exception {
	OAuth2Exception oauthException = new InvalidGrantException(DETAILS);
	String expected = createResponse(oauthException.getOAuth2ErrorCode());
	converter.write(oauthException, contentType, outputMessage);
	assertEquals(expected, getOutput());
}
 
开发者ID:jungyang,项目名称:oauth-client-master,代码行数:8,代码来源:JaxbOAuth2ExceptionMessageConverterTests.java


注:本文中的org.springframework.security.oauth2.common.exceptions.InvalidGrantException类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。