org.springframework.security.oauth2.common.util.OAuth2Utils Java Examples

The following examples show how to use org.springframework.security.oauth2.common.util.OAuth2Utils. 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: TokenController.java    From cloud-service with MIT License 6 votes vote down vote up
/**
     * 系统登陆<br>
     * 根据用户名登录<br>
     * 采用oauth2密码模式获取access_token和refresh_token
     *
     * @param username
     * @param password
     * @return
     */
    @PostMapping("/sys/login")
    public Map<String, Object> login(String username, String password) {
        Map<String, String> parameters = new HashMap<>();
        parameters.put(OAuth2Utils.GRANT_TYPE, "password");
        parameters.put(OAuth2Utils.CLIENT_ID, SystemClientInfo.CLIENT_ID);
        parameters.put("client_secret", SystemClientInfo.CLIENT_SECRET);
        parameters.put(OAuth2Utils.SCOPE, SystemClientInfo.CLIENT_SCOPE);
//		parameters.put("username", username);
        // 为了支持多类型登录,这里在username后拼装上登录类型
        parameters.put("username", username + "|" + CredentialType.USERNAME.name());
        parameters.put("password", password);

        Map<String, Object> tokenInfo = oauth2Client.postAccessToken(parameters);
        saveLoginLog(username, "用户名密码登陆");

        return tokenInfo;
    }
 
Example #2
Source File: TokenController.java    From cloud-service with MIT License 6 votes vote down vote up
/**
 * 短信登录
 *
 * @param phone
 * @param key
 * @param code
 * @return
 */
@PostMapping("/sys/login-sms")
public Map<String, Object> smsLogin(String phone, String key, String code) {
    Map<String, String> parameters = new HashMap<>();
    parameters.put(OAuth2Utils.GRANT_TYPE, "password");
    parameters.put(OAuth2Utils.CLIENT_ID, SystemClientInfo.CLIENT_ID);
    parameters.put("client_secret", SystemClientInfo.CLIENT_SECRET);
    parameters.put(OAuth2Utils.SCOPE, SystemClientInfo.CLIENT_SCOPE);
    // 为了支持多类型登录,这里在username后拼装上登录类型,同时为了校验短信验证码,我们也拼上code等
    parameters.put("username", phone + "|" + CredentialType.PHONE.name() + "|" + key + "|" + code + "|"
            + DigestUtils.md5Hex(key + code));
    // 短信登录无需密码,但security底层有密码校验,我们这里将手机号作为密码,认证中心采用同样规则即可
    parameters.put("password", phone);

    Map<String, Object> tokenInfo = oauth2Client.postAccessToken(parameters);
    saveLoginLog(phone, "手机号短信登陆");

    return tokenInfo;
}
 
Example #3
Source File: TokenController.java    From cloud-service with MIT License 6 votes vote down vote up
/**
 * 微信登录
 *
 * @return
 */
@PostMapping("/sys/login-wechat")
public Map<String, Object> smsLogin(String openid, String tempCode) {
    Map<String, String> parameters = new HashMap<>();
    parameters.put(OAuth2Utils.GRANT_TYPE, "password");
    parameters.put(OAuth2Utils.CLIENT_ID, SystemClientInfo.CLIENT_ID);
    parameters.put("client_secret", SystemClientInfo.CLIENT_SECRET);
    parameters.put(OAuth2Utils.SCOPE, SystemClientInfo.CLIENT_SCOPE);
    // 为了支持多类型登录,这里在username后拼装上登录类型,同时为了服务端校验,我们也拼上tempCode
    parameters.put("username", openid + "|" + CredentialType.WECHAT_OPENID.name() + "|" + tempCode);
    // 微信登录无需密码,但security底层有密码校验,我们这里将手机号作为密码,认证中心采用同样规则即可
    parameters.put("password", tempCode);

    Map<String, Object> tokenInfo = oauth2Client.postAccessToken(parameters);
    saveLoginLog(openid, "微信登陆");

    return tokenInfo;
}
 
