Search in sources :

Example 1 with OAuth2Authentication

use of org.maxkey.authz.oauth2.provider.OAuth2Authentication in project developer-be by EdgeGallery.

the class AccessTokenFilter method doFilterInternal.

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    if (request.getRequestURI() == null || !(request.getRequestURI().equals("/health"))) {
        String accessTokenStr = request.getHeader(Consts.ACCESS_TOKEN_STR);
        if (StringUtils.isEmpty(accessTokenStr)) {
            LOGGER.error("Access token is empty");
            response.sendError(HttpStatus.UNAUTHORIZED.value(), "Access token is empty");
            return;
        }
        OAuth2AccessToken accessToken = jwtTokenStore.readAccessToken(accessTokenStr);
        if (accessToken == null) {
            LOGGER.error("Invalid access token, token string is null");
            response.sendError(HttpStatus.UNAUTHORIZED.value(), "Invalid access token, token string is null.");
            return;
        }
        if (accessToken.isExpired()) {
            LOGGER.error("Access token expired");
            response.sendError(HttpStatus.UNAUTHORIZED.value(), "Access token expired");
            return;
        }
        Map<String, Object> additionalInfoMap = accessToken.getAdditionalInformation();
        if (additionalInfoMap == null) {
            LOGGER.error("Invalid access token, additional info map is null.");
            String msg = "Invalid access token, additional info map is null.";
            response.sendError(HttpStatus.UNAUTHORIZED.value(), msg);
            return;
        }
        String userIdFromToken = additionalInfoMap.get("userId").toString();
        String userNameFromToken = additionalInfoMap.get("userName").toString();
        String userAuthFromToken = additionalInfoMap.get("authorities").toString();
        AccessUserUtil.setUser(userIdFromToken, userNameFromToken, userAuthFromToken, accessTokenStr);
        String userIdFromRequest = request.getParameter("userId");
        if (!StringUtils.isEmpty(userIdFromRequest) && !userIdFromRequest.equals(userIdFromToken)) {
            LOGGER.error("Illegal userId");
            response.sendError(HttpStatus.UNAUTHORIZED.value(), "Illegal userId");
            return;
        }
        String userNameFromRequest = request.getParameter("userName");
        if (!StringUtils.isEmpty(userNameFromRequest) && !userNameFromRequest.equals(userNameFromToken)) {
            LOGGER.error("Illegal userName");
            response.sendError(HttpStatus.UNAUTHORIZED.value(), "Illegal userName");
            return;
        }
        OAuth2Authentication auth = jwtTokenStore.readAuthentication(accessToken);
        if (auth == null) {
            LOGGER.error("Invalid access token, authentication info is null.");
            String msg = "Invalid access token, authentication info is null.";
            response.sendError(HttpStatus.UNAUTHORIZED.value(), msg);
            return;
        }
        SecurityContextHolder.getContext().setAuthentication(auth);
    }
    try {
        filterChain.doFilter(request, response);
    } finally {
        AccessUserUtil.unload();
    }
}
Also used : OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication)

Example 2 with OAuth2Authentication

use of org.maxkey.authz.oauth2.provider.OAuth2Authentication in project service-api by reportportal.

the class AssignedToProjectPermission method isAllowed.

/**
 * Check whether user assigned to project<br>
 * Or user is ADMIN who is GOD of ReportPortal
 */
@Override
public boolean isAllowed(Authentication authentication, Object targetDomainObject) {
    if (!authentication.isAuthenticated()) {
        return false;
    }
    OAuth2Authentication oauth = (OAuth2Authentication) authentication;
    ReportPortalUser rpUser = (ReportPortalUser) oauth.getUserAuthentication().getPrincipal();
    BusinessRule.expect(rpUser, Objects::nonNull).verify(ErrorType.ACCESS_DENIED);
    final String resolvedProjectName = String.valueOf(targetDomainObject);
    final Optional<ReportPortalUser.ProjectDetails> projectDetails = projectExtractor.findProjectDetails(rpUser, resolvedProjectName);
    projectDetails.ifPresent(details -> fillProjectDetails(rpUser, resolvedProjectName, details));
    return projectDetails.isPresent();
}
Also used : OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) ReportPortalUser(com.epam.ta.reportportal.commons.ReportPortalUser)

Example 3 with OAuth2Authentication

use of org.maxkey.authz.oauth2.provider.OAuth2Authentication in project OpenID-Connect-Java-Spring-Server by mitreid-connect.

the class DefaultOIDCTokenService method createAssociatedToken.

