Oauth2 Токен, точка и базовая комбинация аутентификацииJAVA

Программисты JAVA общаются здесь
Anonymous
Oauth2 Токен, точка и базовая комбинация аутентификации

Сообщение Anonymous »

Пожалуйста, помогите мне. мне нужно настроить конечную точку входа в систему, она общедоступна, пока мне не понадобится настроить базовую аутентификацию для определенного API, когда я настраиваю базовую аутентификацию, API входа в систему всегда показывает форму оповещения о входе
здесь моя конфигурация:

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

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class ResourceServerConfiguration extends WebSecurityConfigurerAdapter {

@Value("${spring.profiles.active:default}")
private String activeProfile;

@Value("${ekyc.username}")
private String username;

@Value("${ekyc.password}")
private String password;

private final CustomAuthenticationEntryPoint customAuthenticationEntryPoint;

private final JwtTokenAuthenticationFilter jwtTokenAuthenticationFilter;

public ResourceServerConfiguration(CustomAuthenticationEntryPoint customAuthenticationEntryPoint,
JwtTokenAuthenticationFilter jwtTokenAuthenticationFilter, BasicAuthConfiguration basicAuthConfiguration) {
this.customAuthenticationEntryPoint = customAuthenticationEntryPoint;
this.jwtTokenAuthenticationFilter = jwtTokenAuthenticationFilter;
}

private static final String[] ENDPOINT_PUBLIC =  {
EXTERNAL_MB_SESSION_VERIFY,
EXTERNAL_MB_CALLBACK_TRANSACTION,
EXTERNAL_MB_PAYGATE_CALLBACK_TRANSACTION,
URL_FORGOT_PASSWORD,
"/api/users/token",
"/actuator/health",
URL_RESET_PASSWORD_CONFIRM,
URL_RESET_PASSWORD_REQUEST,
URL_HEALTH_TWELVE_QUESTION,
"/oauth/token"
// Some public end-point...

};

@Override
public void configure(HttpSecurity http) throws Exception {
http
.headers(headers -> headers.frameOptions(FrameOptionsConfig::sameOrigin))
.csrf().disable()
.addFilterBefore(jwtTokenAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers(ENDPOINT_PUBLIC).permitAll()
.anyRequest()
.authenticated()
.and()
.exceptionHandling()
.authenticationEntryPoint(customAuthenticationEntryPoint)
.accessDeniedHandler(new CustomAccessDeniedHandler());
}

@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}

@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}

@Override
public void configure(WebSecurity web) {
if (Objects.equals(activeProfile, "stg") || Objects.equals(activeProfile, "dev")) {
web.ignoring().antMatchers("/v3/api-docs/**", "/swagger-ui/**");
}
}
Я вхожу в систему через TokenEnpoint вот так:

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

public class OAuthTokenEndpoint extends TokenEndpoint {
private final UserSessionService userSessionService;

@Operation(summary = "postAccessToken -> Sử dụng hàm POST để login cho User")
@PostMapping
public ResponseEntity postAccessToken(Principal principal,
@RequestParam Map parameters,
HttpServletRequest request) throws HttpRequestMethodNotSupportedException {
ResponseEntity oAuth2AccessToken = super.postAccessToken(principal, parameters);

if ("password".equals(parameters.get(GRANT_TYPE))) {
Map  additionalInfo = Objects.requireNonNull(oAuth2AccessToken.getBody()).getAdditionalInformation();
RemoteClientDto clientInfo = CommonUtils.getClientInfo(request);

userSessionService.createUserSession(
Long.valueOf(additionalInfo.get(CLAIM_KEY_USER_ID).toString()),
(String) additionalInfo.get(CLAIM_USER_SESSION_ID),
clientInfo
);
}

return oAuth2AccessToken;
}
теперь мне нужно создать API, защищенный базовой аутентификацией, как мне это сделать
я пробовал конфигурацию

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

@Order(2)

public class BasicAuthConfiguration extends WebSecurityConfigurerAdapter {

@Value("${ekyc.username}")
private String username;

@Value("${ekyc.password}")
private String password;

@Override
protected void configure(HttpSecurity http) throws Exception {

// @formatter:off
http.anonymous().disable()
.requestMatcher(request -> {
String auth = request.getHeader(HttpHeaders.AUTHORIZATION);
return (auth != null && auth.startsWith("Basic"));
})
.antMatcher(EXTERNAL_MBAL_SUBMIT_EKYC)
.authorizeRequests().anyRequest().authenticated()
.and()
.httpBasic();
// @formatter:on
}

@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}

@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser(username).password(passwordEncoder().encode(password)).roles("MBAL");
}
}
но это не сработало
пожалуйста, помогите мне

Подробнее здесь: https://stackoverflow.com/questions/787 ... ombination

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