Example #4
Source File: OauthAuthorizeAspect.java    From microservices-platform with Apache License 2.0 6 votes vote down vote up
@Around("execution(* org.springframework.security.oauth2.provider.endpoint.AuthorizationEndpoint.authorize(..))")
public Object doAroundMethod(ProceedingJoinPoint joinPoint) throws Throwable {
    Object[] args = joinPoint.getArgs();
    Map<String, String> parameters = (Map<String, String>) args[1];
    Principal principal = (Principal) args[3];
    if (principal instanceof TenantUsernamePasswordAuthenticationToken) {
        TenantUsernamePasswordAuthenticationToken tenantToken = (TenantUsernamePasswordAuthenticationToken)principal;
        String clientId = tenantToken.getClientId();
        String requestClientId = parameters.get(OAuth2Utils.CLIENT_ID);
        //判断是否不同租户单点登录
        if (!requestClientId.equals(clientId)) {
            try {
                TenantContextHolder.setTenant(requestClientId);
                //重新查询对应该租户的角色等信息
                LoginAppUser user = userService.findByUsername(tenantToken.getName());
                tenantToken = new TenantUsernamePasswordAuthenticationToken(user, tenantToken.getCredentials(), user.getAuthorities(), requestClientId);
                args[3] = tenantToken;
            } finally {
                TenantContextHolder.clear();
            }
        }
    }
    return joinPoint.proceed(args);
}
 
Example #5
Source File: ChoerodonAuthenticationKeyGenerator.java    From oauth-server with Apache License 2.0 6 votes vote down vote up
@Override
public String extractKey(OAuth2Authentication authentication) {
    Map<String, String> values = new LinkedHashMap<>();
    OAuth2Request authorizationRequest = authentication.getOAuth2Request();
    if (!authentication.isClientOnly()) {
        values.put(USERNAME, authentication.getName());
    }
    values.put(CLIENT_ID, authorizationRequest.getClientId());
    if (authorizationRequest.getScope() != null) {
        values.put(SCOPE, OAuth2Utils.formatParameterList(new TreeSet<>(authorizationRequest.getScope())));
    }
    Authentication auth = authentication.getUserAuthentication();
    if (auth != null && auth.getDetails() instanceof WebAuthenticationDetails) {
        String sessionId = ((WebAuthenticationDetails) auth.getDetails()).getSessionId();
        logger.info("sessionId : {}", sessionId);
        if (!StringUtils.isEmpty(sessionId)) {
            values.put(SESSION, sessionId);
        }
    }
    return generateKey(values);
}
 
Example #6
Source File: LoginController.java    From cloud-native-microservice-strangler-example with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Generate an authorization parameter map from the session's token request
 * @param defaultSavedRequest the default saved request from the session
 * @return a map of parameters containing the OAuth2 request details
 */
private Map<String, String> getAuthParameters(DefaultSavedRequest defaultSavedRequest) {
    Map<String, String> authParams = new HashMap<>();

    authParams.put(OAuth2Utils.CLIENT_ID,
            defaultSavedRequest.getParameterMap().get(OAuth2Utils.CLIENT_ID)[0]);

    authParams.put(OAuth2Utils.REDIRECT_URI,
            defaultSavedRequest.getParameterMap().get(OAuth2Utils.REDIRECT_URI)[0]);

    if(defaultSavedRequest.getParameterMap().get(OAuth2Utils.STATE) != null) {
        authParams.put(OAuth2Utils.STATE,
                defaultSavedRequest.getParameterMap().get(OAuth2Utils.STATE)[0]);
    }

    authParams.put(OAuth2Utils.RESPONSE_TYPE, "code");
    authParams.put(OAuth2Utils.USER_OAUTH_APPROVAL, "true");
    authParams.put(OAuth2Utils.GRANT_TYPE, "authorization_code");
    return authParams;
}
 
Example #7
Source File: AccessConfirmationController.java    From spring-boot with Apache License 2.0 6 votes vote down vote up
@RequestMapping("/oauth/confirm_access")
public ModelAndView getAccessConfirmation(Map<String, Object> model, Principal principal) throws Exception {
    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 new ModelAndView("access_confirmation", model); // 订阅 appproval 页面
}
 
