Add a custom header to OAuth2 authentication in Springfox Swagger - swagger

I'm trying to add a custom header to the OAuth Security Scheme (Springfox Swagger 2.8.0).
Any ideas how this could be achieved?
My current configuration (using OAuth with ImplicitGrant, server side is keycloak) looks like:
#Bean
public SecurityContext securityContext() {
return SecurityContext.builder().securityReferences(defaultAuth()).build();
}
private List<SecurityReference> defaultAuth() {
return Arrays.asList(new SecurityReference(SECURITY_SCHEME_OAUTH2, defaultScope().toArray(new AuthorizationScope[] {})));
}
private Predicate<String> postPaths() {
return regex("/.*");
}
private Predicate<String> springBootActuatorJmxPaths() {
return regex("^/(?!env|restart|pause|resume|refresh).*$");
}
private List<AuthorizationScope> defaultScope() {
AuthorizationScope authorizationScope = new AuthorizationScope("openid", "Basic Open ID Connect Scope");
List<AuthorizationScope> authorizationScopes = new ArrayList<>();
authorizationScopes.add(authorizationScope);
return authorizationScopes;
}
#Bean
public Docket postsApi(List<SecurityContext> securityContexts) {
return new Docket(DocumentationType.SWAGGER_2).groupName("public-api")
.apiInfo(apiInfo()).select().paths(postPaths())
.apis(RequestHandlerSelectors.basePackage("com.example"))
.paths(springBootActuatorJmxPaths())
.build()
.securitySchemes(Collections.singletonList(oauth()))
.securityContexts(securityContexts)
;
}
#Bean
List<GrantType> grantTypes() {
List<GrantType> grantTypes = new ArrayList<>();
grantTypes.add(
new ImplicitGrant(
new LoginEndpoint(oAuthServerUri + "/realms/" + REALM_NAME + "/protocol/openid-connect/auth"),
"access_token"
)
);
return grantTypes;
}
#Bean
SecurityScheme oauth() {
return new OAuthBuilder()
.name(SECURITY_SCHEME_OAUTH2)
.scopes(defaultScope())
.grantTypes(grantTypes())
.build();
}
#Bean
public SecurityConfiguration securityInfo() {
return SecurityConfigurationBuilder.builder()
.clientId(clientId)
.realm(REALM_NAME)
.appName(serviceName)
.scopeSeparator(" ")
.build();
}

It's currently not possible in Springfox Swagger, more details here: https://github.com/springfox/springfox/issues/2266

Related

Spring webflux: ReactiveUserDetails is ignored

Here my security configuration:
#Configuration
#EnableWebFluxSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration {
#Bean
public ReactiveJwtDecoder reactiveJwtDecoder() throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKey = new SecretKeySpec("JAC1O17W1F3QB9E8B4B1MT6QKYOQB36V".getBytes(), mac.getAlgorithm());
return NimbusReactiveJwtDecoder.withSecretKey(secretKey)
.macAlgorithm(MacAlgorithm.HS256)
.build();
}
#Bean
public ReactiveUserDetailsService userDetailsService(
UsuariRepository usuariRepository,
UserDetailsMapper userDetailsMapper
) {
return new GitUserDetailsService(usuariRepository, userDetailsMapper);
}
#Bean
SecurityWebFilterChain springSecurityFilterChain(
ServerHttpSecurity http
) {
final CorsConfigurationSource configurationSource = serverWebExchange -> {
final var cc = new CorsConfiguration();
cc.addAllowedOrigin("*");
cc.addAllowedMethod("*");
cc.addAllowedHeader("*");
return cc;
};
Customizer<CorsSpec> corsCustomizer = (corsSpec) -> corsSpec.configurationSource(configurationSource);
return http
.httpBasic(HttpBasicSpec::disable)
.cors(corsCustomizer)
.csrf(CsrfSpec::disable)
.formLogin(FormLoginSpec::disable)
.anonymous(AnonymousSpec::disable)
.logout(LogoutSpec::disable)
.authorizeExchange((authorize) -> authorize
.pathMatchers("/actuator/**").permitAll()
.pathMatchers("/gicar/**").permitAll()
.anyExchange().authenticated()
)
.oauth2ResourceServer(OAuth2ResourceServerSpec::jwt)
.build();
}
}
As you can see, I'm trying to use my UserDetailsService in order to load user details form database.
Into my methods, I'm using:
#RestController
#RequestMapping(value = "/qdcf")
public class QdCFController {
private final QdCFService qdcfService;
#PreAuthorize("hasRole('ADMIN')")
#GetMapping
public Mono<PageableResponseModel<QdCFPresenter>> all(Pageable pageable) {
return this.qdcfService.getQdCFs(pageable);
}
}
I'm trying to reach my code using this request:
curl -s -X GET "http://$BACKEND/qdcf" -H "Authorization: Bearer $JWT_TOKEN"
I was expecting ReactiveUserDetailsService was called. But it's ignored.
Any ideas?
Replace #EnableGlobalMethodSecurity(prePostEnabled = true) with #EnableReactiveMethodSecurity. First one is for non reactive spring security.

