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

The following examples show how to use org.springframework.security.oauth2.provider.OAuth2Request. 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: TokenService.java    From osiam with MIT License 7 votes vote down vote up
public AccessToken validateToken(final String token) {
    OAuth2Authentication auth = tokenStore.readAuthentication(token);
    OAuth2AccessToken accessToken = tokenStore.getAccessToken(auth);
    OAuth2Request authReq = auth.getOAuth2Request();

    AccessToken.Builder tokenBuilder = new AccessToken.Builder(token).setClientId(authReq.getClientId());

    if (auth.getUserAuthentication() != null && auth.getPrincipal() instanceof User) {
        User user = (User) auth.getPrincipal();
        tokenBuilder.setUserName(user.getUserName());
        tokenBuilder.setUserId(user.getId());
    }

    tokenBuilder.setExpiresAt(accessToken.getExpiration());
    for (String scopeString : authReq.getScope()) {
        tokenBuilder.addScope(new Scope(scopeString));
    }

    return tokenBuilder.build();
}
 
Example #2
Source File: CustomRedisTokenStore.java    From microservices-platform with Apache License 2.0 6 votes vote down vote up
@Override
public OAuth2Authentication readAuthentication(OAuth2AccessToken token) {
    OAuth2Authentication auth2Authentication = readAuthentication(token.getValue());
    //是否开启token续签
    boolean isRenew = securityProperties.getAuth().getRenew().getEnable();
    if (isRenew && auth2Authentication != null) {
        OAuth2Request clientAuth = auth2Authentication.getOAuth2Request();
        //判断当前应用是否需要自动续签
        if (checkRenewClientId(clientAuth.getClientId())) {
            //获取过期时长
            int validitySeconds = getAccessTokenValiditySeconds(clientAuth.getClientId());
            if (validitySeconds > 0) {
                double expiresRatio = token.getExpiresIn() / (double)validitySeconds;
                //判断是否需要续签,当前剩余时间小于过期时长的50%则续签
                if (expiresRatio <= securityProperties.getAuth().getRenew().getTimeRatio()) {
                    //更新AccessToken过期时间
                    DefaultOAuth2AccessToken oAuth2AccessToken = (DefaultOAuth2AccessToken) token;
                    oAuth2AccessToken.setExpiration(new Date(System.currentTimeMillis() + (validitySeconds * 1000L)));
                    storeAccessToken(oAuth2AccessToken, auth2Authentication, true);
                }
            }
        }
    }
    return auth2Authentication;
}
 
Example #3
Source File: WithOAuth2MockAccessTokenSecurityContextFactory.java    From microservices-basics-spring-boot with Apache License 2.0 6 votes vote down vote up
/**
 * Mock OAuth2Request
 * 
 * @param withMockOAuth2Token
 * @return
 */
private OAuth2Request getOauth2Request(WithMockOAuth2Token withMockOAuth2Token) {
	String clientId = withMockOAuth2Token.clientId();
	Map<String, String> requestParameters = Collections.emptyMap();
	boolean approved = true;
	String redirectUrl = withMockOAuth2Token.redirectUrl();
	Set<String> responseTypes = Collections.emptySet();
	Set<String> scopes = new HashSet<>(Arrays.asList(withMockOAuth2Token.scopes()));
	Set<String> resourceIds = Collections.emptySet();
	Map<String, Serializable> extensionProperties = Collections.emptyMap();
	List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList(withMockOAuth2Token.authorities());

	OAuth2Request oAuth2Request = new OAuth2Request(requestParameters, clientId, authorities, approved, scopes,
			resourceIds, redirectUrl, responseTypes, extensionProperties);

	return oAuth2Request;
}
 
Example #4
Source File: JwtAccessTokenCustomizer.java    From spring-oauth2-keycloak-connector with Apache License 2.0 6 votes vote down vote up
/**
 * Spring oauth2 expects roles under authorities element in tokenMap, but keycloak provides it under resource_access. Hence extractAuthentication
 * method is overriden to extract roles from resource_access.
 *
 * @return OAuth2Authentication with authorities for given application
 */
