La bota de resorte Expone API REST con autenticación básica utilizando la ID de cliente y la contraseña del cliente -- java campo con spring campo con spring-boot campo con spring-security campo con spring-security-oauth2 camp Relacionados El problema

Spring boot expose rest API with basic auth using client ID and Client password


1
vote

problema

Español

En mi solicitud, tengo tanto descanso como web.
La parte web tiene un patrón de URL de /admin/** que utiliza la autenticación basada en formular.
Mientras que la pieza de descanso tiene un patrón de URL de /api/** que utiliza el token JWT para la autenticación.
También por configuración predeterminada hay otro patrón de URL /oauth/* IE /oauth/token , /oauth/token_key etc
Estoy tratando de exponer la API de descanso específicamente /open/api/** que utiliza Auth Basic Like in /oauth/token6 .
Para que cualquier solicitud a /open/api/**
parezca

  POST http://{{host}}/open/api/test   Accept: application/json   Authorization: Basic {base64encoded(clientId:clientSecret)} // this is important to expose the api   cache-control: no-cache   

He intentado Google No pude encontrar ninguna configuración para ello.
Mi configuración es

   import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.core.annotation.Order; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer; import org.springframework.security.oauth2.provider.token.DefaultTokenServices; import org.springframework.security.oauth2.provider.token.TokenStore; import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;  @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) public class MultiHttpSecurityConfig {      @Autowired     private CustomUserDetailsService userDetailsService;      @Bean     public PasswordEncoder passwordEncoder() {         PasswordEncoder encoder = new BCryptPasswordEncoder();         return encoder;     }      @Autowired     public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {         auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());     }      @Configuration     @Order(1)     public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {          Logger logger = LoggerFactory.getLogger(FormLoginWebSecurityConfigurerAdapter.class);          @Override         protected void configure(HttpSecurity http) throws Exception {              http                 .antMatcher("/admin/**")                 .authorizeRequests()                     .anyRequest().hasAnyAuthority("ADMIN_USER")                 .and()                     .formLogin()                     .loginPage("/admin/login")                     .permitAll()                 .and()                     .logout()                         .logoutUrl("/admin/logout")                         .invalidateHttpSession(true)                         .permitAll()                 .and()                         .exceptionHandling()                         .accessDeniedPage("/403");              http.csrf().disable();              http.headers().frameOptions().disable();          }          @Bean         @Override         public AuthenticationManager authenticationManagerBean() throws Exception {             return super.authenticationManagerBean();         }              }      @Configuration     @EnableResourceServer     @Order(2)     public class CustomResourceServerConfigurerAdapter extends ResourceServerConfigurerAdapter {          Logger logger = LoggerFactory.getLogger(CustomResourceServerConfigurerAdapter.class);          @Autowired         private JdbcTemplate jdbcTemplate;          @Bean         public TokenStore tokenStore() {             return new JdbcTokenStore(jdbcTemplate.getDataSource());         }          @Bean         @Primary         //Making this primary to avoid any accidental duplication with another token service instance of the same name         public DefaultTokenServices tokenServices() {             DefaultTokenServices defaultTokenServices = new DefaultTokenServices();             defaultTokenServices.setTokenStore(tokenStore());             defaultTokenServices.setSupportRefreshToken(true);             return defaultTokenServices;         }            @Override         public void configure(ResourceServerSecurityConfigurer resources) throws Exception {             resources.tokenServices(tokenServices());         }          @Override         public void configure(HttpSecurity http) throws Exception {              http                 .antMatcher("/api/**")                 .authorizeRequests()                     .antMatchers("/api/**" ).authenticated();          }     }  }   

¿Hay alguna forma de configurar /admin/**0 en esta configuración o tengo que escribir mi propia implementación para hacerlo?

editar ....

Después de mucho intento, se le ocurrió agregar un filtro como se muestra el código a continuación. Funciona, pero no sé si es una forma adecuada de hacerlo. Las sugerencias son bienvenidas.

  /admin/**111  

y registrado con frijol

  /admin/**2  
Original en ingles

In my application i have both rest as well as web part.
The web part has url pattern of /admin/** which uses form based authentication.
while rest part has url pattern of /api/** which uses jwt token for authentication.
Also by default configuration there is another url pattern /oauth/* ie /oauth/token , /oauth/token_key etc
I am trying to expose rest api specifically /open/api/** which uses basic auth like in /oauth/token.
So that any request to /open/api/** look like

POST http://{{host}}/open/api/test   Accept: application/json   Authorization: Basic {base64encoded(clientId:clientSecret)} // this is important to expose the api   cache-control: no-cache 

I have tried google i could not find any configuration for it.
My configuration is

 import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.core.annotation.Order; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer; import org.springframework.security.oauth2.provider.token.DefaultTokenServices; import org.springframework.security.oauth2.provider.token.TokenStore; import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;  @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) public class MultiHttpSecurityConfig {      @Autowired     private CustomUserDetailsService userDetailsService;      @Bean     public PasswordEncoder passwordEncoder() {         PasswordEncoder encoder = new BCryptPasswordEncoder();         return encoder;     }      @Autowired     public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {         auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());     }      @Configuration     @Order(1)     public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {          Logger logger = LoggerFactory.getLogger(FormLoginWebSecurityConfigurerAdapter.class);          @Override         protected void configure(HttpSecurity http) throws Exception {              http                 .antMatcher("/admin/**")                 .authorizeRequests()                     .anyRequest().hasAnyAuthority("ADMIN_USER")                 .and()                     .formLogin()                     .loginPage("/admin/login")                     .permitAll()                 .and()                     .logout()                         .logoutUrl("/admin/logout")                         .invalidateHttpSession(true)                         .permitAll()                 .and()                         .exceptionHandling()                         .accessDeniedPage("/403");              http.csrf().disable();              http.headers().frameOptions().disable();          }          @Bean         @Override         public AuthenticationManager authenticationManagerBean() throws Exception {             return super.authenticationManagerBean();         }              }      @Configuration     @EnableResourceServer     @Order(2)     public class CustomResourceServerConfigurerAdapter extends ResourceServerConfigurerAdapter {          Logger logger = LoggerFactory.getLogger(CustomResourceServerConfigurerAdapter.class);          @Autowired         private JdbcTemplate jdbcTemplate;          @Bean         public TokenStore tokenStore() {             return new JdbcTokenStore(jdbcTemplate.getDataSource());         }          @Bean         @Primary         //Making this primary to avoid any accidental duplication with another token service instance of the same name         public DefaultTokenServices tokenServices() {             DefaultTokenServices defaultTokenServices = new DefaultTokenServices();             defaultTokenServices.setTokenStore(tokenStore());             defaultTokenServices.setSupportRefreshToken(true);             return defaultTokenServices;         }            @Override         public void configure(ResourceServerSecurityConfigurer resources) throws Exception {             resources.tokenServices(tokenServices());         }          @Override         public void configure(HttpSecurity http) throws Exception {              http                 .antMatcher("/api/**")                 .authorizeRequests()                     .antMatchers("/api/**" ).authenticated();          }     }  } 

Is there a way to configure /open/api in this config or do i have to write my own implementation to do so?

EDIT....

After much trying, came up with adding a filter as shown code below. It works but I don't know whether its a proper way to do it. Suggestions are welcome.

import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; import org.springframework.security.oauth2.provider.ClientDetails; import org.springframework.security.oauth2.provider.ClientDetailsService; import org.springframework.stereotype.Component;  import java.io.IOException;  import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;  import org.apache.commons.codec.binary.Base64; import org.slf4j.Logger; import org.slf4j.LoggerFactory;  @Component public class OpenApiFilter implements Filter {      Logger logger = LoggerFactory.getLogger(OpenApiFilter.class);      @Autowired     private JdbcTemplate jdbcTemplate;      @Autowired     private ClientDetailsServiceConfigurer clients;      @Autowired     private PasswordEncoder encoder;      @Override     public void init(final FilterConfig filterConfig) throws ServletException {         logger.info("Initializing filter :{}", this);     }      @Override     public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)             throws IOException, ServletException {                  HttpServletRequest req = (HttpServletRequest) request;                 HttpServletResponse httpResponse = (HttpServletResponse) response;                  String auth = req.getHeader(HttpHeaders.AUTHORIZATION);                                  if(auth == null ){                      httpResponse.setContentType("application/json");                     httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");                                          return;                  }else{                      if(!auth.startsWith("Basic ")){                          httpResponse.setContentType("application/json");                         httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");                          return;                      }else{                          auth = auth.substring("Basic ".length());                         if(!Base64.isBase64(auth)){                              httpResponse.setContentType("application/json");                             httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");                              return;                          }else{                              byte[] decoded = Base64.decodeBase64(auth);                             auth = new String(decoded, "UTF-8");                              if( !(auth.indexOf(":") > 1) ){                                  httpResponse.setContentType("application/json");                                 httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");                                                                  return;                              }else{                                  String[] credentials = auth.split(":");                                  try {                                      ClientDetailsService jdbcClientDetailsServiceBuilder = clients.jdbc(jdbcTemplate.getDataSource()).build();                                      ClientDetails clientDetails =  jdbcClientDetailsServiceBuilder.loadClientByClientId(credentials[0]);                                      if(!encoder.matches(credentials[1], clientDetails.getClientSecret())){                                          httpResponse.setContentType("application/json");                                         httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");                                             return;                                      }                                                                      } catch (Exception e) {                                      logger.error("{}", e.getMessage());                                      httpResponse.setContentType("application/json");                                     httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");                                      return;                                 }                              }                          }                      }                  }                  chain.doFilter(request, response);      }          @Override     public void destroy() {         logger.info("Destructing filter :{}", this);     } } 

And registered with bean

import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.Ordered;  @Configuration public class OpenApiFilterConfig {      @Autowired     private OpenApiFilter openApiFilter;      @Bean     public FilterRegistrationBean < OpenApiFilter > filterRegistrationBean() {      FilterRegistrationBean < OpenApiFilter > registrationBean = new FilterRegistrationBean<>();          registrationBean.setFilter(openApiFilter);      registrationBean.addUrlPatterns("/open/api/*");      registrationBean.setOrder(Ordered.HIGHEST_PRECEDENCE); //set precedence      return registrationBean;      }  } 
              

Lista de respuestas


Relacionados problema

0  Intermezcling Spring Security OAuth2 y Jose4j  ( Intermixing spring security oauth2 and jose4j ) 
Me preguntaba (antes de intentar implementar algo a lo largo de este camino) sobre un enfoque. Digamos que tengo un sistema de trabajo completo de OAUTH2 (usa...

25  Spring Standal Spring OAuth2 JWT Autorization Server + Cors  ( Standalone spring oauth2 jwt authorization server cors ) 
Entonces, tengo el siguiente servidor de autorización condensado de este ejemplo de Dave Syer @SpringBootApplication public class AuthserverApplication {...

1  Proveedor de autorización de primavera outh2  ( Spring oauth2 authorization provider ) 
Soy nuevo en OAUTH, tengo aplicación con Spring Oauth2 con XML configuración. Han tomado referencia de http://www.beingjavaguys.com/2014/10/spring-secur...

1  Spring Security OAuth2 - ¿Cómo modificar la respuesta de token JSON?  ( Spring security oauth2 how to modify token response json ) 
Estoy obteniendo la respuesta JSON (para la solicitud de Token JWT) de la siguiente manera: { "access_token": "<JWT Access Token>", "token_type": "...

0  Redirigir de CAS (PingFederate) en un código de autor de OAuth CÓDIGO FLUJO Creación de una nueva sesión en el cliente de OAUTH  ( Redirect from caspingfederate in an oauth auth code grant flow creating a new ) 
Tengo una aplicación web que actúa como un cliente de OAUTH, para obtener fichas de acceso, desde PingFederate (actuando como CAS + IDP aquí). Las sesiones de...

1  Aplicación de arranque de primavera OAURH que no redirige a los login.html después de un cierre de sesión exitoso  ( Spring boot oauth application not redirecting to the login html after successful ) 
He seguido boot de primavera y tutorial de oauth2 y hecho Algunos de los cambios para la UI como a continuación. creó un login.html con el contenido deb...

5  Spring Security OAuth2 Java Config: el despacho de controlador falló; La excepción anidada es Java.lang.StackOverflowerRor  ( Spring security oauth2 java config handler dispatch failed nested exception i ) 
Seguridad de resorte configurada con OAUTH2 en la configuración de Java, y client_credeteils fluyen está funcionando bien, pero contraseña flujo está lanz...

9  Spring-Security-OAUTH2 2.0.7 Actualizar Token UserDetails Service Configuración - Se requiere un UserDetailsService  ( Spring security oauth2 2 0 7 refresh token userdetailsservice configuration us ) 
Tendría una pregunta con respecto a la configuración de Spring-Security-Oauth2 2.0.7 por favor. Estoy haciendo la autenticación usando LDAP a través de unAlta...

5  ¿Cómo persistir los tokens de acceso a OAURH en Spring Security JDBC?  ( How to persist oauth access tokens in spring security jdbc ) 
Cuando el usuario inicie sesión, genere un token, por lo que cuando el usuario desea acceder a la información de Restapi, no volverá a iniciar sesión, el códi...

77  ¿Cómo puedo revocar un token JWT?  ( How can i revoke a jwt token ) 
Estoy usando Spring Security OAuth2 y JWT Tokens. Mi pregunta es: ¿Cómo puedo revocar un token JWT? Como se mencionó aquí http://projects.spring.io/spring-...




© 2022 respuesta.top Reservados todos los derechos. Centro de preguntas y respuestas reservados todos los derechos