private OAuth2AccessTokenEntity createAssociatedToken(ClientDetailsEntity client, Set<String> scope) {
    // revoke any previous tokens that might exist, just to be sure
    OAuth2AccessTokenEntity oldToken = tokenService.getRegistrationAccessTokenForClient(client);
    if (oldToken != null) {
        tokenService.revokeAccessToken(oldToken);
    }
    // create a new token
    Map<String, String> authorizationParameters = Maps.newHashMap();
    OAuth2Request clientAuth = new OAuth2Request(authorizationParameters, client.getClientId(), Sets.newHashSet(new SimpleGrantedAuthority("ROLE_CLIENT")), true, scope, null, null, null, null);
    OAuth2Authentication authentication = new OAuth2Authentication(clientAuth, null);
    OAuth2AccessTokenEntity token = new OAuth2AccessTokenEntity();
    token.setClient(client);
    token.setScope(scope);
    AuthenticationHolderEntity authHolder = new AuthenticationHolderEntity();
    authHolder.setAuthentication(authentication);
    authHolder = authenticationHolderRepository.save(authHolder);
    token.setAuthenticationHolder(authHolder);
    JWTClaimsSet claims = new JWTClaimsSet.Builder().audience(Lists.newArrayList(client.getClientId())).issuer(configBean.getIssuer()).issueTime(new Date()).expirationTime(token.getExpiration()).jwtID(// set a random NONCE in the middle of it
    UUID.randomUUID().toString()).build();
    JWSAlgorithm signingAlg = jwtService.getDefaultSigningAlgorithm();
    JWSHeader header = new JWSHeader(signingAlg, null, null, null, null, null, null, null, null, null, jwtService.getDefaultSignerKeyId(), null, null);
    SignedJWT signed = new SignedJWT(header, claims);
    jwtService.signJwt(signed);
    token.setJwt(signed);
    return token;
}
Also used : SignedJWT(com.nimbusds.jwt.SignedJWT) JWSAlgorithm(com.nimbusds.jose.JWSAlgorithm) Date(java.util.Date) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) OAuth2Request(org.springframework.security.oauth2.provider.OAuth2Request) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) OAuth2AccessTokenEntity(org.mitre.oauth2.model.OAuth2AccessTokenEntity) AuthenticationHolderEntity(org.mitre.oauth2.model.AuthenticationHolderEntity) JWSHeader(com.nimbusds.jose.JWSHeader)

Example 4 with OAuth2Authentication

use of org.maxkey.authz.oauth2.provider.OAuth2Authentication in project OpenID-Connect-Java-Spring-Server by mitreid-connect.

the class DeviceEndpoint method approveDevice.

@PreAuthorize("hasRole('ROLE_USER')")
@RequestMapping(value = "/" + USER_URL + "/approve", method = RequestMethod.POST)
public String approveDevice(@RequestParam("user_code") String userCode, @RequestParam(value = "user_oauth_approval") Boolean approve, ModelMap model, Authentication auth, HttpSession session) {
    AuthorizationRequest authorizationRequest = (AuthorizationRequest) session.getAttribute("authorizationRequest");
    DeviceCode dc = (DeviceCode) session.getAttribute("deviceCode");
    // make sure the form that was submitted is the one that we were expecting
    if (!dc.getUserCode().equals(userCode)) {
        model.addAttribute("error", "userCodeMismatch");
        return "requestUserCode";
    }
    // make sure the code hasn't expired yet
    if (dc.getExpiration() != null && dc.getExpiration().before(new Date())) {
        model.addAttribute("error", "expiredUserCode");
        return "requestUserCode";
    }
    ClientDetailsEntity client = clientService.loadClientByClientId(dc.getClientId());
    model.put("client", client);
    // user did not approve
    if (!approve) {
        model.addAttribute("approved", false);
        return "deviceApproved";
    }
    // create an OAuth request for storage
    OAuth2Request o2req = oAuth2RequestFactory.createOAuth2Request(authorizationRequest);
    OAuth2Authentication o2Auth = new OAuth2Authentication(o2req, auth);
    DeviceCode approvedCode = deviceCodeService.approveDeviceCode(dc, o2Auth);
    // pre-process the scopes
    Set<SystemScope> scopes = scopeService.fromStrings(dc.getScope());
    Set<SystemScope> sortedScopes = new LinkedHashSet<>(scopes.size());
    Set<SystemScope> systemScopes = scopeService.getAll();
    // sort scopes for display based on the inherent order of system scopes
    for (SystemScope s : systemScopes) {
        if (scopes.contains(s)) {
            sortedScopes.add(s);
        }
    }
    // add in any scopes that aren't system scopes to the end of the list
    sortedScopes.addAll(Sets.difference(scopes, systemScopes));
    model.put("scopes", sortedScopes);
    model.put("approved", true);
    return "deviceApproved";
}
Also used : LinkedHashSet(java.util.LinkedHashSet) ClientDetailsEntity(org.mitre.oauth2.model.ClientDetailsEntity) OAuth2Request(org.springframework.security.oauth2.provider.OAuth2Request) AuthorizationRequest(org.springframework.security.oauth2.provider.AuthorizationRequest) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) DeviceCode(org.mitre.oauth2.model.DeviceCode) SystemScope(org.mitre.oauth2.model.SystemScope) Date(java.util.Date) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 5 with OAuth2Authentication