SpringDoc OIDC: how to show only Implicit Flow among the available authorizations?

I'm trying to configure SpringDoc/Swagger-UI in order to show only the Implicit Flow
when clicking on the Authorize button.
However, it shows all the possible authorization methods supported by the IDAM,
as show at /.well-known/openid-configuration:
"grant_types_supported":["authorization_code","implicit","refresh_token","password","client_credentials","urn:ietf:params:oauth:grant-type:device_code","urn:openid:params:grant-type:ciba"]
authorization_code
implicit
refresh_token
password
client_credentials
urn:ietf:params:oauth:grant-type:device_code
urn:openid:params:grant-type:ciba
This is my current configuration:
#Configuration
#RequiredArgsConstructor
public class OpenAPIConfiguration {
private final OAuth2Configuration oAuth2Configuration;
#Bean
public SecurityScheme securityScheme() {
String tokenIssuer = this.oAuth2Configuration.getIssuers().get(0);
String openIdConnectUrl = tokenIssuer + "/.well-known/openid-configuration";
OAuthFlow implicitOAuthFlow = new OAuthFlow();
return new SecurityScheme()
.name("OIDC-Auth")
.type(SecurityScheme.Type.OPENIDCONNECT)
.scheme("bearer")
.bearerFormat("jwt")
.in(SecurityScheme.In.HEADER)
.openIdConnectUrl(openIdConnectUrl)
.flows(new OAuthFlows().implicit(implicitOAuthFlow));
}
#Bean
public SecurityRequirement securityRequirement() {
return new SecurityRequirement().addList("OIDC-Auth");
}
#Bean
public OpenAPI openAPI(SecurityScheme securityScheme, SecurityRequirement securityRequirement) {
return new OpenAPI()
.info(new Info()
.title("MY API")
.version("1"))
.components(new Components()
.addSecuritySchemes(securityScheme.getName(), securityScheme))
.addSecurityItem(securityRequirement);
}
}
How can I limit the flows to be displayed on the UI?
The example below works for me:
...
private static final String PROTOCOL_OPENID_CONNECT = "%s/realms/%s/protocol/openid-connect";
#Bean
OpenAPI customOpenApi() {
return new OpenAPI()
.addServersItem(new Server().url(API_SERVER_URL))
.components(createOauth2SecurityScheme())
.security(createOauth2SecurityRequirement())
.info(createInfo());
}
private Components createOauth2SecurityScheme() {
return new Components().addSecuritySchemes("oAuth2", createOauth2Scheme());
}
private List<SecurityRequirement> createOauth2SecurityRequirement() {
return List.of(new SecurityRequirement().addList("oAuth2"));
}
private SecurityScheme createOauth2Scheme() {
String authUrl = String.format(PROTOCOL_OPENID_CONNECT, AUTH_SERVER_URL, REALM);
String tokenUrl = String.format(PROTOCOL_OPENID_CONNECT, AUTH_SERVER_URL, REALM);
return new SecurityScheme()
.type(SecurityScheme.Type.OAUTH2)
.description("OAuth2 Flow")
.flows(new OAuthFlows()
.authorizationCode(
new OAuthFlow()
.authorizationUrl(authUrl + "/auth")
.tokenUrl(tokenUrl + "/token")
.scopes(new Scopes())
));
}
...

RSocket Java Spring #AuthenticationPrincipal with JWT

