Search in sources :

Example 6 with TokenSettings

use of org.springframework.security.oauth2.server.authorization.config.TokenSettings in project spring-authorization-server by spring-projects.

the class OidcClientRegistrationAuthenticationProvider method createClient.

private static RegisteredClient createClient(OidcClientRegistration clientRegistration) {
    // @formatter:off
    RegisteredClient.Builder builder = RegisteredClient.withId(UUID.randomUUID().toString()).clientId(CLIENT_ID_GENERATOR.generateKey()).clientIdIssuedAt(Instant.now()).clientSecret(CLIENT_SECRET_GENERATOR.generateKey()).clientName(clientRegistration.getClientName());
    if (ClientAuthenticationMethod.CLIENT_SECRET_POST.getValue().equals(clientRegistration.getTokenEndpointAuthenticationMethod())) {
        builder.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_POST);
    } else if (ClientAuthenticationMethod.CLIENT_SECRET_JWT.getValue().equals(clientRegistration.getTokenEndpointAuthenticationMethod())) {
        builder.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_JWT);
    } else if (ClientAuthenticationMethod.PRIVATE_KEY_JWT.getValue().equals(clientRegistration.getTokenEndpointAuthenticationMethod())) {
        builder.clientAuthenticationMethod(ClientAuthenticationMethod.PRIVATE_KEY_JWT);
    } else {
        builder.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC);
    }
    builder.redirectUris(redirectUris -> redirectUris.addAll(clientRegistration.getRedirectUris()));
    if (!CollectionUtils.isEmpty(clientRegistration.getGrantTypes())) {
        builder.authorizationGrantTypes(authorizationGrantTypes -> clientRegistration.getGrantTypes().forEach(grantType -> authorizationGrantTypes.add(new AuthorizationGrantType(grantType))));
    } else {
        builder.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE);
    }
    if (CollectionUtils.isEmpty(clientRegistration.getResponseTypes()) || clientRegistration.getResponseTypes().contains(OAuth2AuthorizationResponseType.CODE.getValue())) {
        builder.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE);
    }
    if (!CollectionUtils.isEmpty(clientRegistration.getScopes())) {
        builder.scopes(scopes -> scopes.addAll(clientRegistration.getScopes()));
    }
    ClientSettings.Builder clientSettingsBuilder = ClientSettings.builder().requireProofKey(true).requireAuthorizationConsent(true);
    if (ClientAuthenticationMethod.CLIENT_SECRET_JWT.getValue().equals(clientRegistration.getTokenEndpointAuthenticationMethod())) {
        MacAlgorithm macAlgorithm = MacAlgorithm.from(clientRegistration.getTokenEndpointAuthenticationSigningAlgorithm());
        if (macAlgorithm == null) {
            macAlgorithm = MacAlgorithm.HS256;
        }
        clientSettingsBuilder.tokenEndpointAuthenticationSigningAlgorithm(macAlgorithm);
    } else if (ClientAuthenticationMethod.PRIVATE_KEY_JWT.getValue().equals(clientRegistration.getTokenEndpointAuthenticationMethod())) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.from(clientRegistration.getTokenEndpointAuthenticationSigningAlgorithm());
        if (signatureAlgorithm == null) {
            signatureAlgorithm = SignatureAlgorithm.RS256;
        }
        clientSettingsBuilder.tokenEndpointAuthenticationSigningAlgorithm(signatureAlgorithm);
        clientSettingsBuilder.jwkSetUrl(clientRegistration.getJwkSetUrl().toString());
    }
    builder.clientSettings(clientSettingsBuilder.build()).tokenSettings(TokenSettings.builder().idTokenSignatureAlgorithm(SignatureAlgorithm.RS256).build());
    return builder.build();