use of org.maxkey.authz.oauth2.provider.OAuth2Authentication in project OpenID-Connect-Java-Spring-Server by mitreid-connect.

the class ChainedTokenGranter method getOAuth2Authentication.

/* (non-Javadoc)
	 * @see org.springframework.security.oauth2.provider.token.AbstractTokenGranter#getOAuth2Authentication(org.springframework.security.oauth2.provider.AuthorizationRequest)
	 */
@Override
protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) throws AuthenticationException, InvalidTokenException {
    // read and load up the existing token
    String incomingTokenValue = tokenRequest.getRequestParameters().get("token");
    OAuth2AccessTokenEntity incomingToken = tokenServices.readAccessToken(incomingTokenValue);
    // check for scoping in the request, can't up-scope with a chained request
    Set<String> approvedScopes = incomingToken.getScope();
    Set<String> requestedScopes = tokenRequest.getScope();
    if (requestedScopes == null) {
        requestedScopes = new HashSet<>();
    }
    // do a check on the requested scopes -- if they exactly match the client scopes, they were probably shadowed by the token granter
    if (client.getScope().equals(requestedScopes)) {
        requestedScopes = new HashSet<>();
    }
    // if our scopes are a valid subset of what's allowed, we can continue
    if (approvedScopes.containsAll(requestedScopes)) {
        if (requestedScopes.isEmpty()) {
            // if there are no scopes, inherit the original scopes from the token
            tokenRequest.setScope(approvedScopes);
        } else {
            // if scopes were asked for, give only the subset of scopes requested
            // this allows safe downscoping
            tokenRequest.setScope(Sets.intersection(requestedScopes, approvedScopes));
        }
        // NOTE: don't revoke the existing access token
        // create a new access token
        OAuth2Authentication authentication = new OAuth2Authentication(getRequestFactory().createOAuth2Request(client, tokenRequest), incomingToken.getAuthenticationHolder().getAuthentication().getUserAuthentication());
        return authentication;
    } else {
        throw new InvalidScopeException("Invalid scope requested in chained request", approvedScopes);
    }
}
Also used : OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) OAuth2AccessTokenEntity(org.mitre.oauth2.model.OAuth2AccessTokenEntity) InvalidScopeException(org.springframework.security.oauth2.common.exceptions.InvalidScopeException)

Aggregations

OAuth2Authentication (org.springframework.security.oauth2.provider.OAuth2Authentication)538 Authentication (org.springframework.security.core.Authentication)211 Test (org.junit.Test)192 OAuth2Request (org.springframework.security.oauth2.provider.OAuth2Request)177 OAuth2AccessToken (org.springframework.security.oauth2.common.OAuth2AccessToken)159 DefaultOAuth2AccessToken (org.springframework.security.oauth2.common.DefaultOAuth2AccessToken)107 AuthorizationRequest (org.springframework.security.oauth2.provider.AuthorizationRequest)91 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)68 HashMap (java.util.HashMap)67 Date (java.util.Date)47 IsEmptyString.isEmptyString (org.hamcrest.text.IsEmptyString.isEmptyString)42 GrantedAuthority (org.springframework.security.core.GrantedAuthority)35 Map (java.util.Map)32 OAuth2RefreshToken (org.springframework.security.oauth2.common.OAuth2RefreshToken)30 BaseClientDetails (org.springframework.security.oauth2.provider.client.BaseClientDetails)30 SimpleGrantedAuthority (org.springframework.security.core.authority.SimpleGrantedAuthority)29 InvalidTokenException (org.springframework.security.oauth2.common.exceptions.InvalidTokenException)28 OAuth2Authentication (org.maxkey.authz.oauth2.provider.OAuth2Authentication)27 UaaAuthentication (org.cloudfoundry.identity.uaa.authentication.UaaAuthentication)26 HashSet (java.util.HashSet)23