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


Java OAuth2Exception类代码示例

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


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

示例1: obtainNewAccessTokenInternal

import org.springframework.security.oauth2.common.exceptions.OAuth2Exception; //导入依赖的package包/类
protected OAuth2AccessToken obtainNewAccessTokenInternal(OAuth2ProtectedResourceDetails details,
		AccessTokenRequest request) throws UserRedirectRequiredException, AccessDeniedException {

	if (request.isError()) {
		// there was an oauth error...
		throw OAuth2Exception.valueOf(request.toSingleValueMap());
	}

	for (AccessTokenProvider tokenProvider : chain) {
		if (tokenProvider.supportsResource(details)) {
			return tokenProvider.obtainAccessToken(details, request);
		}
	}

	throw new OAuth2AccessDeniedException("Unable to obtain a new access token for resource '" + details.getId()
			+ "'. The provider manager is not configured to support it.", details);
}
 
开发者ID:jungyang,项目名称:oauth-client-master,代码行数:18,代码来源:AccessTokenProviderChain.java

示例2: retrieveToken

import org.springframework.security.oauth2.common.exceptions.OAuth2Exception; //导入依赖的package包/类
protected OAuth2AccessToken retrieveToken(AccessTokenRequest request, OAuth2ProtectedResourceDetails resource,
		MultiValueMap<String, String> form, HttpHeaders headers) throws OAuth2AccessDeniedException {

	try {
		// Prepare headers and form before going into rest template call in case the URI is affected by the result
		authenticationHandler.authenticateTokenRequest(resource, form, headers);
		// Opportunity to customize form and headers
		tokenRequestEnhancer.enhance(request, resource, form, headers);

		return getRestTemplate().execute(getAccessTokenUri(resource, form), getHttpMethod(),
				getRequestCallback(resource, form, headers), getResponseExtractor(), form.toSingleValueMap());

	}
	catch (OAuth2Exception oe) {
		throw new OAuth2AccessDeniedException("Access token denied.", resource, oe);
	}
	catch (RestClientException rce) {
		throw new OAuth2AccessDeniedException("Error requesting access token.", resource, rce);
	}

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

示例3: attemptAuthentication

import org.springframework.security.oauth2.common.exceptions.OAuth2Exception; //导入依赖的package包/类
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
    throws AuthenticationException, IOException, ServletException {

    try {
        OAuth2AccessToken accessToken = restTemplate.getAccessToken();
        FacebookUser facebookUser = userIdentity.findOrCreateFrom(accessToken);

        repository.save(facebookUser);

        Authentication authentication = new UsernamePasswordAuthenticationToken(
                facebookUser, null, Arrays.asList(new SimpleGrantedAuthority("ROLE_USER")));
        publish(new AuthenticationSuccessEvent(authentication));
        return authentication;
    } catch (OAuth2Exception e) {
        BadCredentialsException error = new BadCredentialsException(
                "Cannot retrieve the access token", e);
        publish(new OAuth2AuthenticationFailureEvent(error));
        throw error;
    }
}
 
开发者ID:PacktPublishing,项目名称:OAuth-2.0-Cookbook,代码行数:21,代码来源:FacebookLoginFilter.java

示例4: attemptAuthentication

import org.springframework.security.oauth2.common.exceptions.OAuth2Exception; //导入依赖的package包/类
@Override
public Authentication attemptAuthentication(
    HttpServletRequest request, HttpServletResponse response)
    throws AuthenticationException, IOException, ServletException {

    try {
        OAuth2AccessToken accessToken = restTemplate.getAccessToken();

        Claims claims = Claims.createFrom(jsonMapper, accessToken);
        GoogleUser googleUser = userIdentity.findOrCreateFrom(claims);
        repository.save(googleUser);

        Authentication authentication = new UsernamePasswordAuthenticationToken(
            googleUser, null, googleUser.getAuthorities());
        publish(new AuthenticationSuccessEvent(authentication));
        return authentication;
    } catch (OAuth2Exception e) {
        BadCredentialsException error = new BadCredentialsException(
                "Cannot retrieve the access token", e);
        publish(new OAuth2AuthenticationFailureEvent(error));
        throw error;
    }
}
 
开发者ID:PacktPublishing,项目名称:OAuth-2.0-Cookbook,代码行数:24,代码来源:OpenIdConnectFilter.java

示例5: handleException

import org.springframework.security.oauth2.common.exceptions.OAuth2Exception; //导入依赖的package包/类
@ExceptionHandler(InvalidTokenException.class)
public ResponseEntity<OAuth2Exception> handleException(Exception e) throws Exception {
    logger.info("Handling error: " + e.getClass().getSimpleName() + ", " + e.getMessage());
    // This isn't an oauth resource, so we don't want to send an
    // unauthorized code here. The client has already authenticated
    // successfully with basic auth and should just
    // get back the invalid token error.
    @SuppressWarnings("serial")
    InvalidTokenException e400 = new InvalidTokenException(e.getMessage()) {
        @Override
        public int getHttpErrorCode() {
            return 400;
        }
    };
    return exceptionTranslator.translate(e400);
}
 
开发者ID:gravitee-io,项目名称:graviteeio-access-management,代码行数:17,代码来源:RevokeTokenEndpoint.java

示例6: configureHandlerExceptionResolvers

import org.springframework.security.oauth2.common.exceptions.OAuth2Exception; //导入依赖的package包/类
@Override
public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) {
	RestExceptionHandler handler = new RestExceptionHandler();
	handler.setOrder(Ordered.HIGHEST_PRECEDENCE + 1);

	RestErrorDefinition<Exception> authErrorDefinition = new RestErrorDefinition<>(HttpStatus.BAD_REQUEST,
			ErrorType.ACCESS_DENIED,
			new DefaultExceptionMessageBuilder()
	);
	Map<Class<? extends Throwable>, RestErrorDefinition> errorMappings = ImmutableMap.<Class<? extends Throwable>, RestErrorDefinition>builder()
			.put(OAuth2Exception.class, authErrorDefinition)
			.put(AuthenticationException.class, authErrorDefinition)
			.putAll(ExceptionMappings.DEFAULT_MAPPING)

			.build();

	DefaultErrorResolver defaultErrorResolver = new DefaultErrorResolver(errorMappings);
	handler.setErrorResolver(new ReportPortalExceptionResolver(defaultErrorResolver));
	handler.setMessageConverters(messageConverters.getConverters());
	exceptionResolvers.add(handler);
}
 
