Search in sources :

Example 1 with JSONObject

use of org.springframework.security.oauth2.common.json.JSONObject in project fw-cloud-framework by liuweijw.

the class AjaxLoginSuccessHandler method onAuthenticationSuccess.

@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
    String header = request.getHeader(SecurityConstant.AUTHORIZATION);
    if (StringHelper.isBlank(header) || !header.startsWith(SecurityConstant.BASIC)) {
        throw new UnapprovedClientAuthenticationException("请求头中client信息为空");
    }
    try {
        String[] tokens = extractAndDecodeHeader(header);
        assert tokens.length == 2;
        String clientId = tokens[0];
        String clientSecret = tokens[1];
        JSONObject params = new JSONObject();
        params.put("clientId", clientId);
        params.put("clientSecret", clientSecret);
        params.put("authentication", authentication);
        ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId);
        TokenRequest tokenRequest = new TokenRequest(MapUtil.newHashMap(), clientId, clientDetails.getScope(), "mobile");
        OAuth2Request oAuth2Request = tokenRequest.createOAuth2Request(clientDetails);
        OAuth2Authentication oAuth2Authentication = new OAuth2Authentication(oAuth2Request, authentication);
        OAuth2AccessToken oAuth2AccessToken = authorizationServerTokenServices.createAccessToken(oAuth2Authentication);
        response.setCharacterEncoding(CommonConstant.UTF8);
        response.setContentType(CommonConstant.CONTENT_TYPE);
        PrintWriter printWriter = response.getWriter();
        printWriter.append(objectMapper.writeValueAsString(oAuth2AccessToken));
    } catch (IOException e) {
        throw new BadCredentialsException("Failed to decode basic authentication token");
    }
}
Also used : OAuth2Request(org.springframework.security.oauth2.provider.OAuth2Request) ClientDetails(org.springframework.security.oauth2.provider.ClientDetails) JSONObject(com.alibaba.fastjson.JSONObject) UnapprovedClientAuthenticationException(org.springframework.security.oauth2.common.exceptions.UnapprovedClientAuthenticationException) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) TokenRequest(org.springframework.security.oauth2.provider.TokenRequest) IOException(java.io.IOException) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) PrintWriter(java.io.PrintWriter)

Example 2 with JSONObject

use of org.springframework.security.oauth2.common.json.JSONObject in project spring-security by spring-projects.

the class NimbusReactiveOpaqueTokenIntrospectorTests method authenticateWhenActiveTokenThenParsesValuesInResponse.

@Test
public void authenticateWhenActiveTokenThenParsesValuesInResponse() {
    Map<String, Object> introspectedValues = new HashMap<>();
    introspectedValues.put(OAuth2TokenIntrospectionClaimNames.ACTIVE, true);
    introspectedValues.put(OAuth2TokenIntrospectionClaimNames.AUD, Arrays.asList("aud"));
    introspectedValues.put(OAuth2TokenIntrospectionClaimNames.NBF, 29348723984L);
    WebClient webClient = mockResponse(new JSONObject(introspectedValues).toJSONString());
    NimbusReactiveOpaqueTokenIntrospector introspectionClient = new NimbusReactiveOpaqueTokenIntrospector(INTROSPECTION_URL, webClient);
    OAuth2AuthenticatedPrincipal authority = introspectionClient.introspect("token").block();
    // @formatter:off
    assertThat(authority.getAttributes()).isNotNull().containsEntry(OAuth2TokenIntrospectionClaimNames.ACTIVE, true).containsEntry(OAuth2TokenIntrospectionClaimNames.AUD, Arrays.asList("aud")).containsEntry(OAuth2TokenIntrospectionClaimNames.NBF, Instant.ofEpochSecond(29348723984L)).doesNotContainKey(OAuth2TokenIntrospectionClaimNames.CLIENT_ID).doesNotContainKey(OAuth2TokenIntrospectionClaimNames.SCOPE);
// @formatter:on
}
Also used : JSONObject(net.minidev.json.JSONObject) HashMap(java.util.HashMap) OAuth2AuthenticatedPrincipal(org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal) JSONObject(net.minidev.json.JSONObject) WebClient(org.springframework.web.reactive.function.client.WebClient) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 3 with JSONObject

use of org.springframework.security.oauth2.common.json.JSONObject in project new-cloud by xie-summer.

the class MobileLoginSuccessHandler method onAuthenticationSuccess.

/**
 * Called when a user has been successfully authenticated.
 * 调用spring security oauth API 生成 oAuth2AccessToken
 *
 * @param request        the request which caused the successful authentication
 * @param response       the response
 * @param authentication the <tt>Authentication</tt> object which was created during
 */
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
    String header = request.getHeader("Authorization");
    if (header == null || !header.startsWith(BASIC_)) {
        throw new UnapprovedClientAuthenticationException("请求头中client信息为空");
    }
    try {
        String[] tokens = extractAndDecodeHeader(header);
        assert tokens.length == 2;
        String clientId = tokens[0];
        String clientSecret = tokens[1];
        JSONObject params = new JSONObject();
        params.put("clientId", clientId);
        params.put("clientSecret", clientSecret);
        params.put("authentication", authentication);
        ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId);
        TokenRequest tokenRequest = new TokenRequest(MapUtil.newHashMap(), clientId, clientDetails.getScope(), "mobile");
        OAuth2Request oAuth2Request = tokenRequest.createOAuth2Request(clientDetails);
        OAuth2Authentication oAuth2Authentication = new OAuth2Authentication(oAuth2Request, authentication);
        OAuth2AccessToken oAuth2AccessToken = authorizationServerTokenServices.createAccessToken(oAuth2Authentication);
        logger.info("获取token 成功:{}", oAuth2AccessToken.getValue());
        response.setCharacterEncoding(CommonConstant.UTF8);
        response.setContentType(CommonConstant.CONTENT_TYPE);
        PrintWriter printWriter = response.getWriter();
        printWriter.append(objectMapper.writeValueAsString(oAuth2AccessToken));
    } catch (IOException e) {
        throw new BadCredentialsException("Failed to decode basic authentication token");
    }
}
Also used : JSONObject(com.alibaba.fastjson.JSONObject) UnapprovedClientAuthenticationException(org.springframework.security.oauth2.common.exceptions.UnapprovedClientAuthenticationException) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) IOException(java.io.IOException) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) PrintWriter(java.io.PrintWriter)