@Override
public OAuth2Authentication extractAuthentication(Map<String, ?> tokenMap) {
  LOG.debug("Begin extractAuthentication: tokenMap = {}", tokenMap);
  JsonNode token = mapper.convertValue(tokenMap, JsonNode.class);
  Set<String> audienceList = extractClients(token); // extracting client names
  List<GrantedAuthority> authorities = extractRoles(token); // extracting client roles

  OAuth2Authentication authentication = super.extractAuthentication(tokenMap);
  OAuth2Request oAuth2Request = authentication.getOAuth2Request();

  OAuth2Request request =
      new OAuth2Request(oAuth2Request.getRequestParameters(), oAuth2Request.getClientId(), authorities, true, oAuth2Request.getScope(),
          audienceList, null, null, null);

  Authentication usernamePasswordAuthentication = new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), "N/A", authorities);
  LOG.debug("End extractAuthentication");
  return new OAuth2Authentication(request, usernamePasswordAuthentication);
}
 
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: ClientIdAuthorityGrantingAuthenticationExtractor.java    From pazuzu-registry with MIT License 6 votes vote down vote up
@Override
public OAuth2Authentication extractAuthentication(Map<String, Object> map, String clientId) {
    Object principal = getPrincipal(map);

    Set<String> roles = grantUserRoles(principal);

    UsernamePasswordAuthenticationToken user = new UsernamePasswordAuthenticationToken(
            principal,
            "N/A",
            rolesToGrantedAuthorities(roles)
    );
    user.setDetails(map);

    OAuth2Request request = new OAuth2Request(null, clientId, null, true, resolveScopes(map), null, null, null, null);
    return new OAuth2Authentication(request, user);
}
 
Example #7
Source File: OAuth2AuthorizationServerConfig.java    From NFVO with Apache License 2.0 6 votes vote down vote up
/**
 * Method for generating an OAuth2 token for services. The token's (and refresh token's) validity
 * duration is longer than for normal users.
 *
 * @param serviceName
 * @return the oauth2 service token
 */
public OAuth2AccessToken getNewServiceToken(String serviceName) {
  Set<GrantedAuthority> authorities = new HashSet<>();
  authorities.add(new SimpleGrantedAuthority("ADMIN"));

  OAuth2Request oAuth2Request = buildOAuth2Request(serviceName, authorities);
  User userPrincipal =
      new User(serviceName, "" + Math.random() * 1000, true, true, true, true, authorities);

  UsernamePasswordAuthenticationToken authenticationToken =
      new UsernamePasswordAuthenticationToken(userPrincipal, null, authorities);
  OAuth2Authentication auth = new OAuth2Authentication(oAuth2Request, authenticationToken);

  BaseClientDetails externalServiceClientDetails = buildExternalServiceClientDetails(serviceName);
  customClientDetailsService.addclientDetails(externalServiceClientDetails);

  OAuth2AccessToken token = serviceTokenServices.createAccessToken(auth);
  log.trace("New Service token: " + token);
  return token;
}
 
Example #8
Source File: OAuth2AuthorizationServerConfig.java    From NFVO with Apache License 2.0 6 votes vote down vote up
/**
 * Method returns a token that can be used to request a specific image file contained in the
 * NFVImage repository from the REST API.
 *
 * @param imageId ID of the image that can be retrieved with the token
 * @return the oauth2 token for fetching image files from the image repository
 */