Example #8
Source File: LoginController.java    From spring-cloud-event-sourcing-example with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Generate an authorization parameter map from the session's token request
 * @param defaultSavedRequest the default saved request from the session
 * @return a map of parameters containing the OAuth2 request details
 */
private Map<String, String> getAuthParameters(DefaultSavedRequest defaultSavedRequest) {
    Map<String, String> authParams = new HashMap<>();

    authParams.put(OAuth2Utils.CLIENT_ID,
            defaultSavedRequest.getParameterMap().get(OAuth2Utils.CLIENT_ID)[0]);

    authParams.put(OAuth2Utils.REDIRECT_URI,
            defaultSavedRequest.getParameterMap().get(OAuth2Utils.REDIRECT_URI)[0]);

    if(defaultSavedRequest.getParameterMap().get(OAuth2Utils.STATE) != null) {
        authParams.put(OAuth2Utils.STATE,
                defaultSavedRequest.getParameterMap().get(OAuth2Utils.STATE)[0]);
    }

    authParams.put(OAuth2Utils.RESPONSE_TYPE, "code");
    authParams.put(OAuth2Utils.USER_OAUTH_APPROVAL, "true");
    authParams.put(OAuth2Utils.GRANT_TYPE, "authorization_code");
    return authParams;
}
 
Example #9
Source File: AccessConfirmationController.java    From OpenESPI-DataCustodian-java with Apache License 2.0 6 votes vote down vote up
@RequestMapping("/oauth/confirm_access")
public ModelAndView getAccessConfirmation(Map<String, Object> model, Principal principal) throws Exception {
	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");  //Spring Security OAuth2 2.0.0.M2 change
	}
	for (Approval approval : approvalStore.getApprovals(principal.getName(), client.getClientId())) {
		if (clientAuth.getScope().contains(approval.getScope())) {
			scopes.put(OAuth2Utils.SCOPE_PREFIX + approval.getScope(),
					approval.getStatus() == ApprovalStatus.APPROVED ? "true" : "false");
		}
	}
	model.put("scopes", scopes);
	return new ModelAndView("access_confirmation", model);
}
 
Example #10
Source File: OauthTokenAspect.java    From microservices-platform with Apache License 2.0 5 votes vote down vote up
@Around("execution(* org.springframework.security.oauth2.provider.endpoint.TokenEndpoint.postAccessToken(..))")
public Object handleControllerMethod(ProceedingJoinPoint joinPoint) throws Throwable {
    try {
        Object[] args = joinPoint.getArgs();
        Principal principal = (Principal) args[0];
        if (!(principal instanceof Authentication)) {
            throw new InsufficientAuthenticationException(
                    "There is no client authentication. Try adding an appropriate authentication filter.");
        }
        String clientId = getClientId(principal);
        Map<String, String> parameters = (Map<String, String>) args[1];
        String grantType = parameters.get(OAuth2Utils.GRANT_TYPE);

        //保存租户id
        TenantContextHolder.setTenant(clientId);
        Object proceed = joinPoint.proceed();
        if (SecurityConstants.AUTHORIZATION_CODE.equals(grantType)) {
            /*
             如果使用 @EnableOAuth2Sso 注解不能修改返回格式,否则授权码模式可以统一改
             因为本项目的 sso-demo/ss-sso 里面使用了 @EnableOAuth2Sso 注解,所以这里就不修改授权码模式的token返回值了
             */
            return proceed;
        } else {
            ResponseEntity<OAuth2AccessToken> responseEntity = (ResponseEntity<OAuth2AccessToken>) proceed;
            OAuth2AccessToken body = responseEntity.getBody();
            return ResponseEntity
                    .status(HttpStatus.OK)
                    .body(Result.succeed(body));
        }
    } catch (Exception e) {
        log.error("授权错误", e);
        return ResponseEntity
                .status(HttpStatus.BAD_REQUEST)
                .body(Result.failed(e.getMessage()));
    } finally {
        TenantContextHolder.clear();
    }
}
 