// @formatter:on
}
Also used : UriComponentsBuilder(org.springframework.web.util.UriComponentsBuilder) OAuth2TokenGenerator(org.springframework.security.oauth2.server.authorization.OAuth2TokenGenerator) URISyntaxException(java.net.URISyntaxException) RegisteredClientRepository(org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository) Autowired(org.springframework.beans.factory.annotation.Autowired) AuthenticationProvider(org.springframework.security.authentication.AuthenticationProvider) ClaimAccessor(org.springframework.security.oauth2.core.ClaimAccessor) AbstractOAuth2TokenAuthenticationToken(org.springframework.security.oauth2.server.resource.authentication.AbstractOAuth2TokenAuthenticationToken) MacAlgorithm(org.springframework.security.oauth2.jose.jws.MacAlgorithm) AuthenticationException(org.springframework.security.core.AuthenticationException) URI(java.net.URI) StringKeyGenerator(org.springframework.security.crypto.keygen.StringKeyGenerator) ProviderSettings(org.springframework.security.oauth2.server.authorization.config.ProviderSettings) Collection(java.util.Collection) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) Set(java.util.Set) JwtGenerator(org.springframework.security.oauth2.server.authorization.JwtGenerator) UUID(java.util.UUID) Instant(java.time.Instant) DefaultOAuth2TokenContext(org.springframework.security.oauth2.server.authorization.DefaultOAuth2TokenContext) ProviderContextHolder(org.springframework.security.oauth2.server.authorization.context.ProviderContextHolder) Base64(java.util.Base64) List(java.util.List) Base64StringKeyGenerator(org.springframework.security.crypto.keygen.Base64StringKeyGenerator) CollectionUtils(org.springframework.util.CollectionUtils) OAuth2TokenContext(org.springframework.security.oauth2.server.authorization.OAuth2TokenContext) ProviderContext(org.springframework.security.oauth2.server.authorization.context.ProviderContext) Authentication(org.springframework.security.core.Authentication) OAuth2Token(org.springframework.security.oauth2.core.OAuth2Token) OAuth2ParameterNames(org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames) OidcClientMetadataClaimNames(org.springframework.security.oauth2.core.oidc.OidcClientMetadataClaimNames) OAuth2AuthorizationResponseType(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponseType) OAuth2ClientAuthenticationToken(org.springframework.security.oauth2.server.authorization.authentication.OAuth2ClientAuthenticationToken) TokenSettings(org.springframework.security.oauth2.server.authorization.config.TokenSettings) JwtEncoder(org.springframework.security.oauth2.jwt.JwtEncoder) HashSet(java.util.HashSet) ClientAuthenticationMethod(org.springframework.security.oauth2.core.ClientAuthenticationMethod) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) ClientSettings(org.springframework.security.oauth2.server.authorization.config.ClientSettings) OAuth2Authorization(org.springframework.security.oauth2.server.authorization.OAuth2Authorization) RegisteredClient(org.springframework.security.oauth2.server.authorization.client.RegisteredClient) OAuth2ErrorCodes(org.springframework.security.oauth2.core.OAuth2ErrorCodes) OAuth2AuthorizationService(org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService) SignatureAlgorithm(org.springframework.security.oauth2.jose.jws.SignatureAlgorithm) OAuth2TokenType(org.springframework.security.oauth2.core.OAuth2TokenType) OidcClientRegistration(org.springframework.security.oauth2.core.oidc.OidcClientRegistration) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) Collections(java.util.Collections) AuthorizationGrantType(org.springframework.security.oauth2.core.AuthorizationGrantType) Assert(org.springframework.util.Assert) StringUtils(org.springframework.util.StringUtils) MacAlgorithm(org.springframework.security.oauth2.jose.jws.MacAlgorithm) AuthorizationGrantType(org.springframework.security.oauth2.core.AuthorizationGrantType) ClientSettings(org.springframework.security.oauth2.server.authorization.config.ClientSettings) SignatureAlgorithm(org.springframework.security.oauth2.jose.jws.SignatureAlgorithm) RegisteredClient(org.springframework.security.oauth2.server.authorization.client.RegisteredClient)

Example 7 with TokenSettings

use of org.springframework.security.oauth2.server.authorization.config.TokenSettings in project herodotus-engine by herodotus-cloud.

the class OAuth2ApplicationService method createTokenSettings.

private TokenSettings createTokenSettings(OAuth2Application application) {
    TokenSettings.Builder tokenSettingsBuilder = TokenSettings.builder();
    // accessToken 的有效期
    tokenSettingsBuilder.accessTokenTimeToLive(application.getAccessTokenValidity());
    // refreshToken 的有效期
    tokenSettingsBuilder.refreshTokenTimeToLive(application.getRefreshTokenValidity());
    // 是否可重用刷新令牌
    tokenSettingsBuilder.reuseRefreshTokens(application.getReuseRefreshTokens());
    tokenSettingsBuilder.accessTokenFormat(new OAuth2TokenFormat(application.getAccessTokenFormat().getFormat()));
    if (ObjectUtils.isNotEmpty(application.getIdTokenSignatureAlgorithm())) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.from(application.getIdTokenSignatureAlgorithm().name());
        if (ObjectUtils.isNotEmpty(signatureAlgorithm)) {
            tokenSettingsBuilder.idTokenSignatureAlgorithm(signatureAlgorithm);
        }
    }
    return tokenSettingsBuilder.build();
}
Also used : TokenSettings(org.springframework.security.oauth2.server.authorization.config.TokenSettings) SignatureAlgorithm(org.springframework.security.oauth2.jose.jws.SignatureAlgorithm) OAuth2TokenFormat(org.springframework.security.oauth2.core.OAuth2TokenFormat)

