Теперь мне нужно разрешить другому приложению взаимодействовать с моим API либо путем получения данных, либо путем отправки данных через запросы POST. Например, я хочу предоставить простому приложению JavaScript, работающему с Node.js, доступ к моему API.
Мне трудно понять, как этого добиться. Кто-нибудь знает, как настроить аутентификацию и авторизацию для этого сценария?
Большое спасибо за помощь!
Вот моя безопасностьFilterChain
Код: Выделить всё
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http
.csrf(AbstractHttpConfigurer::disable)
.cors(cors -> cors.configurationSource(corsConfigurationSource()))
.authorizeHttpRequests( auth -> auth.anyRequest().authenticated())
.oauth2Login( oauth2 -> oauth2.successHandler(oAuth2LoginSuccessHandler))
.oauth2ResourceServer(oauth2ResourceServer -> oauth2ResourceServer.jwt(Customizer.withDefaults()))
.build();
}
Код: Выделить всё
@Override
public void onAuthenticationSuccess(final HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
OAuth2AuthenticationToken token = (OAuth2AuthenticationToken) authentication;
if("github".equals(token.getAuthorizedClientRegistrationId())){
DefaultOAuth2User principal = (DefaultOAuth2User) authentication.getPrincipal();
Map attributes = principal.getAttributes();
String email = attributes.getOrDefault("email", "").toString();
String name = attributes.getOrDefault("name", "").toString();
userService.findByEmail(email)
.ifPresentOrElse(user -> {
DefaultOAuth2User newUser = new DefaultOAuth2User(List.of(new SimpleGrantedAuthority(user.getRole().name()))
, attributes, "id");
Authentication securityAuth = new OAuth2AuthenticationToken(newUser, List.of(new SimpleGrantedAuthority(user.getRole().name()))
, token.getAuthorizedClientRegistrationId());
SecurityContextHolder.getContext().setAuthentication(securityAuth);
}, () -> {
BMUser userEntity = new BMUser();
userEntity.setRole(BMUserRole.ROLE_USER);
userEntity.setEmail(email);
userEntity.setName(name);
userService.createNewUser(userEntity);
DefaultOAuth2User newUser = new DefaultOAuth2User(List.of(new SimpleGrantedAuthority(userEntity.getRole().name()))
, attributes, "id");
Authentication securityAuth = new OAuth2AuthenticationToken(newUser, List.of(new SimpleGrantedAuthority(userEntity.getRole().name()))
, token.getAuthorizedClientRegistrationId());
SecurityContextHolder.getContext().setAuthentication(securityAuth);
});
}
this.setAlwaysUseDefaultTargetUrl(true);
this.setDefaultTargetUrl(frontendUrl);
super.onAuthenticationSuccess(request, response, authentication);
}
Подробнее здесь: https://stackoverflow.com/questions/786 ... d-machines