开发者ID:reportportal,项目名称:service-authorization,代码行数:22,代码来源:AuthServerApplication.java

示例7: login

import org.springframework.security.oauth2.common.exceptions.OAuth2Exception; //导入依赖的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

示例8: serialize

import org.springframework.security.oauth2.common.exceptions.OAuth2Exception; //导入依赖的package包/类
@Override
public void serialize(OAuth2Exception value, JsonGenerator jgen, SerializerProvider provider) throws IOException,
		JsonProcessingException {
       jgen.writeStartObject();
	jgen.writeStringField("code", value.getOAuth2ErrorCode());
	jgen.writeStringField("message", value.getMessage());
	jgen.writeBooleanField("success", false);
	jgen.writeBooleanField("error", true);
	if (value.getAdditionalInformation()!=null) {
		for (Entry<String, String> entry : value.getAdditionalInformation().entrySet()) {
			String key = entry.getKey();
			String add = entry.getValue();
			jgen.writeStringField(key, add);				
		}
	}
       jgen.writeEndObject();
}
 
开发者ID:wayshall,项目名称:onetwo,代码行数:18,代码来源:OAuth2ExceptionDataResultJsonSerializer.java

示例9: getUnsuccessfulRedirect

import org.springframework.security.oauth2.common.exceptions.OAuth2Exception; //导入依赖的package包/类
private String getUnsuccessfulRedirect(AuthorizationRequest authorizationRequest, OAuth2Exception failure, boolean fragment) {
    if (isNull(authorizationRequest) || isNull(authorizationRequest.getRedirectUri())) {
        // we have no redirect for the user. very sad.
        throw new UnapprovedClientAuthenticationException("Authorization failure, and no redirect URI.", failure);
    }

    Map<String, String> query = new LinkedHashMap<>();

    query.put("error", failure.getOAuth2ErrorCode());
    query.put("error_description", failure.getMessage());

    if (nonNull(authorizationRequest.getState())) {
        query.put("state", authorizationRequest.getState());
    }

    if (nonNull(failure.getAdditionalInformation())) {
        for (Map.Entry<String, String> additionalInfo : failure.getAdditionalInformation().entrySet()) {
            query.put(additionalInfo.getKey(), additionalInfo.getValue());
        }
    }

    return append(authorizationRequest.getRedirectUri(), query, fragment);
}
 
开发者ID:petrbouda,项目名称:joyrest,代码行数:24,代码来源:AuthorizationEndpoint.java

示例10: authenticate

import org.springframework.security.oauth2.common.exceptions.OAuth2Exception; //导入依赖的package包/类
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {

    String username = authentication.getPrincipal() != null ? authentication.getPrincipal().toString() : null;
    String password = authentication.getCredentials() != null ? authentication.getCredentials().toString() : null;
    try {
        // create an authentication request
        final User apiUser = this.userService.authenticate(username, password);
        final UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password, Arrays.<GrantedAuthority>asList(new SimpleGrantedAuthority("ROLE_USER")));
        token.setDetails(apiUser);
        return token;

    } catch (Exception e) {
        throw new OAuth2Exception(e.getMessage(), e);
    }
}
 
开发者ID:xxing1982,项目名称:EDU_SYZT,代码行数:17,代码来源:UserAuthenticationProvider.java

