Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Repo info
Activity
    pvemi
    @vphanibhushanreddy
    DnsNameResolver
    Robert Wiesner
    @rowi1de
    Thats a follow up error: 2021-02-18 16:24:06.239 WARN 2864 --- [or-http-epoll-3] io.netty.channel.AbstractChannel : Force-closing a channel whose registration task was not accepted by an event loop: [id: 0x65e095cd]
    Caused by: java.util.concurrent.RejectedExecutionException: event executor terminated
    DoraRajappan
    @DoraRajappan
    Whats the best solution to upgrade forom spring security 3.x to 4.x and avoid exception below for double slasshes in url? The server encountered an unexpected condition that prevented it from fulfilling the request.</p><p><b>Exception</b></p><pre>org.springframework.security.web.firewall.RequestRejectedException: The request was rejected because the URL was not normalized
    1 reply
    michaelplatt07
    @michaelplatt07
    Hello. We currently have a method behind security using the PreAuthorize tag like so @PreAuthorize("hasAnyRole('ROLE_ADMIN', 'ROLE_CLIENT_ADMIN')"). The scope of the method has increased and we need to allow users who are not admins to call the method but only in specific cases. Is there a way to apply custom logic using spring's built in PreAuthorize?
    1 reply
    Omkar Shetkar
    @Omkar-Shetkar
    Hi All, I have few microservices configured with service accounts. On application start, when I am trying to make an API call to another service, it seems OAuth2AuthorizedClientService .loadAuthorizedClient expects Principal name. But I don't see any Principal name for a service account. Does Spring boot supports service accounts ? Any other approach to make service account calls from Spring boot app ?
    Julius Spencer
    @juliusspencer_twitter

    Hi, I have a spring-boot project that has users authenticating using oauth.

    If I have a signed in user who makes a request to update their username, the principal that comes through with future requests refer to the previous username. The tokens that are stored in the database refer to the old username, not only in the user_name field but also in the oauth_access_token.authentication field. Does anyone know if there is a way that I can update a user's username without them having to sign out and sign in?

    I'm using org.springframework.security.oauth.boot:spring-security-oauth2-autoconfigure.

    Chaturvedi Dewashish
    @ddewashish

    Hi All,

    Below is the code I have

    String[] allowedEndpoints = new String[]{"/preauth/**", "/.~~spring-boot!~/restart/**", "/h2-console/**"};    
    
    @Bean
    public SecurityFilterChain defaultSecurityFilterChain(final HttpSecurity http) throws Exception { // NOPMD
    http
      .csrf().ignoringAntMatchers(allowedEndpoints) //used to allow http post
      .and()
      .authorizeRequests()
      .mvcMatchers(allowedEndpoints).permitAll()
      .requestMatchers(EndpointRequest.toAnyEndpoint()).permitAll()
      .mvcMatchers("/private/**").authenticated()
      //.anyRequest().authenticated()
      .and()
      .formLogin(withDefaults());
    
    http.headers().frameOptions().sameOrigin();
    return http.build();
    }

    This is allowing all endpoints without any authentication except "/private/**" which is expected. As soon as I uncomment .anyRequest().authenticated() it starts asking for authentication for all endpoints.

    My understanding is matchers will go in sequence and as soon as first matcher matches it skips the remaining. So how .anyRequest() is matching which is at the end. Am I missing something?

    Julius Spencer
    @juliusspencer_twitter
    Hi, does anyone know if there's a migration guide for migrating to Spring Security 5’s first-class OAuth support? Also just wondering if this is a dead channel. I'm seeing questions, but not a lot of answers.
    Omkar Shetkar
    @Omkar-Shetkar
    image.png

    In the migration guide for Spring security 5.2, it is mentioned that we can use request interceptor and update RestTemplate by getting values from OAuth2AuthorizedClientService.

    In my case, I am trying to establish client_credential connection using feign client.
    In interceptor, when I call org.springframework.security.oauth2.client.OAuth2AuthorizedClientService#loadAuthorizedClient, I get null as response.
    What could be missing here?
    Thanks
    Config class

    @Configuration
    public class FeignClientConfiguration {
    
        private final Logger logger = LoggerFactory.getLogger(FeignClientConfiguration.class);
    
        private static final String AUTHORIZATION_HEADER = "Authorization";
        private static final String BEARER_TOKEN_TYPE = "Bearer";
    
        private OAuth2AuthorizedClientService clientService;
    
        public FeignClientConfiguration(OAuth2AuthorizedClientService clientService) {
            this.clientService = clientService;
        }
    
        @Bean
        OAuth2AuthorizedClientManager authorizedClientManager(ClientRegistrationRepository clientRegistrationRepository,
                                                              OAuth2AuthorizedClientRepository authorizedClientRepository) {
            OAuth2AuthorizedClientProvider authorizedClientProvider =
                    OAuth2AuthorizedClientProviderBuilder.builder()
                            .clientCredentials()
                            .build();
    
            DefaultOAuth2AuthorizedClientManager authorizedClientManager = new DefaultOAuth2AuthorizedClientManager(
                    clientRegistrationRepository, authorizedClientRepository);
            authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
    
            return authorizedClientManager;
        }
    
    
        @Bean
        public RequestInterceptor oauth2FeignRequestInterceptor() {
            return new RequestInterceptor() {
                @Override
                public void apply(RequestTemplate template) {
                    OAuth2AuthorizedClient oAuth2AuthorizedClient = clientService.loadAuthorizedClient("message-viewer-service", "0oa9zxjby89FnYgz2345");
                    template.header(AUTHORIZATION_HEADER, String.format("%s %s", BEARER_TOKEN_TYPE, oAuth2AuthorizedClient.getAccessToken().getTokenValue()));
                }
            };
        }
    
    }

    application.yaml

    server.port: 8090
    spring:
      application:
        name: message-viewer-service
      security:
        oauth2:
          client:
            registration:
              message-viewer-service:
                client-id: 0oa9zxjby89FnYgz2345
                client-secret: NhxijpJoW_zFr96H2TsoYsgs8WxVcaw4dnwoq4Mx
                authorization-grant-type: client_credentials
                scope: custom_mod
                provider: okta
            provider:
              okta:
                issuer-uri: https://dev-95784560.okta.com/oauth2/default
    irvingwa
    @irvingwa
    Hey all I am running into an issue with our setup of spring security -> keycloak when try and add session replication via spring-session-hazelcast. It looks like I can authenticate but the the redirect is sent to back to the localhost:8080/ instead of localhost:8080/app-name. Does anyone have an example of this setup or tried this before? Thanks in advanced.
    1 reply
    Josh Cummings
    @jzheaux
    @Omkar-Shetkar, the service does not request nor renew the token with the authorization server. I think you likely want to use the OAuth2AuthorizedClientManager to get the token instead.
    2 replies
    Jeongjin Kim
    @thecodinglog
    https://repo.spring.io/plugins-snapshot is not available from anonymous user. It returns 401 status code only. Is there anybody to solve this problem? I can not build the project. I also see https://spring.io/blog/2020/10/29/notice-of-permissions-changes-to-repo-spring-io-fall-and-winter-2020, but it's not working.
    Charly
    @nekperu15739
    Hi all, question, anyone have sample how to enable/create and use-info endpoint in a autorization service?
    willladislaw
    @willladislaw
    Any pointers/references available for Apple's Social Login?
    Ola Petersson
    @olbpetersson

    before having a go at stackoverflow: Does anybody know how to dynamically configure oauth config per request?

    Hi,

    I have a spring-boot application which is configured with a keycloak as an idp. Everything works if I set it up with the configuration

    security:
        oauth2:
          resourceserver:
            opaquetoken:
              client-id: my-id
              client-secret: my-secret
              introspection-uri: /auth/realms/<REALM-ID>/protocol/openid-connect/token/introspect

    and my SecurityFilterChain

    fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain? =
            http.csrf().disable().authorizeExchange()
                .anyExchange().permitAll()
                .and()
                .oauth2Client()
                .and()
                .oauth2ResourceServer { it.opaqueToken(withDefaults()) }
                .build()

    However, keycloak supports multi tenancy via realms, and with every different realm I'd need a different introspection url. Is it possible to configure that dynamically based on, e.g. a header in each request?

    4 replies
    Andreas Falk
    @andifalk
    @olbpetersson you may have a look into multitenancy support of spring security https://docs.spring.io/spring-security/site/docs/5.4.5/reference/html5/#oauth2resourceserver-multitenancy
    Josh Cummings
    @jzheaux
    @willladislaw have you already seen spring-projects/spring-security#9047 ?
    willladislaw
    @willladislaw
    I have not.
    Josh Cummings
    @jzheaux
    There is some discussion on that ticket about configuring Spring Security for Apple login.
    willladislaw
    @willladislaw
    Does it work?
    Josh Cummings
    @jzheaux
    Those posting to the ticket say so. I haven't tried it myself, but I was reminded of that ticket when you asked the question.
    willladislaw
    @willladislaw
    awesome
    nightswimmings
    @nightswimmings
    What is the preferred library for validating JWS tokens when using Boot with Security? Looks like the convention fight is between auth0/java-jwt and jjwt, but I found a security package (org.springframework.security.oauth2.jwt) that seems to include support for it, based on nimbus implementation. I am a bit confused. Where can I find that library? Why is not in the security core? Should I use it in a microservice that does use JWT but not OAUTH? And why thisJWT/JWS implementation preferred over the other 2? (Apologies for that many questions). I feel like a library like that should come built-in, and even autoconfigured so maybe auth0/java-jwt would be the default implementation if the other are not on classpath, provided it seems like the one designed from experts with security in mind, and the widest used with a quickly google search, but I am not proficient on this so I would like to understand the reasons behind current distribution
    8 replies
    nightswimmings
    @nightswimmings
    Another question, sorry. What is the difference between annotating a WebSecurityConfigurerAdapter with @Configuration or the concrete @EnableWebSecurity? (I assume because of my tests that without any of those the adapter does not work)
    I @EnableWebSecurity implicit in Spring Boot, perhaps?
    3 replies
    nightswimmings
    @nightswimmings
    I am really sorry for being that overwhelming :p but there are things I cannot find on the documentation. My last question I hope.. I am using the oauth2-resource-server boot starter. What is exactly the difference between BearerTokenAuthentication and JwtTokenAuthentication? Why do their respective converters (at least the Bearer one) not set DefaultOidcUser/DefaultOauth2User as Principal?
    2 replies
    Francis
    @francis-a
    hey everyone, I'm working through a Spring Security 5 OAuth2 migration. I'm wondering if there is a replacement for the now removed OAuth2ExceptionRenderer or if there is any other kind of guide related to what kind of exception handlers I should be registering as a replacement
    nightswimmings
    @nightswimmings
    I threw this question: https://stackoverflow.com/questions/66896149/does-oauth-and-oidc-make-sense-in-a-scenario-when-you-need-single-sign-on-on-a-m#66909848, because spring-boot-starter-oauth2-resource-server totally fits my needs but somehow I feel lick tricking OAUTH protocol. Would it make sense to split the funcntionality of aforementioned starter into CAS + OAUTH starters? I mean, the whole JWT decoding autconfig thing is really useful evenif one is not using pure OAUTH
    Zakaria Amine
    @zak905
    Hello everyone, in Expression-Based Access Control, is it possible to refer to the request body as an expression argument ? I know it's possible to refer to the path variable, but there is nothing that mentions the request body
    1 reply
    Ben Siegler
    @bs321_gitlab

    Hey everyone,
    I've been working on creating an OTP/2FA solution for spring boot projects. I've been putting some thought into it and think I have a pretty good structure, but before I keep working I think some input from others would be good. I'm also wondering how much of a demand there is for something like this.

    At this point I've got a 2FA filter (a child of AbstractAuthenticationProcessingFilter) down and a configuration looking something like this:

    protected void configure(HttpSecurity http) throws Exception {
            http
                    .csrf().disable()
                    .cors().disable()
                    .twoFactorLogin()
                    .sendStrategy(new AwsEmailSendStrategy())
                    .loginPage("/login").permitAll()
                    .codeService()
                        .inMemoryRepository(cache)
                        .generationStrategy(new SixDigitAuthCodeGenerationStrategy())
                        .expirationTime(45000)
                        .and()
                    .twoFactorRedirectUrl("/2FA")
                    .twoFactorProcessingUrl("/2FA/authenticate")
                    .failureUrl("/login?error=true")
                    .twoFactorFailureUrl("/2FA?error=true")
                    .defaultSuccessUrl("/")
                    .userDetailsService(userDetailService)
                    .and()
                    .logout().permitAll()
                    .and()
                    .authorizeRequests()
                    .anyRequest().authenticated();
    }
    naturzukunft
    @naturzukunft:matrix.org
    [m]

    Hi all, i try to find a simple working example for testing with WebTestClient. My test is working now, with a very basic securitySetting, but without authentication. No i've to test if the principal is existing and ...

    Therefore in my controller i get the principal with:

    ReactiveSecurityContextHolder.getContext()
            .map(SecurityContext::getAuthentication)
            .map(Principal::getName)

    I found that https://docs.spring.io/spring-security/site/docs/current/reference/html5/#test-webtestclient

    @Before
        public void setup() {
            this.rest = WebTestClient
                .bindToApplicationContext(this.context)
                // add Spring Security test Support
                .apply(springSecurity())
                .configureClient()
                .filter(basicAuthentication())
                .build();
        }

    and i found out that i am very annoyed when i find code examples with static imports, but the imports are not included in the example.
    Searching again... and found: SecurityMockMvcConfigurers.springSecurity()but i didn't test Mvc, so this seems to be wrong. And my apply Method anyway didn't accept SecurityMockMvcConfigurers.springSecurity()

    So please redeem me with a beautiful example ;-)
    Thanks a lot

    jay
    @legendjaks

    I am migrating imperative services to reactive services. My API gateway adds double slash(//) when it calls APIs like https://a.b.com/api//products/1.

    When using imperative StrictHttpFirewall.setAllowUrlEncodedSlash() fixed this issue. With WebFlux, getting HTTP 404, due to this issue. Is there any WebFlux equivalent for StrictHttpFirewall.setAllowUrlEncodedSlash()?

    Vladimir Urosevic
    @vurosevic

    Hi, I have a problem with uploading Multipart file (RestController, Spring Security).
    I disabled crsf, and I got 403 error.

          http.csrf().disable().authorizeRequests()
                .antMatchers("/v1/authenticate").permitAll()
                .antMatchers("/h2-console/**").permitAll()
                .anyRequest().authenticated()
                .and().sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);

    application.properties

    spring.servlet.multipart.max-file-size=14096KB
    spring.servlet.multipart.max-request-size=14096KB
    spring.servlet.multipart.enabled=true
    spring.servlet.multipart.location=${java.io.tmpdir}

    Thanks for help

    jay
    @legendjaks

    I am migrating imperative services to reactive services. My API gateway adds double slash(//) when it calls APIs like https://a.b.com/api//products/1.

    When using imperative StrictHttpFirewall.setAllowUrlEncodedSlash() fixed this issue. With WebFlux, getting HTTP 404, due to this issue. Is there any WebFlux equivalent for StrictHttpFirewall.setAllowUrlEncodedSlash()?

    any help here please

    mphmelsen
    @mphmelsen

    Hi, my application needs to support oauth2 / jwt for all endpoints. In addition there is 1 specific endpoints (/api/special/url) that needs to support an apikey next to the oauth2 / jwt support. I've implemented an ApiKeyAuthenticationFilter with an ApiKeyAuthenticationProvider for this. The issue that I'm running into is that when using that special endpoint with a valid jwt token, the apiKeyAuthenticationFilter will throw an exception and that results in authentication to fail and results in a 401. If I provide an apikey, I do get access. My security config is:

            @Override
            protected void configure(HttpSecurity http) throws Exception {
                http.csrf()
                        .disable()
                        .authorizeRequests()
                        .antMatchers("/actuator/health").permitAll()
                        .antMatchers("/**").authenticated()
                        .and()
                        .addFilterAfter(
                                new ApiKeyAuthenticationFilter(authenticationManager()),
                                BearerTokenAuthenticationFilter.class)
                        .oauth2ResourceServer().jwt().jwkSetUri(this.resourceServerProperties.getJwt().getJwkSetUri());
            }

    and the ApiKeyAuthenticationFilter is:

    
    public class ApiKeyAuthenticationFilter extends AbstractAuthenticationProcessingFilter {                          
    
        public ApiKeyAuthenticationFilter(AuthenticationManager authenticationManager) {                              
            super(new AntPathRequestMatcher("/api/special/url", "GET"));                                                                                             
            this.setAuthenticationManager(authenticationManager);                                                     
        }                                                                                                             
    
        @Override                                                                                                     
        public Authentication attemptAuthentication(                                                                  
                HttpServletRequest request, HttpServletResponse response) {                                           
    
            Optional<String> apiKeyOptional = Optional.ofNullable(request.getHeader("Authorization"));                
    
            ApiKeyAuthenticationToken token =                                                                         
                    apiKeyOptional.map(ApiKeyAuthenticationToken::new).orElse(new ApiKeyAuthenticationToken());       
            return getAuthenticationManager().authenticate(token);                                                    
        }                                                                                                             
    
        @Override
        protected void successfulAuthentication(
                HttpServletRequest request,
                HttpServletResponse response,
                FilterChain chain,
                Authentication authResult)
                throws IOException, ServletException {
    
            SecurityContextHolder.getContext().setAuthentication(authResult);
            chain.doFilter(request, response);
        }
    }

    any idea how to resolve this?

    3 replies
    Ken Yee
    @kenkyee_twitter
    Does anyone have a good example of a MockMvc unit test (Spring Boot 2.4.x) for an API endpoint that gets Jwt injected "@AuthenticationPrincipal jwt: Jwt"?
    I found one for injecting an OidcUser by doing this in a unit test:
    SecurityContextHolder.getContext().authentication = authenticationToken(OAuth2AuthenticationToken(...))
    to set the current user info (roles + email) but can't figure out how to do this w/ just a Jwt token.
    Okta's spring security integration doesn't set OidcUser properly so it comes in as Null :-(
    1 reply
    Nick Caballero
    @nickcaballero
    take a look at org.springframework.security.test.context.support.WithSecurityContextFactory - you can use the provided @With* annotations or create your own
    i'm not sure if there's already an implementation out there for jwt. in our project, we use a custom @WithOAuth2User annotation with some attributes for scope, clientId, jti, etc
    Ken Yee
    @kenkyee_twitter
    That seems like an annotation version of the above?
    I think my main issue is I can't figure out how to create a valid security context given only a Jwt object...otherwise, I can stuff it in as above.
    Nick Caballero
    @nickcaballero
    @kenkyee_twitter try using JwtAuthenticationToken?
    you can use org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter to convert an instance of Jwt to the token
    Ken Yee
    @kenkyee_twitter
    Thanks @nickcaballero !
    This works:
    private fun authenticationToken(jwtToken: Jwt): AbstractAuthenticationToken {
        return JwtAuthenticationConverter().apply {
            setPrincipalClaimName("kyee@mycompany.com")
        }.convert(jwtToken)!!
    }
    private fun setupJwtMvcContext() {
        val jwt = Jwt.withTokenValue(ID_TOKEN)
            .header("alg", "none")
            .claim("sub", "kyee@mycompany.com")
            .build()
        SecurityContextHolder.getContext().authentication = authenticationToken(jwt)
        val authInjector = SecurityContextHolderAwareRequestFilter()
        authInjector.afterPropertiesSet()
        mvc = MockMvcBuilders.webAppContextSetup(this.context).build()
    }
    
        // just a valid dummy JWT token
        // see https://developer.okta.com/blog/2019/04/15/testing-spring-security-oauth-with-junit
        private const val ID_TOKEN = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9" +
            ".eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWUsIm" +
            "p0aSI6ImQzNWRmMTRkLTA5ZjYtNDhmZi04YTkzLTdjNmYwMzM5MzE1OSIsImlhdCI6MTU0M" +
            "Tk3MTU4MywiZXhwIjoxNTQxOTc1MTgzfQ.QaQOarmV8xEUYV7yvWzX3cUE_4W1luMcWCwpr" +
            "oqqUrg"
    rahul
    @vikramassmg

    Hi I am using spring SAML, according to the IDP document I need to pass the below parameters:

    SAMLRequest:<encodedSamlRequest>
    ClientID:<ClientID>
    targetURL:https://<host>/sso

    So, how can I pass the above parameters. By default spring will pass only SAMLRequest.
    I tried to RelayState but in key it'll add RelayState.

    2 replies
    ola-zynka
    @ola-zynka

    Hi! If one want to have multiple authentication mechanisms towards the same endpoint, e.g. api-key OR token-information, how would one go about that?

    E.g.

    http.csrf().disable().authorizeExchange()
                .anyExchange().permitAll()
                .and() // Somewhere here I'd like to say that you may authenticate via an API-key and if that is successful the oauth2ResourceServer shouldn't be applied
                .oauth2ResourceServer {
                    it.authenticationManagerResolver(multiTenantResolver)
                }
                .build()
    2 replies
    Christopher Davis
    @cdavis-dissenting-designs_gitlab
    Hi all, I'm looking to create a single spring boot autoconfiguration library that could be consumable by both Spring MVC and Webflux configurations of spring. Is there a shared configuration file somewhere I should be using or overriding or will I have to create two independent libraries? The use case is to require a valid JWT token with specific permissions utilizing @preauthorize and @postauthorize annotations.
    1 reply
    psYchotic
    @stefan:zwanenburg.info
    [m]

    Hey all, I have a question, and it's possible it'll sound a little weird at first, but bear with me. Context: I'm developing a Spring Boot application that is deployed in a Servlet container. That container is configured to handle authentication through one of two means:

    1. Basic authentication
    2. Cookies

    NB: I do not have the means to implement an AuthenticationProvider for whatever mechanism the app container provides

    I've configured security by doing:

    @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter {
      protected void configure(HttpSecurity http) {
        http.jee().mappableAuthorities(/* Mappable roles here */);
      }
    }

    Now, calling my app with basic authentication goes perfectly: the app container receives the request, sees the auth headers, handles authentication, then forwards the request including whatever information it has gathered. All is well.
    But I need to be able to login through other means, to support a frontend. So I defined a controller in my application, which ends up calling HttpServletRequest.login(username, password). This does not work.

    What I've found is that Spring Security wraps the HttpServletRequest (in a HttpServlet3RequestFactory.Servlet3SecurityContextHolderAwareRequestWrapper), and it forwards the call to the AuthenticationManager, which happens to have no provider that is able to perform the authentication. The only way it'll forward the login() call to the actual HttpServletRequest is if there's no AuthenticationManager, but then the PreAuthenticatedAuthenticationProvider can't do its magic...

    I am aware I can disable this wrapping of the HttpServletRequest by disabling Spring Security for the authentication endpoint itself, but then I no longer have things like CSRF protection.

    Is there a way I can make all this work somehow?

    1 reply
    nitineman
    @nitineman
    Although this might be completely related to Spring Security kindly help me with the concern raised as part of the stackoverflow question. https://stackoverflow.com/questions/67469283/spring-security-oauth2-webclient-setup-for-oauth2-client-calls-fails-with-empty