Spring boot + oauth2 + HttpClientErrorException 401 Unauthorized - spring-boot

I'm using the spring boot tutorial as a base (https://spring.io/guides/tutorials/spring-boot-oauth2/)
to test Oauth2.
However, my auth server isn't facebook, it's Netiq Access Manager (NAM).
I managed to be redirected to NAM login page, but after logging in, i get the following error:
The log shows:
o.s.b.a.s.o.r.UserInfoTokenServices : Could not fetch user details: class org.springframework.web.client.HttpClientErrorException, 401 Unauthorized
This is the project:
The app code:
package com.example.springoauthdemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso;
#SpringBootApplication
#EnableOAuth2Sso
public class SocialApplication {
public static void main(String[] args) {
SpringApplication.run(SocialApplication.class, args);
}
}
The application.yml
security:
oauth2:
client:
clientId: 55bb61f1-4384-4939-9cd0-fa7d76af9a0c
clientSecret: fdUjegFlCJjnD778RUSuS4SqMRey4IKVDOkadi4hjN6YbhC1xCInxoxobf-a-p-po8rt1wfZM2BPqJHpcZ-FGs
accessTokenUri: https://nam.example.com/nidp/oauth/nam/token
userAuthorizationUri: https://nam.example.com/nidp/oauth/nam/authz
tokenName: oauth_token
authenticationScheme: query
clientAuthenticationScheme: form
resource:
userInfoUri: https://localhost:8443/index.html
#userInfoUri: https://nam.example.com/nidp/oauth/nam/userinfo
server:
port: 8443
ssl:
enabled: true
key-alias: tomcat-localhost
key-password: changeit
key-store: classpath:keystore.jks
key-store-provider: SUN
key-store-type: JKS
key-store-password: changeit
As far i know, using this Oauth2 flow as example, step 1, 2 and 3 seems to be ok, so the problem is trying to get the access token?
Any ideas?
Thanks in advance!

When you are authenticated and you have a user, you can validate it against the userInfoUri, which returns a Principal object of the oauth.
You are setting this value against an html:
resource:
userInfoUri: https://localhost:8443/index.html
It should be something like:
resource:
userInfoUri: https://localhost:8443/userinfo
And that service response would have to return something like:
#RequestMapping("/userinfo")
Principal getUser(Principal user) {
return user;
}

Related

Spring Cloud Gateway redirects to Keycloak login page although Bearer token is set

