Search in sources :

Example 61 with OAuth2Authentication

use of org.springframework.security.oauth2.provider.OAuth2Authentication in project spring-security-oauth by spring-projects.

the class TokenStoreBaseTests method testStoreAccessToken.

@Test
public void testStoreAccessToken() {
    OAuth2Authentication expectedAuthentication = new OAuth2Authentication(RequestTokenFactory.createOAuth2Request("id", false), new TestAuthentication("test2", false));
    OAuth2AccessToken expectedOAuth2AccessToken = new DefaultOAuth2AccessToken("testToken");
    getTokenStore().storeAccessToken(expectedOAuth2AccessToken, expectedAuthentication);
    OAuth2AccessToken actualOAuth2AccessToken = getTokenStore().readAccessToken("testToken");
    assertEquals(expectedOAuth2AccessToken, actualOAuth2AccessToken);
    assertEquals(expectedAuthentication, getTokenStore().readAuthentication(expectedOAuth2AccessToken));
    getTokenStore().removeAccessToken(expectedOAuth2AccessToken);
    assertNull(getTokenStore().readAccessToken("testToken"));
    assertNull(getTokenStore().readAuthentication(expectedOAuth2AccessToken.getValue()));
}
Also used : DefaultOAuth2AccessToken(org.springframework.security.oauth2.common.DefaultOAuth2AccessToken) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) DefaultOAuth2AccessToken(org.springframework.security.oauth2.common.DefaultOAuth2AccessToken) Test(org.junit.Test)

Example 62 with OAuth2Authentication

use of org.springframework.security.oauth2.provider.OAuth2Authentication in project spring-security-oauth by spring-projects.

the class TokenEndpoint method getClientId.

/**
	 * @param principal the currently authentication principal
	 * @return a client id if there is one in the principal
	 */
protected String getClientId(Principal principal) {
    Authentication client = (Authentication) principal;
    if (!client.isAuthenticated()) {
        throw new InsufficientAuthenticationException("The client is not authenticated.");
    }
    String clientId = client.getName();
    if (client instanceof OAuth2Authentication) {
        // Might be a client and user combined authentication
        clientId = ((OAuth2Authentication) client).getOAuth2Request().getClientId();
    }
    return clientId;
}
Also used : OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) Authentication(org.springframework.security.core.Authentication) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) InsufficientAuthenticationException(org.springframework.security.authentication.InsufficientAuthenticationException)

Example 63 with OAuth2Authentication

use of org.springframework.security.oauth2.provider.OAuth2Authentication in project spring-security-oauth by spring-projects.

the class TokenEndpointAuthenticationFilter method doFilter.

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    final boolean debug = logger.isDebugEnabled();
    final HttpServletRequest request = (HttpServletRequest) req;
    final HttpServletResponse response = (HttpServletResponse) res;
    try {
        Authentication credentials = extractCredentials(request);
        if (credentials != null) {
            if (debug) {
                logger.debug("Authentication credentials found for '" + credentials.getName() + "'");
            }
            Authentication authResult = authenticationManager.authenticate(credentials);
            if (debug) {
                logger.debug("Authentication success: " + authResult.getName());
            }
            Authentication clientAuth = SecurityContextHolder.getContext().getAuthentication();
            if (clientAuth == null) {
                throw new BadCredentialsException("No client authentication found. Remember to put a filter upstream of the TokenEndpointAuthenticationFilter.");
            }
            Map<String, String> map = getSingleValueMap(request);
            map.put(OAuth2Utils.CLIENT_ID, clientAuth.getName());
            AuthorizationRequest authorizationRequest = oAuth2RequestFactory.createAuthorizationRequest(map);
            authorizationRequest.setScope(getScope(request));
            if (clientAuth.isAuthenticated()) {
                // Ensure the OAuth2Authentication is authenticated
                authorizationRequest.setApproved(true);
            }
            OAuth2Request storedOAuth2Request = oAuth2RequestFactory.createOAuth2Request(authorizationRequest);
            SecurityContextHolder.getContext().setAuthentication(new OAuth2Authentication(storedOAuth2Request, authResult));
            onSuccessfulAuthentication(request, response, authResult);
        }
    } catch (AuthenticationException failed) {
        SecurityContextHolder.clearContext();
        if (debug) {
            logger.debug("Authentication request for failed: " + failed);
        }
        onUnsuccessfulAuthentication(request, response, failed);
        authenticationEntryPoint.commence(request, response, failed);
        return;
    }
    chain.doFilter(request, response);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) OAuth2Request(org.springframework.security.oauth2.provider.OAuth2Request) AuthorizationRequest(org.springframework.security.oauth2.provider.AuthorizationRequest) AuthenticationException(org.springframework.security.core.AuthenticationException) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) Authentication(org.springframework.security.core.Authentication) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) HttpServletResponse(javax.servlet.http.HttpServletResponse) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException)