public String getNewImageToken(String imageId) {
  Set<GrantedAuthority> authorities = new HashSet<>();
  authorities.add(new SimpleGrantedAuthority(imageId));

  OAuth2Request oAuth2Request = buildOAuth2Request("vimdriver" + imageId, authorities);

  User userPrincipal =
      new User(
          "vimdriver" + imageId, "" + Math.random() * 1000, true, true, true, true, authorities);

  UsernamePasswordAuthenticationToken authenticationToken =
      new UsernamePasswordAuthenticationToken(userPrincipal, null, authorities);
  OAuth2Authentication auth = new OAuth2Authentication(oAuth2Request, authenticationToken);

  OAuth2AccessToken token = imageTokenServices.createAccessToken(auth);
  return token.getValue();
}
 
Example #9
Source File: OAuth2AuthorizationServerConfig.java    From NFVO with Apache License 2.0 6 votes vote down vote up
private OAuth2Request buildOAuth2Request(String serviceName, Set<GrantedAuthority> authorities) {
  Map<String, String> requestParameters = new HashMap<>();
  Set<String> scopes = new HashSet<>(Arrays.asList("read", "write"));
  Set<String> resourceIds = new HashSet<>();
  Set<String> responseTypes = new HashSet<>();
  responseTypes.add("code");
  Map<String, Serializable> extensionProperties = new HashMap<>();

  return new OAuth2Request(
      requestParameters,
      serviceName,
      authorities,
      true,
      scopes,
      resourceIds,
      null,
      responseTypes,
      extensionProperties);
}
 
Example #10
Source File: AuthenticationTest.java    From nakadi with MIT License 6 votes vote down vote up
@Bean
public ResourceServerTokenServices mockResourceTokenServices() {
    final ResourceServerTokenServices tokenServices = mock(ResourceServerTokenServices.class);

    when(tokenServices.loadAuthentication(any())).thenAnswer(invocation -> {

        final UsernamePasswordAuthenticationToken user = new UsernamePasswordAuthenticationToken("user", "N/A",
                AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER"));

        final String token = (String) invocation.getArguments()[0];
        final Set<String> scopes = ImmutableSet.copyOf(scopesForTokens.get(token));
        final Map<String, Object> details = new HashMap<>();
        details.put("realm", realms.get(token));
        user.setDetails(details);

        final OAuth2Request request = new OAuth2Request(null, null, null, true, scopes, null, null, null, null);

        return new OAuth2Authentication(request, user);
    });
    return tokenServices;
}
 
Example #11
Source File: FacebookAccessTokenConverter.java    From geowave with Apache License 2.0 6 votes vote down vote up
@Override
public OAuth2Authentication extractAuthentication(final Map<String, ?> map) {
  final Map<String, String> parameters = new HashMap<>();
  final Set<String> scope = parseScopes(map);
  final Object principal = map.get("name");
  final Authentication user =
      new UsernamePasswordAuthenticationToken(principal, "N/A", defaultAuthorities);
  final String clientId = (String) map.get(CLIENT_ID);
  parameters.put(CLIENT_ID, clientId);
  final Set<String> resourceIds =
      new LinkedHashSet<>(
          map.containsKey(AUD) ? (Collection<String>) map.get(AUD)
              : Collections.<String>emptySet());
  final OAuth2Request request =
      new OAuth2Request(parameters, clientId, null, true, scope, resourceIds, null, null, null);
  return new OAuth2Authentication(request, user);
}
 
Example #12
Source File: OpenHelper.java    From open-cloud with MIT License 6 votes vote down vote up
/**
 * 获取认证用户信息
 *
 * @return
 */
public static OpenUserDetails getUser() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication != null && authentication.isAuthenticated() && authentication instanceof OAuth2Authentication) {
        OAuth2Authentication oAuth2Authentication = (OAuth2Authentication) authentication;
        OAuth2Request clientToken = oAuth2Authentication.getOAuth2Request();
        if (!oAuth2Authentication.isClientOnly()) {
            if (authentication.getPrincipal() instanceof OpenUserDetails) {
                return (OpenUserDetails) authentication.getPrincipal();
            }
            if (authentication.getPrincipal() instanceof Map) {
                return BeanConvertUtils.mapToObject((Map) authentication.getPrincipal(), OpenUserDetails.class);
            }
        } else {
            OpenUserDetails openUser = new OpenUserDetails();
            openUser.setClientId(clientToken.getClientId());
            openUser.setAuthorities(clientToken.getAuthorities());
            return openUser;
        }
    }
    return null;
}
 
