org.springframework.security.oauth2.provider.TokenRequest Java Examples

The following examples show how to use org.springframework.security.oauth2.provider.TokenRequest. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PhonePasswordTokenGranter.java    From spring-cloud-shop with MIT License 8 votes vote down vote up
@Override
protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {

    Map<String, String> parameters = new LinkedHashMap<>(tokenRequest.getRequestParameters());
    String username = parameters.get("phone");
    String password = parameters.get("password");
    // Protect from downstream leaks of password
    parameters.remove("password");

    Authentication userAuth = new UsernamePasswordAuthenticationToken(username, password);
    ((AbstractAuthenticationToken) userAuth).setDetails(parameters);
    try {
        userAuth = authenticationManager.authenticate(userAuth);
    } catch (AccountStatusException | BadCredentialsException ase) {
        //covers expired, locked, disabled cases (mentioned in section 5.2, draft 31)
        throw new InvalidGrantException(ase.getMessage());
    } // If the username/password are wrong the spec says we should send 400/invalid grant

    if (userAuth == null || !userAuth.isAuthenticated()) {
        throw new InvalidGrantException("Could not authenticate user: " + username);
    }

    return new OAuth2Authentication(getRequestFactory().createOAuth2Request(client, tokenRequest), userAuth);
}
 
Example #2
Source File: SocialLoginServiceImpl.java    From FEBS-Cloud with Apache License 2.0 6 votes vote down vote up
private OAuth2AccessToken getOauth2AccessToken(SystemUser user) throws FebsException {
    final HttpServletRequest httpServletRequest = FebsUtil.getHttpServletRequest();
    httpServletRequest.setAttribute(ParamsConstant.LOGIN_TYPE, SocialConstant.SOCIAL_LOGIN);
    String socialLoginClientId = properties.getSocialLoginClientId();
    ClientDetails clientDetails = null;
    try {
        clientDetails = redisClientDetailsService.loadClientByClientId(socialLoginClientId);
    } catch (Exception e) {
        throw new FebsException("获取第三方登录可用的Client失败");
    }
    if (clientDetails == null) {
        throw new FebsException("未找到第三方登录可用的Client");
    }
    Map<String, String> requestParameters = new HashMap<>(5);
    requestParameters.put(ParamsConstant.GRANT_TYPE, GrantTypeConstant.PASSWORD);
    requestParameters.put(USERNAME, user.getUsername());
    requestParameters.put(PASSWORD, SocialConstant.SOCIAL_LOGIN_PASSWORD);

    String grantTypes = String.join(StringConstant.COMMA, clientDetails.getAuthorizedGrantTypes());
    TokenRequest tokenRequest = new TokenRequest(requestParameters, clientDetails.getClientId(), clientDetails.getScope(), grantTypes);
    return granter.grant(GrantTypeConstant.PASSWORD, tokenRequest);
}
 
Example #3
Source File: AuthorizationConfig.java    From Using-Spring-Oauth2-to-secure-REST with MIT License 6 votes vote down vote up
@Override
public OAuth2AccessToken refreshAccessToken(String refreshTokenValue, TokenRequest tokenRequest) throws AuthenticationException {
    logger.info("refresh token:" + refreshTokenValue);
    String jti = tokenRequest.getRequestParameters().get("jti");
    try {
        if ( jti != null )
                if ( blackListService.isBlackListed(jti) ) return null;


        OAuth2AccessToken token = super.refreshAccessToken(refreshTokenValue, tokenRequest);
        blackListService.addToBlackList(jti);
        return token;
    } catch (TokenBlackListService.TokenNotFoundException e) {
        e.printStackTrace();
        return null;
    }
}
 