Example 4 with JSONObject

use of org.springframework.security.oauth2.common.json.JSONObject in project new-cloud by xie-summer.

the class SocialLoginSuccessHandler method onAuthenticationSuccess.

/**
 * Called when a user has been successfully authenticated.
 * 调用spring security oauth API 生成 oAuth2AccessToken
 *
 * @param request        the request which caused the successful authentication
 * @param response       the response
 * @param authentication the <tt>Authentication</tt> object which was created during
 */
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
    try {
        String clientId = authServerConfig.getClientId();
        String clientSecret = authServerConfig.getClientSecret();
        JSONObject params = new JSONObject();
        params.put("clientId", clientId);
        params.put("clientSecret", clientSecret);
        params.put("authentication", authentication);
        ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId);
        TokenRequest tokenRequest = new TokenRequest(MapUtil.newHashMap(), clientId, clientDetails.getScope(), "social");
        OAuth2Request oAuth2Request = tokenRequest.createOAuth2Request(clientDetails);
        OAuth2Authentication oAuth2Authentication = new OAuth2Authentication(oAuth2Request, authentication);
        OAuth2AccessToken oAuth2AccessToken = authorizationServerTokenServices.createAccessToken(oAuth2Authentication);
        logger.info("获取token 成功:{}", oAuth2AccessToken.getValue());
        String url = String.format("http://localhost:9527/#/login?access_token=%s&refresh_token=%s", oAuth2AccessToken.getValue(), oAuth2AccessToken.getRefreshToken().getValue());
        logger.info("social登录,回调地址:{}", url);
        response.sendRedirect(url);
    } catch (IOException e) {
        throw new BadCredentialsException("Failed to decode basic authentication token");
    }
}
Also used : JSONObject(com.alibaba.fastjson.JSONObject) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) IOException(java.io.IOException) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException)

Example 5 with JSONObject

use of org.springframework.security.oauth2.common.json.JSONObject in project OpenClinica by OpenClinica.

the class RandomizeService method retrieveARandomisation.

private JSONObject retrieveARandomisation(String randomiseUrl, StudySubjectBean studySubject, HttpHeaders headers) throws JSONException {
    // method : GET
    // concatenate
    randomiseUrl = randomiseUrl + "/api/randomisation?identifier=" + studySubject.getOid();
    // Study_Siubject_oid
    RestTemplate rest = new RestTemplate(requestFactory);
    ResponseEntity<String> response = null;
    String body = null;
    JSONObject jsonObject = null;
    HttpEntity<String> request = new HttpEntity<String>(headers);
    try {
        response = rest.exchange(randomiseUrl, HttpMethod.GET, request, String.class);
        body = response.getBody();
        jsonObject = new JSONObject(body);
    // if (!jsonObject.get("error").equals("0"))
    // jsonObject= null;
    } catch (Exception e) {
        System.out.println(e.getMessage());
        logger.error(e.getMessage());
        logger.error(ExceptionUtils.getStackTrace(e));
    }
    return jsonObject;
}
Also used : JSONObject(org.springframework.security.oauth2.common.json.JSONObject) HttpEntity(org.springframework.http.HttpEntity) RestTemplate(org.springframework.web.client.RestTemplate) JSONException(org.springframework.security.oauth2.common.json.JSONException)

Aggregations

JSONObject (net.minidev.json.JSONObject)5 Test (org.junit.jupiter.api.Test)5 OAuth2AuthenticatedPrincipal (org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal)4 JSONObject (com.alibaba.fastjson.JSONObject)3 IOException (java.io.IOException)3 BadCredentialsException (org.springframework.security.authentication.BadCredentialsException)3 OAuth2AccessToken (org.springframework.security.oauth2.common.OAuth2AccessToken)3 JSONException (org.springframework.security.oauth2.common.json.JSONException)3 JSONObject (org.springframework.security.oauth2.common.json.JSONObject)3 PrintWriter (java.io.PrintWriter)2 HashMap (java.util.HashMap)2 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)2 HttpEntity (org.springframework.http.HttpEntity)2 UnapprovedClientAuthenticationException (org.springframework.security.oauth2.common.exceptions.UnapprovedClientAuthenticationException)2 DefaultOAuth2AuthenticatedPrincipal (org.springframework.security.oauth2.core.DefaultOAuth2AuthenticatedPrincipal)2 RestTemplate (org.springframework.web.client.RestTemplate)2 JWSHeader (com.nimbusds.jose.JWSHeader)1 JWSObject (com.nimbusds.jose.JWSObject)1 Payload (com.nimbusds.jose.Payload)1 RSASSASigner (com.nimbusds.jose.crypto.RSASSASigner)1