Example #13
Source File: OAuthHelper.java    From resource-server-testing with MIT License 6 votes vote down vote up
public OAuth2Authentication oAuth2Authentication(final String clientId, final String username) {
	// Look up authorities, resourceIds and scopes based on clientId
	ClientDetails client = clientDetailsService.loadClientByClientId(clientId);
	Collection<GrantedAuthority> authorities = client.getAuthorities();
	Set<String> resourceIds = client.getResourceIds();
	Set<String> scopes = client.getScope();

	// Default values for other parameters
	Map<String, String> requestParameters = Collections.emptyMap();
	boolean approved = true;
	String redirectUrl = null;
	Set<String> responseTypes = Collections.emptySet();
	Map<String, Serializable> extensionProperties = Collections.emptyMap();

	// Create request
	OAuth2Request oAuth2Request = new OAuth2Request(requestParameters, clientId, authorities, approved, scopes, resourceIds, redirectUrl, responseTypes, extensionProperties);

	// Create OAuth2AccessToken
	UserDetails user = userDetailsService.loadUserByUsername(username);
	UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user, null, authorities);
	OAuth2Authentication auth = new OAuth2Authentication(oAuth2Request, authenticationToken);
	return auth;
}
 
Example #14
Source File: MongoTokenStoreTest.java    From konker-platform with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {

    OAuth2AccessToken token = new DefaultOAuth2AccessToken(TOKEN);

    // check if token not exists
    oAuth2AccessToken = mongoTokenStore.readAccessToken(TOKEN);
    assertThat(oAuth2AccessToken, nullValue());

    // create token
    Set<String> scopes = new HashSet<>();
    scopes.add("read");

    OAuth2Request storedRequest = new OAuth2Request(
            new HashMap<>(),
            CLIENT_ID,
            new LinkedList<GrantedAuthority>(),
            true,
            scopes,
            new HashSet<String>(),
            null,
            null,
            null
    );

    Authentication userAuthentication = new PreAuthenticatedAuthenticationToken(null, null);
    authentication = new OAuth2Authentication(storedRequest, userAuthentication);

    mongoTokenStore.storeAccessToken(token, authentication);

}
 
Example #15
Source File: OAuth2TokenMockUtil.java    From cubeai with Apache License 2.0 5 votes vote down vote up
private OAuth2Authentication createAuthentication(String username, Set<String> scopes, Set<String> roles) {
    List<GrantedAuthority> authorities = roles.stream()
        .map(SimpleGrantedAuthority::new)
        .collect(Collectors.toList());

    User principal = new User(username, "test", true, true, true, true, authorities);
    Authentication authentication = new UsernamePasswordAuthenticationToken(principal, principal.getPassword(),
        principal.getAuthorities());

    // Create the authorization request and OAuth2Authentication object
    OAuth2Request authRequest = new OAuth2Request(null, "testClient", null, true, scopes, null, null, null,
        null);
    return new OAuth2Authentication(authRequest, authentication);
}
 
Example #16
Source File: OAuth2TokenMockUtil.java    From cubeai with Apache License 2.0 5 votes vote down vote up
private OAuth2Authentication createAuthentication(String username, Set<String> scopes, Set<String> roles) {
    List<GrantedAuthority> authorities = roles.stream()
        .map(SimpleGrantedAuthority::new)
        .collect(Collectors.toList());

    User principal = new User(username, "test", true, true, true, true, authorities);
    Authentication authentication = new UsernamePasswordAuthenticationToken(principal, principal.getPassword(),
        principal.getAuthorities());

    // Create the authorization request and OAuth2Authentication object
    OAuth2Request authRequest = new OAuth2Request(null, "testClient", null, true, scopes, null, null, null,
        null);
    return new OAuth2Authentication(authRequest, authentication);
}
 