How can we use #AuthenticationPrincipal with a RSocket Method #AuthenticationPrincipal Mono token
public Mono<String> uppercase(String s, #AuthenticationPrincipal Mono<JwtAuthenticationToken> token) {
//Token is always null
return Mono.just(s.toUpperCase());
}
I created a RSocketSecurityConfiguration class:
#Configuration
#EnableRSocketSecurity
#EnableReactiveMethodSecurity
#Slf4j
public class RSocketSecurityConfiguration {
#Value("${spring.security.oauth2.resourceserver.jwt.issuer-uri}")
private String issuerUri;
#Bean
PayloadSocketAcceptorInterceptor rsocketInterceptor(RSocketSecurity rsocket) {
rsocket
.authorizePayload(authorize ->
authorize
.anyRequest().authenticated()
.anyExchange().permitAll()
)
.jwt(jwtSpec -> {
jwtSpec.authenticationManager(jwtReactiveAuthenticationManager(reactiveJwtDecoder()));
});
return rsocket.build();
}
#Bean
ReactiveJwtDecoder reactiveJwtDecoder() {
NimbusReactiveJwtDecoder decoder = (NimbusReactiveJwtDecoder)
ReactiveJwtDecoders.fromOidcIssuerLocation(issuerUri);
return decoder;
}
#Bean
public JwtReactiveAuthenticationManager jwtReactiveAuthenticationManager(ReactiveJwtDecoder reactiveJwtDecoder) {
JwtReactiveAuthenticationManager jwtReactiveAuthenticationManager = new JwtReactiveAuthenticationManager(reactiveJwtDecoder);
JwtAuthenticationConverter authenticationConverter = new JwtAuthenticationConverter();
JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
jwtGrantedAuthoritiesConverter.setAuthorityPrefix("ROLE_");
authenticationConverter.setJwtGrantedAuthoritiesConverter(jwtGrantedAuthoritiesConverter);
jwtReactiveAuthenticationManager.setJwtAuthenticationConverter( new ReactiveJwtAuthenticationConverterAdapter(authenticationConverter));
return jwtReactiveAuthenticationManager;
}
#Bean
RSocketMessageHandler messageHandler(RSocketStrategies strategies) {
RSocketMessageHandler mh = new RSocketMessageHandler();
mh.getArgumentResolverConfigurer().addCustomResolver(new AuthenticationPrincipalArgumentResolver());
mh.setRSocketStrategies(strategies);
return mh;
}
Full UpperCaseController:
#Slf4j
#Controller
public class UpperCaseController {
#MessageMapping("uppercase")
public Mono<String> uppercase(String s, #AuthenticationPrincipal Mono<JwtAuthenticationToken> token) {
JwtAuthenticationToken currentToken = token.block();
if ( currentToken == null ) {
log.info("token is null");
}
return Mono.just(s.toUpperCase());
}
}
Full ConnectController:
#Slf4j
#Controller
public class ConnectController {
#ConnectMapping("connect")
void connectShellClientAndAskForTelemetry(RSocketRequester requester,
#Payload String client) {
requester.rsocket()
.onClose()
.doFirst(() -> {
// Add all new clients to a client list
log.info("Client: {} CONNECTED.", client);
})
.doOnError(error -> {
// Warn when channels are closed by clients
log.warn("Channel to client {} CLOSED", client);
})
.doFinally(consumer -> {
// Remove disconnected clients from the client list
log.info("Client {} DISCONNECTED", client);
})
.subscribe();
}
}
RSocket Client:
#Component
#Slf4j
public class RSocketClient {
private static final MimeType SIMPLE_AUTH = MimeTypeUtils.parseMimeType(WellKnownMimeType.MESSAGE_RSOCKET_AUTHENTICATION.getString());
MimeType BEARER_AUTH =
MimeTypeUtils.parseMimeType(WellKnownMimeType.MESSAGE_RSOCKET_AUTHENTICATION.getString());
private static final String BEARER_TOKEN = "....";
private final RSocketRequester requester;
private RSocketStrategies rsocketStrategies;
public RSocketClient(RSocketRequester.Builder requesterBuilder,
#Qualifier("rSocketStrategies") RSocketStrategies strategies) {
this.rsocketStrategies = strategies;
SocketAcceptor responder = RSocketMessageHandler.responder(rsocketStrategies, new RSocketClientHandler());
requester = requesterBuilder
.setupRoute("connect")
.setupData("MyTestClient")
.setupMetadata(new BearerTokenMetadata(BEARER_TOKEN), BEARER_AUTH)
.rsocketStrategies(builder ->
builder.encoder(new BearerTokenAuthenticationEncoder()))
.rsocketConnector(connector -> connector.acceptor(responder))
.connectTcp("localhost", 7000)
.block();
requester.rsocket()
.onClose()
.doOnError(error -> log.warn("Connection CLOSED"))
.doFinally(consumer -> log.info("Client DISCONNECTED"))
.subscribe();
}
public void uppercase() {
String response = requester
.route("uppercase")
.metadata(BEARER_TOKEN, BEARER_AUTH)
.data("Hello")
.retrieveMono(String.class).block();
log.info(response);
}
}
I have done something very similar for Spring REST and it works fine but for RSocket the token is always null.
I assume you have started with https://spring.io/blog/2020/06/17/getting-started-with-rsocket-spring-security
I was able to get this working for my codebase using a different type than #Payload
#ConnectMapping
fun handle(requester: RSocketRequester, #AuthenticationPrincipal jwt: String) {
logger.debug("connected $jwt")
}
#MessageMapping("runCommand")
suspend fun runCommand(request: CommandRequest, rSocketRequester: RSocketRequester, #AuthenticationPrincipal jwt: String): Flow<CommandResponse> {
...
}
I am using Keycloak as jwt Issuer. Just follow up this git repo. Only thing that didn't work for me is
#CurrentUserProfile Mono<UserProfile> currentUserProfile
Solution for that w.r.t above git repo will be using either of the below
#CurrentUserProfile Mono<Jwt> currentUserProfile
or directly use
#AuthenticationPrincipal Jwt currentUserProfile
Hope this will work for you. Enjoy!

How to override the OAuth2AuthorizationServerSecurity's config?

For this project.I want to build a OAuth2 Server on separate front-end and back-end architecture. The back-end based on [spring-authorization-server] while front-end based on VUE.
In the OAuth2 login flow ,it redirects to /login page, but i need to redirect to the vue front-end's login page such as "http://front-end ip:port/loginPage" .
How can I customize the authenticationEntryPoint in org.springframework.security.config.annotation.web.configuration.OAuth2AuthorizationServerSecurity like this:
.formLogin(withDefaults()).exceptionHandling().authenticationEntryPoint(xxx)
Any idea ?
NOTE: OAuth2AuthorizationServerSecurity has been removed. The code below is latest master.
The sample authorization server application has the following default configuration:
#Configuration(proxyBeanMethods = false)
#Import(OAuth2AuthorizationServerConfiguration.class)
public class AuthorizationServerConfig {
#Bean
public RegisteredClientRepository registeredClientRepository() {
RegisteredClient registeredClient = RegisteredClient.withId(UUID.randomUUID().toString())
.clientId("messaging-client")
.clientSecret("secret")
.clientAuthenticationMethod(ClientAuthenticationMethod.BASIC)
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS)
.redirectUri("http://localhost:8080/authorized")
.scope("message.read")
.scope("message.write")
.clientSettings(clientSettings -> clientSettings.requireUserConsent(true))
.build();
return new InMemoryRegisteredClientRepository(registeredClient);
}
#Bean
public CryptoKeySource keySource() {
return new StaticKeyGeneratingCryptoKeySource();
}
}
In order to customize the default configuration, DO NOT #Import(OAuth2AuthorizationServerConfiguration.class) and instead provide the following:
#Configuration(proxyBeanMethods = false)
public class AuthorizationServerConfig {
#Bean
#Order(Ordered.HIGHEST_PRECEDENCE)
public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http);
// TODO Customize http
return http.build();
}
#Bean
public RegisteredClientRepository registeredClientRepository() {
RegisteredClient registeredClient = RegisteredClient.withId(UUID.randomUUID().toString())
.clientId("messaging-client")
.clientSecret("secret")
.clientAuthenticationMethod(ClientAuthenticationMethod.BASIC)
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS)
.redirectUri("http://localhost:8080/authorized")
.scope("message.read")
.scope("message.write")
.clientSettings(clientSettings -> clientSettings.requireUserConsent(true))
.build();
return new InMemoryRegisteredClientRepository(registeredClient);
}
#Bean
public CryptoKeySource keySource() {
return new StaticKeyGeneratingCryptoKeySource();
}
}
This provides you access to HttpSecurity so you can customize anything you require.

