本文整理汇总了Java中org.springframework.security.oauth2.common.exceptions.InvalidRequestException类的典型用法代码示例。如果您正苦于以下问题:Java InvalidRequestException类的具体用法?Java InvalidRequestException怎么用?Java InvalidRequestException使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
InvalidRequestException类属于org.springframework.security.oauth2.common.exceptions包,在下文中一共展示了InvalidRequestException类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Java代码示例。
示例1: getFrom
import org.springframework.security.oauth2.common.exceptions.InvalidRequestException; //导入依赖的package包/类
public AuthenticatedPerson getFrom(Person person) {
Optional<User> userOptional = userService.findByPersonalCode(person.getPersonalCode());
User user = userOptional.orElseGet(() -> createUser(person));
if (!user.getActive()) {
log.info("Failed to login inactive user with personal code {}", person.getPersonalCode());
throw new InvalidRequestException("INACTIVE_USER");
}
return AuthenticatedPerson.builder()
.firstName(person.getFirstName())
.lastName(person.getLastName())
.personalCode(person.getPersonalCode())
.userId(user.getId())
.build();
}
开发者ID:TulevaEE,项目名称:onboarding-service,代码行数:20,代码来源:PrincipalService.java
示例2: resolveRedirect
import org.springframework.security.oauth2.common.exceptions.InvalidRequestException; //导入依赖的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
示例3: getOAuth2Authentication
import org.springframework.security.oauth2.common.exceptions.InvalidRequestException; //导入依赖的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
示例4: getParametersForTokenRequest
import org.springframework.security.oauth2.common.exceptions.InvalidRequestException; //导入依赖的package包/类
private MultiValueMap<String, String> getParametersForTokenRequest(AuthorizationCodeResourceDetails resource, AccessTokenRequest request) {
MultiValueMap<String, String> form = new LinkedMultiValueMap();
String state = request.getStateKey();
// if (state.contains("session")) {
// form.set("appid", resource.getClientId());
// form.set("secret", resource.getClientSecret());
// } else {
// form.set("appid", "wx38871ac04c8208af");
// form.set("secret", "50f7e835165d91006bf32fb3ba8d53dd");
// }
form.set("appid", resource.getClientId());
form.set("secret", resource.getClientSecret());
form.set("code", request.getAuthorizationCode());
form.set("grant_type", "authorization_code");
Object preservedState = request.getPreservedState();
//if((request.getStateKey() != null || this.stateMandatory) && preservedState == null) {
if(false) {
throw new InvalidRequestException("Possible CSRF detected - state parameter was required but no state could be found");
} else {
String redirectUri = null;
if(preservedState instanceof String) {
redirectUri = String.valueOf(preservedState);
} else {
redirectUri = resource.getRedirectUri(request);
}
if(redirectUri != null && !"NONE".equals(redirectUri)) {
form.set("redirect_uri", redirectUri);
}
return form;
}
}
开发者ID:luotuo,项目名称:springboot-security-wechat,代码行数:34,代码来源:MyAuthorizationCodeAccessTokenProvider.java
示例5: getParametersForAuthorizeRequest
import org.springframework.security.oauth2.common.exceptions.InvalidRequestException; //导入依赖的package包/类
private MultiValueMap<String, String> getParametersForAuthorizeRequest(AuthorizationCodeResourceDetails resource, AccessTokenRequest request) {
MultiValueMap<String, String> form = new LinkedMultiValueMap();
form.set("response_type", "code");
form.set("client_id", resource.getClientId());
if(request.get("scope") != null) {
form.set("scope", request.getFirst("scope"));
} else {
form.set("scope", OAuth2Utils.formatParameterList(resource.getScope()));
}
String redirectUri = resource.getPreEstablishedRedirectUri();
Object preservedState = request.getPreservedState();
if(redirectUri == null && preservedState != null) {
redirectUri = String.valueOf(preservedState);
} else {
redirectUri = request.getCurrentUri();
}
String stateKey = request.getStateKey();
if(stateKey != null) {
form.set("state", stateKey);
if(preservedState == null) {
throw new InvalidRequestException("Possible CSRF detected - state parameter was present but no state could be found");
}
}
if(redirectUri != null) {
form.set("redirect_uri", redirectUri);
}
return form;
}
开发者ID:luotuo,项目名称:springboot-security-wechat,代码行数:33,代码来源:MyAuthorizationCodeAccessTokenProvider.java
示例6: appendAccessToken
import org.springframework.security.oauth2.common.exceptions.InvalidRequestException; //导入依赖的package包/类
private String appendAccessToken(AuthorizationRequest authorizationRequest, OAuth2AccessToken accessToken) {
Map<String, Object> vars = new LinkedHashMap<>();
Map<String, String> keys = new HashMap<>();
if (isNull(accessToken)) {
throw new InvalidRequestException("An implicit grant could not be made");
}
vars.put("access_token", accessToken.getValue());
vars.put("token_type", accessToken.getTokenType());
String state = authorizationRequest.getState();
if (nonNull(state)) {
vars.put("state", state);
}
Date expiration = accessToken.getExpiration();
if (nonNull(expiration)) {
long expires_in = (expiration.getTime() - System.currentTimeMillis()) / 1000;
vars.put("expires_in", expires_in);
}
String originalScope = authorizationRequest.getRequestParameters().get(OAuth2Utils.SCOPE);
if (isNull(originalScope) || !OAuth2Utils.parseParameterList(originalScope).equals(accessToken.getScope())) {
vars.put("scope", OAuth2Utils.formatParameterList(accessToken.getScope()));
}
Map<String, Object> additionalInformation = accessToken.getAdditionalInformation();
for (String key : additionalInformation.keySet()) {
Object value = additionalInformation.get(key);
if (nonNull(value)) {
keys.put("extra_" + key, key);
vars.put("extra_" + key, value);
}
}
// Do not include the refresh token (even if there is one)
return append(authorizationRequest.getRedirectUri(), vars, keys, true);
}
开发者ID:petrbouda,项目名称:joyrest,代码行数:40,代码来源:AuthorizationEndpoint.java
示例7: getParametersForTokenRequest
import org.springframework.security.oauth2.common.exceptions.InvalidRequestException; //导入依赖的package包/类
private MultiValueMap<String, String> getParametersForTokenRequest(AuthorizationCodeResourceDetails resource,
AccessTokenRequest request) {
MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
form.set("grant_type", "authorization_code");
form.set("code", request.getAuthorizationCode());
form.set("response_type", "id_token");
Object preservedState = request.getPreservedState();
if (request.getStateKey() != null || stateMandatory) {
// The token endpoint has no use for the state so we don't send it back, but we are using it
// for CSRF detection client side...
if (preservedState == null) {
throw new InvalidRequestException(
"Possible CSRF detected - state parameter was required but no state could be found");
}
}
// Extracting the redirect URI from a saved request should ignore the current URI, so it's not simply a call to
// resource.getRedirectUri()
String redirectUri = null;
// Get the redirect uri from the stored state
if (preservedState instanceof String) {
// Use the preserved state in preference if it is there
// TODO: treat redirect URI as a special kind of state (this is a historical mini hack)
redirectUri = String.valueOf(preservedState);
}
else {
redirectUri = resource.getRedirectUri(request);
}
if (redirectUri != null && !"NONE".equals(redirectUri)) {
form.set("redirect_uri", redirectUri);
}
return form;
}
开发者ID:pivotal-cf,项目名称:identity-sample-apps,代码行数:39,代码来源:OpenIDTokenProvider.java
示例8: getParametersForTokenRequest
import org.springframework.security.oauth2.common.exceptions.InvalidRequestException; //导入依赖的package包/类
private MultiValueMap<String, String> getParametersForTokenRequest(AuthorizationCodeResourceDetails resource,
AccessTokenRequest request) {
MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
form.set("grant_type", "authorization_code");
form.set("code", request.getAuthorizationCode());
Object preservedState = request.getPreservedState();
if (request.getStateKey() != null) {
// The token endpoint has no use for the state so we don't send it back, but we are using it
// for CSRF detection client side...
if (preservedState == null) {
throw new InvalidRequestException(
"Possible CSRF detected - state parameter was present but no state could be found");
}
}
// Extracting the redirect URI from a saved request should ignore the current URI, so it's not simply a call to
// resource.getRedirectUri()
String redirectUri = null;
// Get the redirect uri from the stored state
if (preservedState instanceof String) {
// Use the preserved state in preference if it is there
// TODO: treat redirect URI as a special kind of state (this is a historical mini hack)
redirectUri = String.valueOf(preservedState);
} else {
redirectUri = resource.getRedirectUri(request);
}
if (redirectUri != null && !"NONE".equals(redirectUri)) {
form.set("redirect_uri", redirectUri);
}
return form;
}
开发者ID:jungyang,项目名称:oauth-client-master,代码行数:37,代码来源:AuthorizationCodeAccessTokenProvider.java
示例9: writeInvalidRequest
import org.springframework.security.oauth2.common.exceptions.InvalidRequestException; //导入依赖的package包/类
@Test
public void writeInvalidRequest() throws Exception {
OAuth2Exception oauthException = new InvalidRequestException(DETAILS);
String expected = createResponse(oauthException.getOAuth2ErrorCode());
converter.write(oauthException, contentType, outputMessage);
assertEquals(expected, getOutput());
}
开发者ID:jungyang,项目名称:oauth-client-master,代码行数:8,代码来源:JaxbOAuth2ExceptionMessageConverterTests.java
示例10: readInvalidRequest
import org.springframework.security.oauth2.common.exceptions.InvalidRequestException; //导入依赖的package包/类
@Test
public void readInvalidRequest() throws Exception {
String accessToken = createResponse(OAuth2Exception.INVALID_REQUEST);
when(inputMessage.getBody()).thenReturn(createInputStream(accessToken));
@SuppressWarnings("unused")
InvalidRequestException result = (InvalidRequestException) converter.read(OAuth2Exception.class, inputMessage);
}
开发者ID:jungyang,项目名称:oauth-client-master,代码行数:8,代码来源:JaxbOAuth2ExceptionMessageConverterTests.java
示例11: testApproveOrDenyWithOAuth2RequestWithoutRedirectUri
import org.springframework.security.oauth2.common.exceptions.InvalidRequestException; //导入依赖的package包/类
/**
* Ensure that if the approval endpoint is called without a resolved redirect URI, the request fails.
* @throws Exception
*/
@Test(expected = InvalidRequestException.class)
public void testApproveOrDenyWithOAuth2RequestWithoutRedirectUri() throws Exception {
AuthorizationRequest request = getAuthorizationRequest("foo", null, null, null, Collections.singleton("code"));
request.setApproved(true);
Map<String, String> approvalParameters = new HashMap<String, String>();
approvalParameters.put("user_oauth_approval", "true");
model.put("authorizationRequest", request);
endpoint.approveOrDeny(approvalParameters, model, sessionStatus, principal);
}
开发者ID:jungyang,项目名称:oauth-client-master,代码行数:15,代码来源:AuthorizationEndpointTests.java
示例12: readValueInvalidRequest
import org.springframework.security.oauth2.common.exceptions.InvalidRequestException; //导入依赖的package包/类
@Test
public void readValueInvalidRequest() throws Exception {
String accessToken = createResponse(OAuth2Exception.INVALID_REQUEST);
InvalidRequestException result = (InvalidRequestException) mapper.readValue(accessToken, OAuth2Exception.class);
assertEquals(DETAILS,result.getMessage());
assertEquals(null,result.getAdditionalInformation());
}
开发者ID:jungyang,项目名称:oauth-client-master,代码行数:8,代码来源:OAuth2ExceptionDeserializerTests.java
示例13: getAccessToken
import org.springframework.security.oauth2.common.exceptions.InvalidRequestException; //导入依赖的package包/类
@Override
protected OAuth2AccessToken getAccessToken(ClientDetails client, TokenRequest tokenRequest) {
// grant_type validated in AbstractTokenGranter
final String clientId = client.getClientId();
if (clientId == null) {
log.error("Failed to authenticate client {}", clientId);
throw new InvalidRequestException("Unknown Client ID.");
}
Optional<MobileIDSession> session = genericSessionStore.get(MobileIDSession.class);
if (!session.isPresent()) {
return null;
}
MobileIDSession mobileIdSession = session.get();
boolean isComplete = mobileIdAuthService.isLoginComplete(mobileIdSession);
if (!isComplete) {
throw new MobileIdAuthNotCompleteException();
}
AuthenticatedPerson authenticatedPerson = principalService.getFrom(new Person() {
@Override
public String getPersonalCode() {
return mobileIdSession.personalCode;
}
@Override
public String getFirstName() {
return mobileIdSession.firstName;
}
@Override
public String getLastName() {
return mobileIdSession.lastName;
}
});
Authentication userAuthentication =
new PersonalCodeAuthentication<>(
authenticatedPerson,
mobileIdSession,
grantedAuthorityFactory.from(authenticatedPerson)
);
userAuthentication.setAuthenticated(true);
final OAuth2Request oAuth2Request = tokenRequest.createOAuth2Request(client);
final OAuth2Authentication oAuth2Authentication = new OAuth2Authentication(oAuth2Request,
userAuthentication
);
beforeTokenGrantedEventPublisher.publish(oAuth2Authentication);
return getTokenServices().createAccessToken(oAuth2Authentication);
}
开发者ID:TulevaEE,项目名称:onboarding-service,代码行数:56,代码来源:MobileIdTokenGranter.java
示例14: getAccessToken
import org.springframework.security.oauth2.common.exceptions.InvalidRequestException; //导入依赖的package包/类
@Override
protected OAuth2AccessToken getAccessToken(ClientDetails client, TokenRequest tokenRequest) {
final String clientId = client.getClientId();
if (clientId == null) {
throw new InvalidRequestException("Unknown Client ID.");
}
Optional<IdCardSession> session = sessionStore.get(IdCardSession.class);
if (!session.isPresent()) {
return null;
}
IdCardSession idCardSession = session.get();
AuthenticatedPerson authenticatedPerson = principalService.getFrom(new Person() {
@Override
public String getPersonalCode() {
return idCardSession.getPersonalCode();
}
@Override
public String getFirstName() {
return idCardSession.getFirstName();
}
@Override
public String getLastName() {
return idCardSession.getLastName();
}
});
Authentication userAuthentication = new PersonalCodeAuthentication<>(
authenticatedPerson,
idCardSession,
grantedAuthorityFactory.from(authenticatedPerson));
userAuthentication.setAuthenticated(true);
OAuth2Request oAuth2Request = tokenRequest.createOAuth2Request(client);
OAuth2Authentication oAuth2Authentication = new OAuth2Authentication(oAuth2Request, userAuthentication);
beforeTokenGrantedEventPublisher.publish(oAuth2Authentication);
return getTokenServices().createAccessToken(oAuth2Authentication);
}
开发者ID:TulevaEE,项目名称:onboarding-service,代码行数:44,代码来源:IdCardTokenGranter.java
示例15: getOAuth2Authentication
import org.springframework.security.oauth2.common.exceptions.InvalidRequestException; //导入依赖的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);
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();
// 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 (redirectUriApprovalParameter != null && redirectUri == null
|| redirectUriApprovalParameter != null
&& !pendingOAuth2Request.getRedirectUri().startsWith(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<>(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:osiam,项目名称:auth-server,代码行数:50,代码来源:LessStrictRedirectUriAuthorizationCodeTokenGranter.java
示例16: configure
import org.springframework.security.oauth2.common.exceptions.InvalidRequestException; //导入依赖的package包/类
@Override
protected void configure() {
setControllerPath("oauth");
post("token", (req, resp) -> {
Authentication principal = basicAuthenticator.authenticate(req);
String clientId = getClientId(principal);
ClientDetails authenticatedClient = clientDetailsService.loadClientByClientId(clientId);
Map<String, String> parameters = MapUtils.createOneDimMap(req.getQueryParams());
TokenRequest tokenRequest = requestFactory.createTokenRequest(parameters, authenticatedClient);
// Only validate the client details if a client authenticated during this request.
if (!isEmpty(clientId) && !clientId.equals(tokenRequest.getClientId())) {
throw new InvalidClientException("Given client ID does not match authenticated client");
}
if (nonNull(authenticatedClient)) {
requestValidator.validateScope(tokenRequest, authenticatedClient);
}
if (!isEmpty(tokenRequest.getGrantType())) {
throw new InvalidRequestException("Missing grant type");
}
if (tokenRequest.getGrantType().equals("implicit")) {
throw new InvalidGrantException("Implicit grant type not supported from token endpoint");
}
// The scope was requested or determined during the authorization step
if (isAuthCodeRequest(parameters) && nonEmpty(tokenRequest.getScope())) {
tokenRequest.setScope(emptySet());
}
// A refresh token has its own default scopes, so we should ignore any added by the factory here.
if (isRefreshTokenRequest(parameters)) {
tokenRequest.setScope(OAuth2Utils.parseParameterList(parameters.get(OAuth2Utils.SCOPE)));
}
OAuth2AccessToken token = tokenGranter.grant(tokenRequest.getGrantType(), tokenRequest);
if (isNull(token)) {
throw new UnsupportedGrantTypeException("Unsupported grant type: " + tokenRequest.getGrantType());
}
createResponse(resp, token);
}, Resp(OAuth2AccessToken.class)).produces(JSON);
}
开发者ID:petrbouda,项目名称:joyrest,代码行数:50,代码来源:TokenEndpoint.java
示例17: getParametersForAuthorizeRequest
import org.springframework.security.oauth2.common.exceptions.InvalidRequestException; //导入依赖的package包/类
private MultiValueMap<String, String> getParametersForAuthorizeRequest(AuthorizationCodeResourceDetails resource,
AccessTokenRequest request) {
MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
form.set("response_type", "code");
form.set("client_id", resource.getClientId());
if (request.get("scope") != null) {
form.set("scope", request.getFirst("scope"));
}
else {
form.set("scope", OAuth2Utils.formatParameterList(resource.getScope()));
}
// Extracting the redirect URI from a saved request should ignore the current URI, so it's not simply a call to
// resource.getRedirectUri()
String redirectUri = resource.getPreEstablishedRedirectUri();
Object preservedState = request.getPreservedState();
if (redirectUri == null && preservedState != null) {
// no pre-established redirect uri: use the preserved state
// TODO: treat redirect URI as a special kind of state (this is a historical mini hack)
redirectUri = String.valueOf(preservedState);
}
else {
redirectUri = request.getCurrentUri();
}
String stateKey = request.getStateKey();
if (stateKey != null) {
form.set("state", stateKey);
if (preservedState == null) {
throw new InvalidRequestException(
"Possible CSRF detected - state parameter was present but no state could be found");
}
}
if (redirectUri != null) {
form.set("redirect_uri", redirectUri);
}
return form;
}
开发者ID:jungyang,项目名称:oauth-client-master,代码行数:45,代码来源:AuthorizationCodeAccessTokenProvider.java
示例18: getOAuth2Authentication
import org.springframework.security.oauth2.common.exceptions.InvalidRequestException; //导入依赖的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);
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();
// 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:jungyang,项目名称:oauth-client-master,代码行数:52,代码来源:AuthorizationCodeTokenGranter.java
示例19: getAccessToken
import org.springframework.security.oauth2.common.exceptions.InvalidRequestException; //导入依赖的package包/类
@RequestMapping
public ResponseEntity<OAuth2AccessToken> getAccessToken(Principal principal, @RequestParam
Map<String, String> parameters) {
if (!(principal instanceof Authentication)) {
throw new InsufficientAuthenticationException(
"There is no client authentication. Try adding an appropriate authentication filter.");
}
String clientId = getClientId(principal);
ClientDetails authenticatedClient = getClientDetailsService().loadClientByClientId(clientId);
TokenRequest tokenRequest = getOAuth2RequestFactory().createTokenRequest(parameters, authenticatedClient);
if (clientId != null && !clientId.equals("")) {
// Only validate the client details if a client authenticated during this
// request.
if (!clientId.equals(tokenRequest.getClientId())) {
// double check to make sure that the client ID in the token request is the same as that in the
// authenticated client
throw new InvalidClientException("Given client ID does not match authenticated client");
}
if (authenticatedClient != null) {
oAuth2RequestValidator.validateScope(tokenRequest, authenticatedClient);
}
}
if (!StringUtils.hasText(tokenRequest.getGrantType())) {
throw new InvalidRequestException("Missing grant type");
}
if (tokenRequest.getGrantType().equals("implicit")) {
throw new InvalidGrantException("Implicit grant type not supported from token endpoint");
}
if (isAuthCodeRequest(parameters) || isRefreshTokenRequest(parameters)) {
// The scope was requested or determined during the authorization step
if (!tokenRequest.getScope().isEmpty()) {
logger.debug("Clearing scope of incoming auth code request");
tokenRequest.setScope(Collections.<String> emptySet());
}
}
if (isRefreshTokenRequest(parameters)) {
// A refresh token has its own default scopes, so we should ignore any added by the factory here.
tokenRequest.setScope(OAuth2Utils.parseParameterList(parameters.get(OAuth2Utils.SCOPE)));
}
OAuth2AccessToken token = getTokenGranter().grant(tokenRequest.getGrantType(), tokenRequest);
if (token == null) {
throw new UnsupportedGrantTypeException("Unsupported grant type: " + tokenRequest.getGrantType());
}
return getResponse(token);
}
开发者ID:jungyang,项目名称:oauth-client-master,代码行数:55,代码来源:TokenEndpoint.java
示例20: approveOrDeny
import org.springframework.security.oauth2.common.exceptions.InvalidRequestException; //导入依赖的package包/类
@RequestMapping(method = RequestMethod.POST, params = OAuth2Utils.USER_OAUTH_APPROVAL)
public View approveOrDeny(@RequestParam Map<String, String> approvalParameters, Map<String, ?> model,
SessionStatus sessionStatus, Principal principal) {
if (!(principal instanceof Authentication)) {
sessionStatus.setComplete();
throw new InsufficientAuthenticationException(
"User must be authenticated with Spring Security before authorizing an access token.");
}
AuthorizationRequest authorizationRequest = (AuthorizationRequest) model.get("authorizationRequest");
if (authorizationRequest == null) {
sessionStatus.setComplete();
throw new InvalidRequestException("Cannot approve uninitialized authorization request.");
}
try {
Set<String> responseTypes = authorizationRequest.getResponseTypes();
authorizationRequest.setApprovalParameters(approvalParameters);
authorizationRequest = userApprovalHandler.updateAfterApproval(authorizationRequest, (Authentication) principal);
boolean approved = userApprovalHandler.isApproved(authorizationRequest, (Authentication) principal);
authorizationRequest.setApproved(approved);
if (authorizationRequest.getRedirectUri() == null) {
sessionStatus.setComplete();
throw new InvalidRequestException("Cannot approve request when no redirect URI is provided.");
}
if (!authorizationRequest.isApproved()) {
return new RedirectView(getUnsuccessfulRedirect(authorizationRequest, new UserDeniedAuthorizationException(
"User denied access"), responseTypes.contains("token")), false, true, false);
}
if (responseTypes.contains("token")) {
return getImplicitGrantResponse(authorizationRequest).getView();
}
return getAuthorizationCodeResponse(authorizationRequest, (Authentication) principal);
}
finally {
sessionStatus.setComplete();
}
}
开发者ID:jungyang,项目名称:oauth-client-master,代码行数:47,代码来源:AuthorizationEndpoint.java
注:本文中的org.springframework.security.oauth2.common.exceptions.InvalidRequestException类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论