Example #17
Source File: CustomUserInfoTokenServices.java    From DAFramework with MIT License 5 votes vote down vote up
private OAuth2Authentication extractAuthentication(Map<String, Object> map) {
	Object principal = getPrincipal(map);
	OAuth2Request request = getRequest(map);
	List<GrantedAuthority> authorities = authoritiesExtractor.extractAuthorities(map);
	UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(principal, "N/A", authorities);
	token.setDetails(map);
	return new OAuth2Authentication(request, token);
}
 
Example #18
Source File: RedisTokensServiceImpl.java    From microservices-platform with Apache License 2.0 5 votes vote down vote up
@Override
public PageResult<TokenVo> listTokens(Map<String, Object> params, String clientId) {
    Integer page = MapUtils.getInteger(params, "page");
    Integer limit = MapUtils.getInteger(params, "limit");
    int[] startEnds = PageUtil.transToStartEnd(page, limit);
    //根据请求参数生成redis的key
    String redisKey = getRedisKey(params, clientId);
    long size = redisRepository.length(redisKey);
    List<TokenVo> result = new ArrayList<>(limit);
    //查询token集合
    List<Object> tokenObjs = redisRepository.getList(redisKey, startEnds[0], startEnds[1]-1);
    if (tokenObjs != null) {
        for (Object obj : tokenObjs) {
            DefaultOAuth2AccessToken accessToken = (DefaultOAuth2AccessToken)obj;
            //构造token对象
            TokenVo tokenVo = new TokenVo();
            tokenVo.setTokenValue(accessToken.getValue());
            tokenVo.setExpiration(accessToken.getExpiration());

            //获取用户信息
            Object authObj = redisRepository.get(SecurityConstants.REDIS_TOKEN_AUTH + accessToken.getValue());
            OAuth2Authentication authentication = (OAuth2Authentication)authObj;
            if (authentication != null) {
                OAuth2Request request = authentication.getOAuth2Request();
                tokenVo.setUsername(authentication.getName());
                tokenVo.setClientId(request.getClientId());
                tokenVo.setGrantType(request.getGrantType());
            }

            result.add(tokenVo);
        }
    }
    return PageResult.<TokenVo>builder().data(result).code(0).count(size).build();
}
 
Example #19
Source File: CustomUserInfoTokenServices.java    From DAFramework with MIT License 5 votes vote down vote up
@SuppressWarnings({ "unchecked" })
private OAuth2Request getRequest(Map<String, Object> map) {
	Map<String, Object> request = (Map<String, Object>) map.get("oauth2Request");

	String clientId = (String) request.get("clientId");
	Set<String> scope = new LinkedHashSet<>(request.containsKey("scope")
			? (Collection<String>) request.get("scope")
			: Collections.<String> emptySet());

	return new OAuth2Request(null, clientId, null, true, new HashSet<>(scope), null, null, null, null);
}
 
Example #20
Source File: CustomUserInfoTokenServices.java    From microservice-skeleton with MIT License 5 votes vote down vote up
private OAuth2Authentication extractAuthentication(Map<String, Object> map) {
    Object principal = this.getPrincipal(map);
    List<GrantedAuthority> authorities = getAuthorities(map);

    OAuth2Request request = new OAuth2Request((Map) null, this.clientId, authorities, true, (Set) null, (Set) null, (String) null, (Set) null, (Map) null);
    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(principal, "N/A", authorities);
    token.setDetails(map);
    return new OAuth2Authentication(request, token);
}
 