Unable to redirect to CAS for single log out from spring

I am developing an application which has an angular2 frontend and a spring boot backend. For the authentication I am using CAS. Single sign on is working properly, but the single log out is not working and not even redirecting to cas/logout endpoint.(I am sending a POST to my spring boot app's /logout url from angular app )
CAS version - 4.2.2
CAS client core - 3.4
I followed http://docs.spring.io/spring-security/site/migrate/current/3-to-4/html5/migrate-3-to-4-jc.html#m3to4-filter-urls-cas and did necessary changes to Authentication Filter and Logout filter. But still I couldn't identify the issue. Any help is much appreciated.
Security Config
#Configuration
#EnableGlobalMethodSecurity(prePostEnabled = true, jsr250Enabled = true)
#EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Autowired
private AuthProperties properties;
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.addFilterAfter(csrfHeaderFilter(), CsrfFilter.class)
.addFilterBefore(requestSingleLogoutFilter(), LogoutFilter.class)
.addFilterBefore(singleSignOutFilter(), CasAuthenticationFilter.class)
.addFilterBefore(casAuthenticationFilter(), BasicAuthenticationFilter.class)
.exceptionHandling()
.authenticationEntryPoint(casAuthenticationEntryPoint())
.and()
.logout()
.logoutUrl("/logout")
.invalidateHttpSession(true)
.deleteCookies("JSESSIONID")
.permitAll()
.and()
.authorizeRequests()
.antMatchers("//**").authenticated()
.antMatchers("/test").permitAll()
.and()
.csrf()
.csrfTokenRepository(csrfTokenRepository());
}
/***
* Service Properties refer to the application which is being authenticated
* Typically in this case, the service is the authentication engine or auth app
*/
#Bean
public ServiceProperties serviceProperties() {
ServiceProperties sp = new ServiceProperties();
sp.setService(properties.getAppServiceSecurity());
sp.setArtifactParameter("casTicket");
sp.setAuthenticateAllArtifacts(true);
sp.setSendRenew(false);
return sp;
}
#Bean
public CasAuthenticationProvider casAuthenticationProvider() throws Exception {
CasAuthenticationProvider casAuthenticationProvider = new CasAuthenticationProvider();
casAuthenticationProvider.setAuthenticationUserDetailsService(userService());
casAuthenticationProvider.setServiceProperties(serviceProperties());
if (properties.isCasProxyTicket()) {
casAuthenticationProvider.setTicketValidator(cas30ServiceProxyTicketValidator());
casAuthenticationProvider.setStatelessTicketCache(ehManager());
} else {
casAuthenticationProvider.setTicketValidator(cas30ServiceTicketValidator());
}
casAuthenticationProvider.setKey(properties.getProviderKey());
return casAuthenticationProvider;
}
#Bean
public SessionAuthenticationStrategy sessionStrategy() {
SessionAuthenticationStrategy sessionStrategy = new SessionFixationProtectionStrategy();
return sessionStrategy;
}
#Bean
public Cas30ServiceTicketValidator cas30ServiceTicketValidator() {
return new Cas30ServiceTicketValidator(properties.getCasUrlPrefix());
}
#Bean
public CasAuthenticationFilter casAuthenticationFilter() throws Exception {
CasAuthenticationFilter casAuthenticationFilter = new CasAuthenticationFilter();
casAuthenticationFilter.setAuthenticationManager(authenticationManager());
casAuthenticationFilter.setSessionAuthenticationStrategy(sessionStrategy());
casAuthenticationFilter.setProxyGrantingTicketStorage(pgtStorage());
casAuthenticationFilter.setFilterProcessesUrl("/login/cas");
casAuthenticationFilter.setProxyReceptorUrl(properties.getCasProxyReceptor());
return casAuthenticationFilter;
}
#Bean
public CasAuthenticationEntryPoint casAuthenticationEntryPoint() {
CasAuthenticationEntryPoint casAuthenticationEntryPoint = new TBXCasAuthenticationEntryPoint();
casAuthenticationEntryPoint.setLoginUrl(properties.getCasLoginUrl());
casAuthenticationEntryPoint.setServiceProperties(serviceProperties());
return casAuthenticationEntryPoint;
}
#Bean
public LogoutFilter requestSingleLogoutFilter() {
StringBuffer stringBuffer = new StringBuffer("");
stringBuffer.append(properties.getCasLogoutUrl());
LogoutFilter logoutFilter = new LogoutFilter("https://localhost:9443/cas/logout", new SecurityContextLogoutHandler());//env.getRequiredProperty(CAS_URL_LOGOUT) + "?service="+ env.getRequiredProperty(APP_SERVICE_HOME)
logoutFilter.setFilterProcessesUrl("/logout");
return logoutFilter;
}
#Bean
public SingleSignOutFilter singleSignOutFilter() {
SingleSignOutFilter filter = new SingleSignOutFilter();
filter.setArtifactParameterName(Protocol.CAS3.getArtifactParameterName());
filter.setCasServerUrlPrefix("https://localhost:9443/cas");
filter.setIgnoreInitConfiguration(true);
return filter;
}
#Bean
public Filter csrfHeaderFilter() {
return new OncePerRequestFilter() {
#Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
if (csrf != null) {
Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN");
if (cookie != null) {
} else {
}
String token = csrf.getToken();
if (cookie == null || token != null && !token.equals(cookie.getValue())) {
cookie = new Cookie("XSRF-TOKEN", token);
cookie.setPath("/");
response.addCookie(cookie);
}
}
filterChain.doFilter(request, response);
}
};
}
#Bean
public CsrfTokenRepository csrfTokenRepository() {
HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
repository.setHeaderName("X-XSRF-TOKEN");
return repository;
}
/**
* configure via WebSecurity provides the fonts, images, scripts, styles and views to be removed
* from the security features, because, access to these scripts is a must regarding the user experience
**/
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring()
.antMatchers("/fonts*//**")
.antMatchers("/images1*//**")
.antMatchers("/scripts*//**")
.antMatchers("/styles*//**")
.antMatchers("/views*//**")
.antMatchers("/i18n*//**");
}
#Bean
public UserPrincipleHandler userService() {
UserPrincipleHandler userPrincipleServiceHanlder = new UserPrincipleHandler();
return userPrincipleServiceHanlder;
}
#Bean
public RequestContextListener requestContextListener() {
return new RequestContextListener();
}
#Bean
public RequestContextFilter requestContextFilter() {
return new RequestContextFilter();
}
#Bean
public ServiceAuthenticationDetailsSource serviceAuthenticationDataSource() {
ServiceAuthenticationDetailsSource serviceDetailSource = new ServiceAuthenticationDetailsSource(serviceProperties());
return serviceDetailSource;
}
#Bean
public SimpleUrlAuthenticationFailureHandler simpleUrlAuthentication() {
SimpleUrlAuthenticationFailureHandler failureHandler = new SimpleUrlAuthenticationFailureHandler();
failureHandler.setDefaultFailureUrl(properties.getCasFailureUrl());
return failureHandler;
}
#Bean
public ProxyList proxyChainList() {
List<String> list = properties.getProxyList();
String[] stringArray = Arrays.copyOf(list.toArray(), list.size(), String[].class);
List<String[]> urls = new ArrayList<String[]>();
urls.add(stringArray);
ProxyList proxyList = new ProxyList(urls);
return proxyList;
}
#Bean
public ProxyGrantingTicketStorageImpl pgtStorage() {
ProxyGrantingTicketStorageImpl pgtImpl = new ProxyGrantingTicketStorageImpl();
return pgtImpl;
}
#Bean
public SpringCacheBasedTicketCache ehManager() throws Exception {
SpringCacheBasedTicketCache ehmanager = new SpringCacheBasedTicketCache(cacheMap());
return ehmanager;
}
#Bean
public ConcurrentMapCache cacheMap() {
ConcurrentMapCache conCacheMap = new ConcurrentMapCache("casTickets");
conCacheMap.put("casTickets", 50);
return conCacheMap;
}
#Bean
public Cas30ProxyTicketValidator cas30ServiceProxyTicketValidator() {
Cas30ProxyTicketValidator validator = new Cas30ProxyTicketValidator(properties.getCasUrlPrefix());//env.getRequiredProperty(CAS_URL_PREFIX)
StringBuffer stringBuffer = new StringBuffer("");
stringBuffer.append(properties.getAppServiceHome()).append(properties.getCasProxyReceptor());
validator.setProxyCallbackUrl(stringBuffer.toString());//env.getRequiredProperty(APP_SERVICE_HOME)+"login/cas/proxyreceptor"
validator.setProxyGrantingTicketStorage(pgtStorage());
validator.setAllowedProxyChains(proxyChainList());
validator.setAcceptAnyProxy(false);
return validator;
}
}

Resources