Example #4
Source File: OAuth2Configuration.java    From spring-boot-2-oauth2-authorization-jwt with MIT License 5 votes vote down vote up
@Override
public TokenRequest createTokenRequest(Map<String, String> requestParameters,
		ClientDetails authenticatedClient) {
	if (requestParameters.get("grant_type").equals("refresh_token")) {
		OAuth2Authentication authentication = tokenStore.readAuthenticationForRefreshToken(
				tokenStore.readRefreshToken(requestParameters.get("refresh_token")));
		SecurityContextHolder.getContext()
				.setAuthentication(new UsernamePasswordAuthenticationToken(authentication.getName(), null,
						userDetailsService.loadUserByUsername(authentication.getName()).getAuthorities()));
	}
	return super.createTokenRequest(requestParameters, authenticatedClient);
}
 
Example #5
Source File: SmsTokenGranter.java    From spring-cloud-shop with MIT License 5 votes vote down vote up
@Override
protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
    Map<String, String> parameters = new LinkedHashMap<>(tokenRequest.getRequestParameters());
    String phone = parameters.get("phone");
    String smsCode = parameters.get("smsCode");
    Collection<? extends GrantedAuthority> grantedAuthorities = userService.loadUserBySMS(phone, smsCode);
    PreAuthenticatedAuthenticationToken authentication = new PreAuthenticatedAuthenticationToken(phone, null, grantedAuthorities);
    authentication.setDetails(parameters);
    return new OAuth2Authentication(this.requestFactory.createOAuth2Request(client, tokenRequest), authentication);
}
 
Example #6
Source File: OAuth2Configuration.java    From microservices-oauth with Apache License 2.0 5 votes vote down vote up
@Override
public TokenRequest createTokenRequest(Map<String, String> requestParameters,
		ClientDetails authenticatedClient) {
	if (requestParameters.get("grant_type").equals("refresh_token")) {
		OAuth2Authentication authentication = tokenStore.readAuthenticationForRefreshToken(
				tokenStore.readRefreshToken(requestParameters.get("refresh_token")));
		SecurityContextHolder.getContext()
				.setAuthentication(new UsernamePasswordAuthenticationToken(authentication.getName(), null,
						userDetailsService.loadUserByUsername(authentication.getName()).getAuthorities()));
	}
	return super.createTokenRequest(requestParameters, authenticatedClient);
}
 
Example #7
Source File: UserTokenRequest.java    From spring-cloud-gray with Apache License 2.0 4 votes vote down vote up
public UserTokenRequest(TokenRequest tokenRequest, UserDetails userDetails, Map<String, Serializable> extensionProperties){
    this(tokenRequest.getRequestParameters(), tokenRequest.getClientId(), tokenRequest.getScope(), tokenRequest.getGrantType());
    setExtensionProperties(extensionProperties);
    this.userDetails = userDetails;
}
 
Example #8
Source File: CustomAuthCodeTokenGranter.java    From OAuth-2.0-Cookbook with MIT License 4 votes vote down vote up
@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);

}
 
Example #9
Source File: CustomResourceOwnerPasswordTokenGranter.java    From spring-auth-example with MIT License 4 votes vote down vote up
@Override
protected OAuth2Authentication getOAuth2Authentication(ClientDetails client,
    TokenRequest tokenRequest) {

  Map<String, String> parameters = new LinkedHashMap<String, String>(
      tokenRequest.getRequestParameters());
  String username = parameters.get("username");
  String password = parameters.get("password");
  String clientId = client.getClientId();
  // Protect from downstream leaks of password
  parameters.remove("password");

  Authentication userAuth;
  if ("foo_app".equalsIgnoreCase(clientId)) {
    userAuth = new FooUsernamePasswordAuthenticationToken(username,
        password);
  } else if ("bar_app".equalsIgnoreCase(clientId)) {
    userAuth = new BarUsernamePasswordAuthenticationToken(username,
        password);
  } else {
    throw new InvalidGrantException("Unknown client: " + clientId);
  }

  ((AbstractAuthenticationToken) userAuth).setDetails(parameters);
  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/invalid 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);
}
 
Example #10
Source File: LessStrictRedirectUriAuthorizationCodeTokenGranter.java    From osiam with MIT License 4 votes vote down vote up
@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);
}