Принципал OAuth2 пуст после аутентификации в Spring BootJAVA

Программисты JAVA общаются здесь
Ответить
Anonymous
 Принципал OAuth2 пуст после аутентификации в Spring Boot

Сообщение Anonymous »

Я унаследовал старый проект Spring Boot. В проекте авторизуемся через корпоративный OIDC-сервер. Spring Boot видит, что мы прошли аутентификацию, а затем предлагает несколько конечных точек, которые мы можем использовать. Я пытаюсь добавить авторизацию - мы проверяем токен JWT и обслуживаем страницу ответа только в том случае, если они являются членами определенной группы. В процессе я обновил Spring Boot с 2.0.7 до 2.4.13 (знаю, все еще старый, но я не знаком с этим кодом и стараюсь минимизировать изменения).
Вот минимальная версия кода:
MyApplication.java

Код: Выделить всё

@SpringBootApplication
@EnableOAuth2Sso // this enables the authorization code flow via sso/pwd
@RestController
@Order(value = 0) // makes this security adapter have precedence over others
public class MyApplication extends WebSecurityConfigurerAdapter {

private final Logger log = LoggerFactory.getLogger(this.getClass());

public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}

@RequestMapping(value = "/userinfo", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public void getUserInfo(final @AuthenticationPrincipal OAuth2Authentication activeUser) throws Exception {
log.info("GET /userinfo called");
activeUser.getAuthorities();
log.info("Principal: "+activeUser.getPrincipal());
}

@Override
protected void configure(final HttpSecurity http) throws Exception {
//Added by me, I've tried with and without this line with no difference to the result
//http.oauth2ResourceServer()
//      .jwt()
//      .jwtAuthenticationConverter(jwtAuthenticationConverter());

// Minimal http block to run server, the original is much longer but also results in empty Principals
http.csrf().disable()
.authorizeRequests().antMatchers("/**")
.permitAll().anyRequest().authenticated();

//Added by me, I've tried with and without this line with no difference to the result
//http.oauth2ResourceServer()
//      .jwt()
//      .jwtAuthenticationConverter(jwtAuthenticationConverter());

}

// Function added by me, from https://stackoverflow.com/a/63869532/18572146
private JwtAuthenticationConverter jwtAuthenticationConverter() {
JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
jwtGrantedAuthoritiesConverter.setAuthoritiesClaimName("myGroups");
jwtGrantedAuthoritiesConverter.setAuthorityPrefix("ROLE_");
JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();
jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(jwtGrantedAuthoritiesConverter);
return jwtAuthenticationConverter;
}
}
application.yml

Код: Выделить всё

security:
ignored: /favicon.ico, /lib/**, /js/**, /resources/**
basic:
enabled: false  # Enable basic authentication.
headers:
cache: true  # Enable cache control HTTP headers.
frame: true  # Enable "X-Frame-Options" header.
xss: true    # Enable cross site scripting (XSS) protection.
filter-order: 1  # Security filter chain order.
oauth2:
client:
clientId: ${APP_CLIENT_ID}
clientSecret: ${APP_CLIENT_SECRET}
accessTokenUri: ${APP_ACCESS_TOKEN_URI}
userAuthorizationUri: ${APP_USER_AUTH_URI}
scope: openid,profile
pre-established-redirect-uri: https://${APP_SERVER}:${APP_PORT}/login
registered-redirect-uri: https://${APP_SERVER}:${APP_PORT}/login
use-current-uri: false

resource:
userInfoUri: ${APP_USER_INFO_URI}
prefer-token-info: true

server:
port: ${APP_PORT}
use-forward-headers: true
tomcat:
remote-ip-header: x-forwarded-for
protocol-header: x-forwarded-proto
protocol-header-https-value: http
ssl:
enabled: true
#key-alias: tomcat
key-store: ${APP_KEY_STORE_FILE}
key-store-password: ${APP_KEY_STORE_PASSWORD}
key-store-type: PKCS12
error:
path: /error

spring:
resources:
chain:
enabled: true  # Enable the Spring Resource Handling chain.  Disabled by default unless at least one strategy has been enabled.
main:
banner-mode: "off"  # Mode used to display the banner when the application runs.
allow-bean-definition-overriding: true     # Turns off package conflict detector
security:
oauth2:
resourceserver:
jwt:
jwk-set-uri: ${APP_KEY_URI}

#Forward authorization token downstream
proxy:
auth:
routes:
customers: oauth2
stores: passthru
В версии 2.0.7 я смог войти в систему, получить JSESSIONID, и если я попаду в конечную точку /userinfo, он успешно зарегистрирует заполненный принципал. В версии 2.4.13 я могу войти в систему и получить JSESSIONID, но если я доберусь до конечной точки /userinfo, я получу исключение нулевого указателя. Если вместо этого я попытаюсь использовать конечную точку, которая напрямую обращается к участнику, она снова будет работать в 2.0.7, но не будет заполнена в 2.4.13 (имя «неизвестно», и даже когда я раскомментирую вызов jwtAuthenticationConverter, единственной ролью будет значение по умолчанию " ROLE_USER").
Я подозреваю, что у него проблемы с декодированием токенов. Примечательно, что единственное изменение, которое мне пришлось внести в application.yml для версии 2.4.13, — это добавить Spring:security:oauth2:resourceserver:jwt:jwk-set-uri. Но я не знаю, как это подтвердить или исправить.
Спасибо за совет!

Подробнее здесь: https://stackoverflow.com/questions/793 ... pring-boot
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «JAVA»