Example 64 with OAuth2Authentication

use of org.springframework.security.oauth2.provider.OAuth2Authentication in project spring-security-oauth by spring-projects.

the class CheckTokenEndpoint method checkToken.

@RequestMapping(value = "/oauth/check_token")
@ResponseBody
public Map<String, ?> checkToken(@RequestParam("token") String value) {
    OAuth2AccessToken token = resourceServerTokenServices.readAccessToken(value);
    if (token == null) {
        throw new InvalidTokenException("Token was not recognised");
    }
    if (token.isExpired()) {
        throw new InvalidTokenException("Token has expired");
    }
    OAuth2Authentication authentication = resourceServerTokenServices.loadAuthentication(token.getValue());
    Map<String, ?> response = accessTokenConverter.convertAccessToken(token, authentication);
    return response;
}
Also used : InvalidTokenException(org.springframework.security.oauth2.common.exceptions.InvalidTokenException) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 65 with OAuth2Authentication

use of org.springframework.security.oauth2.provider.OAuth2Authentication in project spring-security-oauth by spring-projects.

the class TokenApprovalStore method getApprovals.

/**
	 * Extract the implied approvals from any tokens associated with the user and client id supplied.
	 * 
	 * @see org.springframework.security.oauth2.provider.approval.ApprovalStore#getApprovals(java.lang.String,
	 * java.lang.String)
	 */
@Override
public Collection<Approval> getApprovals(String userId, String clientId) {
    Collection<Approval> result = new HashSet<Approval>();
    Collection<OAuth2AccessToken> tokens = store.findTokensByClientIdAndUserName(clientId, userId);
    for (OAuth2AccessToken token : tokens) {
        OAuth2Authentication authentication = store.readAuthentication(token);
        if (authentication != null) {
            Date expiresAt = token.getExpiration();
            for (String scope : token.getScope()) {
                result.add(new Approval(userId, clientId, scope, expiresAt, ApprovalStatus.APPROVED));
            }
        }
    }
    return result;
}
Also used : OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) Date(java.util.Date) HashSet(java.util.HashSet)

Aggregations

OAuth2Authentication (org.springframework.security.oauth2.provider.OAuth2Authentication)167 Test (org.junit.Test)116 OAuth2Request (org.springframework.security.oauth2.provider.OAuth2Request)84 Authentication (org.springframework.security.core.Authentication)69 OAuth2AccessToken (org.springframework.security.oauth2.common.OAuth2AccessToken)58 DefaultOAuth2AccessToken (org.springframework.security.oauth2.common.DefaultOAuth2AccessToken)50 Date (java.util.Date)34 HashMap (java.util.HashMap)23 AuthorizationRequest (org.springframework.security.oauth2.provider.AuthorizationRequest)21 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)20 DBUnitTest (org.orcid.test.DBUnitTest)17 ProfileEntity (org.orcid.persistence.jpa.entities.ProfileEntity)15 DefaultExpiringOAuth2RefreshToken (org.springframework.security.oauth2.common.DefaultExpiringOAuth2RefreshToken)15 DefaultOAuth2RefreshToken (org.springframework.security.oauth2.common.DefaultOAuth2RefreshToken)15 HashSet (java.util.HashSet)13 ClientDetailsEntity (org.orcid.persistence.jpa.entities.ClientDetailsEntity)13 ExpiringOAuth2RefreshToken (org.springframework.security.oauth2.common.ExpiringOAuth2RefreshToken)13 OAuth2RefreshToken (org.springframework.security.oauth2.common.OAuth2RefreshToken)13 TokenRequest (org.springframework.security.oauth2.provider.TokenRequest)13 BaseClientDetails (org.springframework.security.oauth2.provider.client.BaseClientDetails)12