Example #11
Source File: AuthorizationController.java    From Taroco with Apache License 2.0 5 votes vote down vote up
/**
 * 自定义 确认/拒绝授权
 *
 * @param approvalParameters
 * @param model
 * @param sessionStatus
 * @param principal
 * @return
 */
@RequestMapping(value = "/oauth/custom_authorize", method = RequestMethod.POST, params = OAuth2Utils.USER_OAUTH_APPROVAL)
public ResponseEntity<Response> approveOrDeny(@RequestParam Map<String, String> approvalParameters,
                                              Map<String, ?> model, SessionStatus sessionStatus, Principal principal) {
    try{
        final RedirectView redirectView = (RedirectView) authorizationEndpoint.approveOrDeny(
                approvalParameters, model, sessionStatus, principal);
        return ResponseEntity.ok(Response.success(redirectView.getUrl()));
    } catch (OAuth2Exception e) {
        log.error("确认/拒绝授权失败", e);
        return ResponseEntity.status(e.getHttpErrorCode()).body(Response.failure(e.getOAuth2ErrorCode(), e.getMessage()));
    }
}
 
Example #12
Source File: MyAuthorizationCodeAccessTokenProvider.java    From springboot-security-wechat with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #13
Source File: LoginController.java    From microservices-event-sourcing with Apache License 2.0 5 votes vote down vote up
/**
 * 为会话的令牌请求生成认证参数Map
 * @param defaultSavedRequest 会话中默认保存的SPRING_SECURITY_SAVED_REQUEST请求
 * @return 包含OAuth2请求明细的参数Map
 */
private Map<String,String> getAuthParameters(DefaultSavedRequest defaultSavedRequest) {
    Map<String, String> authParams = new HashMap<>();
    authParams.put(OAuth2Utils.CLIENT_ID, defaultSavedRequest.getParameterMap().get(OAuth2Utils.CLIENT_ID)[0]);
    authParams.put(OAuth2Utils.REDIRECT_URI, defaultSavedRequest.getParameterMap().get(OAuth2Utils.REDIRECT_URI)[0]);
    if(defaultSavedRequest.getParameterMap().get(OAuth2Utils.STATE) != null) {
        authParams.put(OAuth2Utils.STATE, defaultSavedRequest.getParameterMap().get(OAuth2Utils.STATE)[0]);
    }

    authParams.put(OAuth2Utils.RESPONSE_TYPE, "code");
    authParams.put(OAuth2Utils.USER_OAUTH_APPROVAL, "true");
    authParams.put(OAuth2Utils.GRANT_TYPE, "authorization_code");

    return authParams;
}
 
Example #14
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 #15
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);
}
 
Example #16
Source File: OAuthRestController.java    From spring-oauth-server with GNU General Public License v2.0 4 votes vote down vote up
@RequestMapping(value = "/oauth/rest_token", method = RequestMethod.POST)
@ResponseBody
public OAuth2AccessToken postAccessToken(@RequestBody Map<String, String> parameters) {


    String clientId = getClientId(parameters);
    ClientDetails authenticatedClient = clientDetailsService.loadClientByClientId(clientId);

    TokenRequest tokenRequest = oAuth2RequestFactory.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);
    }

    final String grantType = tokenRequest.getGrantType();
    if (!StringUtils.hasText(grantType)) {
        throw new InvalidRequestException("Missing grant type");
    }
    if (grantType.equals("implicit")) {
        throw new InvalidGrantException("Implicit grant type not supported from token endpoint");
    }

    if (isAuthCodeRequest(parameters)) {
        // The scope was requested or determined during the authorization step
        if (!tokenRequest.getScope().isEmpty()) {
            LOG.debug("Clearing scope of incoming token 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(grantType).grant(grantType, tokenRequest);
    if (token == null) {
        throw new UnsupportedGrantTypeException("Unsupported grant type: " + grantType);
    }


    return token;

}