Example #21
Source File: DiscordTokenServices.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
public OAuth2Authentication load(String accessToken) {
    Map map = executeRequest(Map.class,
            apiProperties.getDiscord().getUserInfoUri(), accessToken);
    Object principal = map.get("username");
    principal = (principal == null ? "unknown" : principal);
    List<GrantedAuthority> authorities = authoritiesExtractor.extractAuthorities(map);
    OAuth2Request request = new OAuth2Request(null,
            apiProperties.getDiscord().getClientId(), null, true, null,
            null, null, null, null);
    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
            principal, "N/A", authorities);
    token.setDetails(DiscordUserDetails.create(map));
    return new OAuth2Authentication(request, token);
}
 
Example #22
Source File: OAuth2AccessTokenService.java    From konker-platform with Apache License 2.0 5 votes vote down vote up
public ServiceResponse<OAuth2AccessToken> getAccessToken(Tenant tenant, Application application, OauthClientDetails clientDetails) {

        Role gatewayRole;
        if (clientDetails.getClientId().contains("gateway")) {
            gatewayRole = roleRepository.findByName(RoleService.ROLE_IOT_GATEWAY);
        } else {
            gatewayRole = roleRepository.findByName(RoleService.ROLE_IOT_USER);
        }

        Set<GrantedAuthority> authorities = new HashSet<>();
        for (Privilege privilege : gatewayRole.getPrivileges()) {
            authorities.add(new SimpleGrantedAuthority(privilege.getName()));
        }

        Set<String> scopes = new HashSet<>();
        scopes.add("read");
        scopes.add("write");

        OAuth2Request authorizationRequest = new OAuth2Request(
                null, clientDetails.getClientId(),
                authorities, true, scopes, null, "",
                null, null);

        OAuth2Authentication authenticationRequest = new OAuth2Authentication(
                authorizationRequest, null);
        authenticationRequest.setAuthenticated(true);

        OAuth2AccessToken accessToken = defaultTokenServices.createAccessToken(authenticationRequest);

        return ServiceResponseBuilder.<OAuth2AccessToken>ok()
                .withResult(accessToken)
                .build();

    }
 
Example #23
Source File: AppUserInfoTokenServices.java    From template-spring-boot-oauth2-wso2-is with Apache License 2.0 5 votes vote down vote up
private OAuth2Authentication extractAuthentication(Map<String, Object> map) {
	Object principal = getPrincipal(map);
	List<GrantedAuthority> authorities = this.authoritiesExtractor
			.extractAuthorities(map);
	OAuth2Request request = new OAuth2Request(null, this.clientId, null, true, null,
			null, null, null, null);
	UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
			principal, "N/A", authorities);
	token.setDetails(map);
	return new OAuth2Authentication(request, token);
}
 
Example #24
Source File: OAuth2TokenMockUtil.java    From tutorials with MIT License 5 votes vote down vote up
private OAuth2Authentication createAuthentication(String username, Set<String> scopes, Set<String> roles) {
    List<GrantedAuthority> authorities = roles.stream()
        .map(SimpleGrantedAuthority::new)
        .collect(Collectors.toList());

    User principal = new User(username, "test", true, true, true, true, authorities);
    Authentication authentication = new UsernamePasswordAuthenticationToken(principal, principal.getPassword(),
        principal.getAuthorities());

    // Create the authorization request and OAuth2Authentication object
    OAuth2Request authRequest = new OAuth2Request(null, "testClient", null, true, scopes, null, null, null,
        null);
    return new OAuth2Authentication(authRequest, authentication);
}
 
Example #25
Source File: _OAuth2AuthenticationReadConverter.java    From jhipster-ribbon-hystrix with GNU General Public License v3.0 5 votes vote down vote up
@Override
public OAuth2Authentication convert(DBObject source) {
    DBObject storedRequest = (DBObject)source.get("storedRequest");
    OAuth2Request oAuth2Request = new OAuth2Request((Map<String, String>)storedRequest.get("requestParameters"),
            (String)storedRequest.get("clientId"), null, true, new HashSet((List)storedRequest.get("scope")),
            null, null, null, null);

    DBObject userAuthorization = (DBObject)source.get("userAuthentication");
    Object principal = getPrincipalObject(userAuthorization.get("principal"));
    Authentication userAuthentication = new UsernamePasswordAuthenticationToken(principal,
            userAuthorization.get("credentials"), getAuthorities((List) userAuthorization.get("authorities")));

    return new OAuth2Authentication(oAuth2Request,  userAuthentication );
}
 