示例11: authenticate

import org.springframework.security.oauth2.common.exceptions.OAuth2Exception; //导入依赖的package包/类
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {

    String username = authentication.getPrincipal() != null ? authentication.getPrincipal().toString() : null;
    String password = authentication.getCredentials() != null ? authentication.getCredentials().toString() : null;
    try {
        // create an authentication request
        final ApiUser apiUser = this.userService.authenticate(username, password);
        final UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password, Arrays.<GrantedAuthority>asList(new SimpleGrantedAuthority("ROLE_USER")));
        token.setDetails(apiUser);
        return token;

    } catch (Exception e) {
        throw new OAuth2Exception(e.getMessage(), e);
    }
}
 
开发者ID:iainporter,项目名称:oauth2-provider,代码行数:17,代码来源:UserAuthenticationProvider.java

示例12: handleError

import org.springframework.security.oauth2.common.exceptions.OAuth2Exception; //导入依赖的package包/类
@SuppressWarnings("unchecked")
@Override
public void handleError(ClientHttpResponse response) throws IOException {
	for (HttpMessageConverter<?> converter : messageConverters) {
		if (converter.canRead(OAuth2Exception.class, response.getHeaders().getContentType())) {
			OAuth2Exception ex;
			try {
				ex = ((HttpMessageConverter<OAuth2Exception>) converter).read(OAuth2Exception.class, response);
			}
			catch (Exception e) {
				// ignore
				continue;
			}
			throw ex;
		}
	}
	super.handleError(response);
}
 
开发者ID:jungyang,项目名称:oauth-client-master,代码行数:19,代码来源:OAuth2AccessTokenSupport.java

示例13: enhanceResponse

import org.springframework.security.oauth2.common.exceptions.OAuth2Exception; //导入依赖的package包/类
@Override
protected ResponseEntity<OAuth2Exception> enhanceResponse(ResponseEntity<OAuth2Exception> response, Exception exception) {
	HttpHeaders headers = response.getHeaders();
	String existing = null;
	if (headers.containsKey("WWW-Authenticate")) {
		existing = extractTypePrefix(headers.getFirst("WWW-Authenticate"));
	}
	StringBuilder builder = new StringBuilder();
	builder.append(typeName+" ");
	builder.append("realm=\"" + realmName + "\"");
	if (existing!=null) {
		builder.append(", "+existing);
	}
	HttpHeaders update = new HttpHeaders();
	update.putAll(response.getHeaders());
	update.set("WWW-Authenticate", builder.toString());
	return new ResponseEntity<OAuth2Exception>(response.getBody(), update, response.getStatusCode());
}
 
开发者ID:jungyang,项目名称:oauth-client-master,代码行数:19,代码来源:OAuth2AuthenticationEntryPoint.java

示例14: translate

import org.springframework.security.oauth2.common.exceptions.OAuth2Exception; //导入依赖的package包/类
public ResponseEntity<OAuth2Exception> translate(Exception e) throws Exception {

		// Try to extract a SpringSecurityException from the stacktrace
		Throwable[] causeChain = throwableAnalyzer.determineCauseChain(e);
		RuntimeException ase = (OAuth2Exception) throwableAnalyzer.getFirstThrowableOfType(
				OAuth2Exception.class, causeChain);

		if (ase != null) {
			return handleOAuth2Exception((OAuth2Exception) ase);
		}

		ase = (AuthenticationException) throwableAnalyzer.getFirstThrowableOfType(AuthenticationException.class,
				causeChain);
		if (ase != null) {
			return handleOAuth2Exception(new UnauthorizedException(e.getMessage(), e));
		}

		ase = (AccessDeniedException) throwableAnalyzer
				.getFirstThrowableOfType(AccessDeniedException.class, causeChain);
		if (ase instanceof AccessDeniedException) {
			return handleOAuth2Exception(new ForbiddenException(ase.getMessage(), ase));
		}

		return handleOAuth2Exception(new ServerErrorException(e.getMessage(), e));

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

示例15: handleOAuth2Exception

import org.springframework.security.oauth2.common.exceptions.OAuth2Exception; //导入依赖的package包/类
private ResponseEntity<OAuth2Exception> handleOAuth2Exception(OAuth2Exception e) throws IOException {

		int status = e.getHttpErrorCode();
		HttpHeaders headers = new HttpHeaders();
		headers.set("Cache-Control", "no-store");
		headers.set("Pragma", "no-cache");
		if (status == HttpStatus.UNAUTHORIZED.value() || (e instanceof InsufficientScopeException)) {
			headers.set("WWW-Authenticate", String.format("%s %s", OAuth2AccessToken.BEARER_TYPE, e.getSummary()));
		}

		ResponseEntity<OAuth2Exception> response = new ResponseEntity<OAuth2Exception>(e, headers,
				HttpStatus.valueOf(status));

		return response;

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


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