I am using a setup with Keycloak as Identity Provider, Spring Cloud Gateway as API Gateway and multiple Microservices.
I can receive a JWT via my Gateway (redirecting to Keycloak) via http://localhost:8050/auth/realms/dev/protocol/openid-connect/token.
I can use the JWT to access a resource directly located at the Keycloak server (e.g. http://localhost:8080/auth/admin/realms/dev/users).
But when I want to use the Gateway to relay me to the same resource (http://localhost:8050/auth/admin/realms/dev/users) I get the Keycloak Login form as response.
My conclusion is that there must me a misconfiguration in my Spring Cloud Gateway application.
This is the Security Configuration in the Gateway:
#Configuration
#EnableWebFluxSecurity
#EnableReactiveMethodSecurity
public class SecurityConfiguration {
#Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http, ReactiveClientRegistrationRepository clientRegistrationRepository) {
// Authenticate through configured OpenID Provider
http.oauth2Login();
// Also logout at the OpenID Connect provider
http.logout(logout -> logout.logoutSuccessHandler(
new OidcClientInitiatedServerLogoutSuccessHandler(clientRegistrationRepository)));
//Exclude /auth from authentication
http.authorizeExchange().pathMatchers("/auth/realms/ahearo/protocol/openid-connect/token").permitAll();
// Require authentication for all requests
http.authorizeExchange().anyExchange().authenticated();
// Allow showing /home within a frame
http.headers().frameOptions().mode(Mode.SAMEORIGIN);
// Disable CSRF in the gateway to prevent conflicts with proxied service CSRF
http.csrf().disable();
return http.build();
}
}
This is my application.yaml in the Gateway:
spring:
application:
name: gw-service
cloud:
gateway:
default-filters:
- TokenRelay
discovery:
locator:
lower-case-service-id: true
enabled: true
routes:
- id: auth
uri: http://localhost:8080
predicates:
- Path=/auth/**
security:
oauth2:
client:
registration:
keycloak:
client-id: 'api-gw'
client-secret: 'not-relevant-but-correct'
authorizationGrantType: authorization_code
redirect-uri: '{baseUrl}/login/oauth2/code/{registrationId}'
scope: openid,profile,email,resource.read
provider:
keycloak:
issuerUri: http://localhost:8080/auth/realms/dev
user-name-attribute: preferred_username
server:
port: 8050
eureka:
client:
service-url:
default-zone: http://localhost:8761/eureka
register-with-eureka: true
fetch-registry: true
How can I make the Gateway able to know that the user is authenticated (using the JWT) and not redirect me to the login page?
If you want to make requests to Spring Gateway with access token you need to make it a resource server. Add the following:
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>
application.yml
security:
oauth2:
resourceserver:
jwt:
issuer-uri: https://.../auth/realms/...
SecurityConfiguration.java
#Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http,
ReactiveClientRegistrationRepository clientRegistrationRepository) {
// Authenticate through configured OpenID Provider
http.oauth2Login();
// Also logout at the OpenID Connect provider
http.logout(logout -> logout.logoutSuccessHandler(
new OidcClientInitiatedServerLogoutSuccessHandler(clientRegistrationRepository)));
// Require authentication for all requests
http.authorizeExchange().anyExchange().authenticated();
http.oauth2ResourceServer().jwt();
// Allow showing /home within a frame
http.headers().frameOptions().mode(Mode.SAMEORIGIN);
// Disable CSRF in the gateway to prevent conflicts with proxied service CSRF
http.csrf().disable();
return http.build();
}
I bypassed the problem by communicating directly with Keycloak without relaying requests to it via Spring Cloud Gateway.
That's actually not a workaround but actually best practice/totally ok as far as I understand.
This code is for Client_credentials grant_type. if you use other grant type you need to add client_id and client_secret in request parameters.
public class MyFilter2 extends OncePerRequestFilter {
private final ObjectMapper mapper = new ObjectMapper();
#Value("${auth.server.uri}")
private String authServerUri;
#Value("${client_id}")
private String clientId;
#Value("${client_secret}")
private String clientSecret;
#Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
FilterChain filterChain) throws IOException {
try {
String token = httpServletRequest.getHeader("Authorization");
HttpHeaders headers = new HttpHeaders();
headers.set("Content-Type","application/x-www-form-urlencoded");
headers.set("Authorization",token);
final HttpEntity finalRequest = new HttpEntity("{}", headers);
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = restTemplate.postForEntity(authServerUri,finalRequest,String.class);
if (!HttpStatus.OK.equals(response.getStatusCode())) {
Map<String, Object> errorDetails = new HashMap<>();
errorDetails.put("status", HttpStatus.UNAUTHORIZED.value());
errorDetails.put("message", "Invalid or empty token");
httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
httpServletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
mapper.writeValue(httpServletResponse.getWriter(), errorDetails);
} else {
filterChain.doFilter(httpServletRequest, httpServletResponse);
}
}catch(HttpClientErrorException he) {
Map<String, Object> errorDetails = new HashMap<>();
errorDetails.put("status", HttpStatus.UNAUTHORIZED.value());
errorDetails.put("message", "Invalid or empty token");
httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
httpServletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
mapper.writeValue(httpServletResponse.getWriter(), errorDetails);
}catch (Exception exception) {
}
}

How can I retrieve the azure AD JWT access token from Spring?

I'm trying to retrieve the azure JWT access token from my Spring Boot application from another application by querying a /token endpoint, but the token I receive is seemingly incorrect.
The project has a Spring Boot backend and an Eclipse rcp frontend. I'm attempting to retrieve the access token from the eclipse frontend. For this, I have the controller below:
#Autowired
private OAuth2AuthorizedClientService authorizedClientService;
#GetMapping("/token")
public String user(OAuth2AuthenticationToken authentication) {
OAuth2AuthorizedClient authorizedClient = this.authorizedClientService
.loadAuthorizedClient(authentication.getAuthorizedClientRegistrationId(), authentication.getName());
return authorizedClient.getAccessToken().getTokenValue();
}
Which returns a token with the following format:
PAQABAAAAAABeAFzDwllzTYGDLh_qYbH8hgtbYMB8x7YLamQyQPk_MEXyd9Ckc5epDFQMv3RxjmMie0JDr5uN82U4RFLgU3fnDBxGolo4XVwzLEsTZDmUK_r0YG6ZwLbbQI_ch_Xn8xCxhsFq-AoRbEESDqK3GmK4eXwCYoT0G8_XfZjHTvCNTOMqUb2Q-CD2EalIKf0zSZ5184qrvlXfdNeT_BJdH_tqaodn80Bp2UL2hdnOCDZuWRqKl_2fi4v-eOOKJCcjOqY6SreVEeoKkIvVdayGE8F6qCxFehmlA0sX9sVW34FIVYVo4lDRsTkm-WN2KJwxJmalNcxg0k2ObDnIeC1ulPPpiPq-O_LK9bVA4HEZ63cJi9ZwQHwLPUhOO6TquoCOroHSy5KPoFkX3N796hM1i0NpaaY4MeAx17CSYeZ9P06jvYD7UMTV3OwWt-OVrDm5z_AvbOvyHRf9wjh31H6oLoc-iu_NCspT6NzC2UZQSHBtKdydEcP6sNkRp073jrZEg8UtcVT6HzddIBk2P0tVeIiSyU3SfLETbzJE67xtJVip3ai9aLN28c0qt3rDBaVGDAXjXhqrh5D3NiXdQjS6YTAKy0bVmNk9Yr9o2CGBA2wFjE8OZ6_Hb3k8_13KMJHafx0gAA
Dependencies from pom.xml
Built using spring boot with the following relevant dependencies:
spring-boot-starter-web v2.2.4
azure-active-directory-spring-boot-starter v2.2.1
spring-security-oauth2-client v5.2.1
spring-security-oauth2-jose v5.2.1
spring-security-oauth2-resource-server v5.2.1
Config from application.yml
We support multiple authorization servers, here is the fully configured azure client:
spring:
security:
oauth2:
client:
azure:
client-id: XXX
client-secret: XXX
client-name: Microsoft
scope: openid, https://graph.microsoft.com/user.read, profile
authorization-grant-type: authorization_code
redirect-uri: http://localhost:8080/login/oauth2/code/azure
client-authentication-method: basic
authentication-method: post
provider:
authorization-uri: https://login.microsoftonline.com/XXX/oauth2/authorize
token-uri: https://login.microsoftonline.com/XXX/oauth2/token
user-info-uri: https://login.microsoftonline.com/XXX/openid/userinfo
jwt-set-uri: https://login.microsoftonline.com/dXXX/discovery/keys
azure:
activedirectory:
tenant-id: XXX
active-directory-groups: XXX
allow-telemetry: false
websecurityconfig.java
#Configuration
#EnableConfigurationProperties
#EnableWebSecurity
#Order(1)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private OAuth2UserService<OidcUserRequest, OidcUser> oidcUserService;
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
[...]
.anyRequest().authenticated();
http.oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt)
http.oauth2Login()
.userInfoEndpoint()
.oidcUserService(oidcUserService)
.and()
.authorizationEndpoint();
}
[...]
}
This is how I ended up obtaining the open id token from Azure
#GetMapping("/token")
public String user(OAuth2AuthenticationToken authentication) {
DefaultOidcUser user = (DefaultOidcUser) authentication.getPrincipal();
return user.getIdToken().getTokenValue();
}

Spring Security 5.2.1 + spring-security-oauth2 + WebClient: how to use password grant-type

Here is my current setup:
I'm exposing a WebClient bean with oauth2 filter:
#Configuration
class OAuthConfiguration {
#Bean("authProvider")
fun webClient(
clientRegistrationRepository: ClientRegistrationRepository,
authorizedClientRepository: OAuth2AuthorizedClientRepository,
clientHttpConnector: ClientHttpConnector
): WebClient {
val oauth = ServletOAuth2AuthorizedClientExchangeFilterFunction(clientRegistrationRepository, authorizedClientRepository)
oauth.setDefaultClientRegistrationId("authProvider")
oauth.setDefaultOAuth2AuthorizedClient(true)
return WebClient.builder()
.baseUrl("baseUrl")
.clientConnector(clientHttpConnector)
.filter(oauth)
.build()
}
}
And I'm using it here:
fun callExternalService() {
val retrieve = webClient.get()
.uri("/uri")
.retrieve()
.bodyToMono(String::class.java)
.block()
// ...
}
My application.yml has the following structure
security:
oauth2:
client:
provider:
authProvider:
token-uri: https://authentication-uri.com
registration:
authProvider:
client-id: client-id
client-secret: client-secret
authorization-grant-type: authorization_code
scope: any
This code is failing because my internal authentication service accepts only password grant-type and I can see the response for my auth URL returning a 400 code. Once I change authorization-grant-type: authorization_code to authorization-grant-type: password, spring ignores all the logic of authentication, it does not try to authenticate.
Does anyone know how to implement authorization-grant-type: password?

Spring Boot Google Oauth2 all requests return a 401 Unauthorized

I have a very simple Spring Boot app where I want all pages to be authenticated thtough Google Oauth2. I followed the Spring Oauth2 tuotrial and looked at the code under the /simple implementation. (My application.yml file is setup for Google instead of FB)
Any request to my app returns a 401 Unauthorized response, and goes to localhost:8080/login... (The Spring security auto generated login page, which is set as the Redirect URI in Google developer console)
I have looked at all the other questions that try to answer this issue, but none have been of help.
My Application class:
#SpringBootApplication
#EnableOAuth2Sso
#RestController
public class ControlApplication extends WebSecurityConfigurerAdapter {
public static void main(String[] args) {
SpringApplication.run(ControlApplication.class, args);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.antMatcher("/**").authorizeRequests().anyRequest().authenticated().and().formLogin().defaultSuccessUrl("/", false);
}
}
And my application.yml:
security:
oauth2:
client:
clientId: [MyClientID]
clientSecret: [MyClientSecret]
accessTokenUri: https://accounts.google.com/o/auth2/token
userAuthorizationUri: https://accounts.google.com/o/oauth2/auth?hd=xyz.com
redirectUri: http://localhost:8080
clientAuthenticationScheme: form
tokenName: oauth_token
authenticationScheme: query
scope:
- email
- profile
resource:
userInfoUri: https://www.googleapis.com/oauth2/v3/userinfo
preferTokenInfo: true
Solved. (Finally!) The issue appears to be wrong config for acessTokenUri in calling the Google Auth API. Working config:
accessTokenUri: https://www.googleapis.com/oauth2/v4/token
userAuthorizationUri: https://accounts.google.com/o/oauth2/v2/auth?hd=xyz.com
clientAuthenticationScheme: form
scope:
- openid
- email
- profile
resource:
userInfoUri: https://www.googleapis.com/oauth2/v3/userinfo
preferTokenInfo: true

Spring security oauth 2 client app can't check token validity

here is what I'm trying to achieve :
I have an enterprise oauth 2 provider, I want to use their login form and get code, access token and so on from this provider
here is my conf
security:
oauth2:
client:
clientId: MY_CLIENT_ID
clientSecret: asecret
accessTokenUri: https://blabla/oauth-server/oauth/token
userAuthorizationUri: https://blabla/oauth-server/oauth/authorize
tokenName: access_token
scope : read
userInfoUri: https://localhost/user
I can get my code which is changed for an access token, everything is fine, it's calling my local endpoint to get user information (roles for instance)
but when I debug the code I can't see any expires_in value anywhere and my token doesn't expire at all.
here's my resource server conf
#EnableResourceServer
#EnableOAuth2Sso
#RestController
public class SecurityController extends ResourceServerConfigurerAdapter {
private static final String RESOURCE_ID = "my_rest_api";
#Override
public void configure(ResourceServerSecurityConfigurer resources) {
resources.resourceId(RESOURCE_ID).stateless(true);
}
#Override
public void configure(HttpSecurity http) throws Exception {
http.requestMatchers().anyRequest().and().authorizeRequests();
http.
anonymous().disable()
.requestMatchers().antMatchers("/**/*")
.and().authorizeRequests()
.antMatchers("/**/*").access("#oauth2.hasScope('read')")
.and().exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());
}
}
I can't fidn out how to revoke the token
any idea is welcome, i've lost a bunch of hour reading tutorials ...
Add access-token-validity-seconds to your yaml
security:
oauth2:
client:
clientId: MY_CLIENT_ID
clientSecret: asecret
accessTokenUri: https://blabla/oauth-server/oauth/token
userAuthorizationUri: https://blabla/oauth-server/oauth/authorize
tokenName: access_token
scope : read
userInfoUri: https://localhost/user
access-token-validity-seconds: 30 //Adds 30 seconds of token validity

Resources