Example #26
Source File: OAuth2TokenMockUtil.java    From tutorials with MIT License 5 votes vote down vote up
private OAuth2Authentication createAuthentication(String username, Set<String> scopes, Set<String> roles) {
    List<GrantedAuthority> authorities = roles.stream()
        .map(SimpleGrantedAuthority::new)
        .collect(Collectors.toList());

    User principal = new User(username, "test", true, true, true, true, authorities);
    Authentication authentication = new UsernamePasswordAuthenticationToken(principal, principal.getPassword(),
        principal.getAuthorities());

    // Create the authorization request and OAuth2Authentication object
    OAuth2Request authRequest = new OAuth2Request(null, "testClient", null, true, scopes, null, null, null,
        null);
    return new OAuth2Authentication(authRequest, authentication);
}
 
Example #27
Source File: OAuth2TokenMockUtil.java    From tutorials with MIT License 5 votes vote down vote up
private OAuth2Authentication createAuthentication(String username, Set<String> scopes, Set<String> roles) {
    List<GrantedAuthority> authorities = roles.stream()
        .map(SimpleGrantedAuthority::new)
        .collect(Collectors.toList());

    User principal = new User(username, "test", true, true, true, true, authorities);
    Authentication authentication = new UsernamePasswordAuthenticationToken(principal, principal.getPassword(),
        principal.getAuthorities());

    // Create the authorization request and OAuth2Authentication object
    OAuth2Request authRequest = new OAuth2Request(null, "testClient", null, true, scopes, null, null, null,
        null);
    return new OAuth2Authentication(authRequest, authentication);
}
 
Example #28
Source File: OAuth2RequestBuilder.java    From spring-security-mongo with MIT License 5 votes vote down vote up
public OAuth2Request build() {
    return new OAuth2Request(requestParameters,
            clientId,
            authorities,
            approved,
            scope,
            resourceIds,
            redirectUri,
            responseTypes,
            extensionProperties);
}
 
Example #29
Source File: ShibbolethAcrAwareTokenService.java    From shibboleth-oidc with Apache License 2.0 5 votes vote down vote up
/**
 * Calculate auth time claim.
 *
 * @param request  the request
 * @param idClaims the id claims
 */
private void calculateAuthTimeClaim(final OAuth2Request request, final JWTClaimsSet.Builder idClaims) {
    final long authTime = Long.parseLong(
            request.getExtensions().get(OIDCConstants.AUTH_TIME).toString()) / 1000;
    log.debug("Request contains {} extension. {} set to {}",
            ConnectRequestParameters.MAX_AGE, OIDCConstants.AUTH_TIME, authTime);
    idClaims.claim(OIDCConstants.AUTH_TIME, authTime);
}
 
Example #30
Source File: ShibbolethAcrAwareTokenService.java    From shibboleth-oidc with Apache License 2.0 5 votes vote down vote up
/**
 * Calculate nonce claim.
 *
 * @param request  the request
 * @param idClaims the id claims
 */
private void calculateNonceClaim(final OAuth2Request request, final JWTClaimsSet.Builder idClaims) {
    final String nonce = (String) request.getExtensions().get(ConnectRequestParameters.NONCE);
    if (!Strings.isNullOrEmpty(nonce)) {
        idClaims.claim(ConnectRequestParameters.NONCE, nonce);
        log.debug("{} is set to {}", ConnectRequestParameters.NONCE, nonce);
    }
}