Example 8 with TokenSettings

use of org.springframework.security.oauth2.server.authorization.config.TokenSettings in project best-cloud by shanzhaozhen.

the class AuthorizationServerConfig method registeredClientRepository.

/**
 * 配置客户端
 * @return
 */
@Bean
public RegisteredClientRepository registeredClientRepository(JdbcTemplate jdbcTemplate) {
    // 使用内存作为客户端的信息库
    // RegisteredClient registeredClient = RegisteredClient.withId(UUID.randomUUID().toString())
    // // 客户端id 需要唯一
    // .clientId("auth")
    // // 客户端密码
    // .clientSecret("123456")
    // // 可以基于 basic 的方式和授权服务器进行认证
    // .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
    // // 授权码
    // .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
    // // 刷新token
    // .authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN)
    // // 客户端模式
    // .authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS)
    // // 密码模式
    // .authorizationGrantType(AuthorizationGrantType.PASSWORD)
    // // 重定向url
    // // 回调地址名单,不在此列将被拒绝 而且只能使用IP或者域名  不能使用 localhost
    // .redirectUri("http://127.0.0.1:8080/login/oauth2/code/messaging-client-oidc")
    // .redirectUri("http://127.0.0.1:8080/authorized")
    // .redirectUri("http://www.baidu.com")
    // // 客户端申请的作用域,也可以理解这个客户端申请访问用户的哪些信息,比如:获取用户信息,获取用户照片等
    // // OIDC支持
    // .scope(OidcScopes.OPENID)
    // // 其它Scope
    // .scope("all")
    // .scope("message.read")
    // .scope("message.write")
    // .clientSettings(ClientSettings
    // .builder()
    // // 是否需要用户确认一下客户端需要获取用户的哪些权限
    // // 比如:客户端需要获取用户的 用户信息、用户照片 但是此处用户可以控制只给客户端授权获取 用户信息。
    // // 配置客户端相关的配置项,包括验证密钥或者 是否需要授权页面
    // .requireAuthorizationConsent(true).build())
    // .tokenSettings(TokenSettings.builder()
    // // accessToken 的有效期
    // .accessTokenTimeToLive(Duration.ofHours(1))
    // // refreshToken 的有效期
    // .refreshTokenTimeToLive(Duration.ofDays(3))
    // // 是否可重用刷新令牌
    // .reuseRefreshTokens(true)
    // .build()
    // )
    // .build();
    // return new InMemoryRegisteredClientRepository(registeredClient);
    // return new JdbcRegisteredClientRepository(jdbcTemplate);
    // 使用数据库作为客户端的信息库
    // JdbcRegisteredClientRepository jdbcRegisteredClientRepository = new JdbcRegisteredClientRepository(jdbcTemplate);
    // jdbcRegisteredClientRepository.save(registeredClient);
    // return jdbcRegisteredClientRepository;
    JdbcRegisteredClientRepository jdbcRegisteredClientRepository = new JdbcRegisteredClientRepository(jdbcTemplate);
    // 解决json 反序列化 白名单问题
    JdbcRegisteredClientRepository.RegisteredClientRowMapper registeredClientRowMapper = new JdbcRegisteredClientRepository.RegisteredClientRowMapper();
    registeredClientRowMapper.setObjectMapper(SecurityJacksonConfig.objectMapper);
    jdbcRegisteredClientRepository.setRegisteredClientRowMapper(registeredClientRowMapper);
    return jdbcRegisteredClientRepository;
}
Also used : JdbcRegisteredClientRepository(org.springframework.security.oauth2.server.authorization.client.JdbcRegisteredClientRepository) Bean(org.springframework.context.annotation.Bean)

Example 9 with TokenSettings

use of org.springframework.security.oauth2.server.authorization.config.TokenSettings in project muses by acgist.

the class AuthorizationServerConfig method registeredClientRepository.

/**
 * 注意ID不能随机生成否者重启之后Redis不能正确加载
 *
 * 如果需要指定重定向地址不能使用localhost等等本地回环地址
 * 正确跳转:http://localhost:9999/oauth2/authorize?response_type=code&client_id=web&client_secret=acgist&scope=all&state=state
 * 不能跳转:http://localhost:9999/oauth2/authorize?response_type=code&client_id=web&client_secret=acgist&scope=all&state=state&redirect_uri=http://localhost:9999/code
 */
@Bean
@ConditionalOnMissingBean
public RegisteredClientRepository registeredClientRepository(PasswordEncoder passwordEncoder) {
    final TokenSettings tokenSettings = this.tokenSettings();
    final List<RegisteredClient> clients = new ArrayList<>();
    this.oAuth2Config.getClients().forEach((name, secret) -> {
        log.info("注册授权客户端:{}", name);
        final RegisteredClient client = RegisteredClient.withId(name).clientId(name).clientSecret(passwordEncoder.encode(secret)).clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC).authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE).authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN).redirectUri(this.redirectUrl(name)).tokenSettings(tokenSettings).scope("all").build();
        clients.add(client);
    });
    return new InMemoryRegisteredClientRepository(clients);
}
Also used : InMemoryRegisteredClientRepository(org.springframework.security.oauth2.server.authorization.client.InMemoryRegisteredClientRepository) TokenSettings(org.springframework.security.oauth2.server.authorization.config.TokenSettings) ArrayList(java.util.ArrayList) RegisteredClient(org.springframework.security.oauth2.server.authorization.client.RegisteredClient) ConditionalOnMissingBean(org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean) ConditionalOnMissingBean(org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean) Bean(org.springframework.context.annotation.Bean)

Example 10 with TokenSettings

use of org.springframework.security.oauth2.server.authorization.config.TokenSettings in project platform-base by SummerWindL.

the class AuthorizationConfig method registeredClientRepository.

/**
 * 创建客户端信息,可以保存在内存和数据库,此处保存在数据库中
 */
@Bean
public RegisteredClientRepository registeredClientRepository(JdbcTemplate jdbcTemplate) {
    RegisteredClient registeredClient = RegisteredClient.withId(UUID.randomUUID().toString()).clientId("csdn").clientSecret("csdn123").clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC).authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE).authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN).authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS).authorizationGrantType(AuthorizationGrantType.PASSWORD).authorizationGrantType(AuthorizationGrantType.IMPLICIT).redirectUri("https://www.baidu.com").scope("user.userInfo").scope("user.photos").clientSettings(ClientSettings.builder().requireAuthorizationConsent(true).build()).tokenSettings(TokenSettings.builder().accessTokenTimeToLive(Duration.ofHours(1)).refreshTokenTimeToLive(Duration.ofDays(3)).reuseRefreshTokens(true).build()).build();
    JdbcRegisteredClientRepository jdbcRegisteredClientRepository = new JdbcRegisteredClientRepository(jdbcTemplate);
    if (null == jdbcRegisteredClientRepository.findByClientId("csdn")) {
        jdbcRegisteredClientRepository.save(registeredClient);
    }
    return jdbcRegisteredClientRepository;
}
Also used : JdbcRegisteredClientRepository(org.springframework.security.oauth2.server.authorization.client.JdbcRegisteredClientRepository) RegisteredClient(org.springframework.security.oauth2.server.authorization.client.RegisteredClient) Bean(org.springframework.context.annotation.Bean)

Aggregations

RegisteredClient (org.springframework.security.oauth2.server.authorization.client.RegisteredClient)17 Test (org.junit.Test)13 TokenSettings (org.springframework.security.oauth2.server.authorization.config.TokenSettings)10 OAuth2Authorization (org.springframework.security.oauth2.server.authorization.OAuth2Authorization)8 Bean (org.springframework.context.annotation.Bean)5 OAuth2TokenFormat (org.springframework.security.oauth2.core.OAuth2TokenFormat)5 Instant (java.time.Instant)4 OAuth2TokenType (org.springframework.security.oauth2.core.OAuth2TokenType)4 SignatureAlgorithm (org.springframework.security.oauth2.jose.jws.SignatureAlgorithm)4 Authentication (org.springframework.security.core.Authentication)3 AuthorizationGrantType (org.springframework.security.oauth2.core.AuthorizationGrantType)3 ClientAuthenticationMethod (org.springframework.security.oauth2.core.ClientAuthenticationMethod)3 OAuth2AuthorizationRequest (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest)3 Principal (java.security.Principal)2 ArrayList (java.util.ArrayList)2 Collections (java.util.Collections)2 HashMap (java.util.HashMap)2 HashSet (java.util.HashSet)2 List (java.util.List)2 Map (java.util.Map)2