Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Repo info
Activity
    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?

    2 replies
    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
    Jordan Finci
    @finci-square
    is ACL's being deprecated? I am looking at standardizing our domain object security in our project and the spring ACL implementation seems like a great fit but im see some deprecation annotations
    1 reply
    Daniel Gradecak
    @dgradecak
    hi, is there a digest authentication for spring security webflux?
    2 replies
    nitineman
    @nitineman
    1 reply
    psYchotic
    @stefan:zwanenburg.info
    [m]

    marcusdacoregio (Marcus Hert Da Corégio)

    I don't think if I understand why you need to call HttpServletRequest#login directly, and why you can not provide your own AuthenticationProvider implementation.

    If Stackoverflow is the preferred medium for getting support, I'll be happy to move the conversation there, but in short: the authentication system being used is abstracted away from me by the operations team, that provisions the servlet container I deploy in.
    This container thus handles authentication, and the only API available to me is HttpServletRequest#login.

    During normal operation (CORRECTION: once logged in), the container injects principals in the requests, and Spring Security can then do its thing.

    4 replies
    MarkusKlussmann1337
    @MarkusKlussmann1337
    Hey there, im trying call a downstream service with the same token which was used to call my service. Its working using the JwtAuthenticationToken in the headers as showcased below. I was wondering if there is a more elegant way to achieve this or if this is bad bad practice in general.
    @RestController
    @RequestMapping("test")
    class TestController(
        webClientBuilder: WebClient.Builder,
    ) {
        private val webClient = webClientBuilder
            .baseUrl("https://some.url")
            .build()
    
        @PostMapping
        @PreAuthorize("hasAnyRole('${Roles.SOME_ROLE}','${Roles.SOME_OTHER_ROLE}')")
        fun createNewValue(
            authentication: JwtAuthenticationToken,
        ): Mono<String> = webClient.post()
            .uri("/some-endpoint")
            .headers {
                it.setBearerAuth(authentication.token.tokenValue)
            }
            .bodyValue(valueToPost)
            .retrieve()
            .bodyToMono<String>()
    }
    3 replies
    bibek
    @bibekjyoti_twitter
    Hi i want to get the client_id in my authorization server login page before login to show from which client the request has come. How can I achieve that.
    3 replies
    Rajeev Kumar kallempudi
    @rajeevprasanna
    Spring Security OAuth not redirecting authorization URL given YML file. can someone help me with this
    https://stackoverflow.com/questions/67700589/spring-security-not-redirecting-to-given-oauth-authentication-url
    1 reply
    Knut Schleßelmann
    @kschlesselmann
    Is there an annotation to remove the effect of @WithMockUser entirely? @WithAnonymousUser seems te keep some kind of security context (if you really want to test an API for 401 vs 403)
    7 replies
    Jonathan Kupcho
    @jkupcho
    Is there a way to turn off OAuthResourceServer JWT authentication easily to run locally?
    5 replies
    Benjamin DeLillo
    @OneGeek

    What is the difference, in a WebSecurityConfigurerAdapter subclass, between

    A:

    • overriding configure(HttpSecurity http) and calling http.authenticationProvider(myProvider)
    • overriding configure(AuthenticationManagerBuilder auth) and doing nothing at all (which implicitly sets disableLocalConfigureAuthenticationBldr = false)

    and

    B:

    • overriding configure(AuthenticationManagerBuilder auth) and calling auth.authenticationProvider(myProvider)

    ?

    2 replies
    Benjamin DeLillo
    @OneGeek
    How do I turn off HttpOnly on the JSESSIONID cookie when I am exclusively using Spring Security (no spring-boot, no spring-session). I've tried implementing a filter, and tried inserting it in various places in the filter chain, but the response object it sees never has JSESSIONID set. I've also tried writing an HttpServletResponseWrapper subclass, but it never sees addCookie("JSESSIONID", ...) get called. I've also tried implementing a ServletContextListener and calling initEvent.getServletContext().getSessionCookieConfig().setHttpOnly(false) inside the contextInitialized method.
    Bassem Khadige
    @bkhadige_gitlab
    Hello is it possibe to define a userAuthoritiesMapper in a oauth2-resource-server configuration ? I need to define the authorities from a "roles" array defined in the userAttributes
    4 replies
    Josh Dev
    @JoshDev
    Hi - I am trying to incorporate multiple OAuth2 logins (Google and Microsoft/Azure) using Spring Security Oauth (spring.security.oauth2.client.registration.provider). For some reason when I login into one of them(Google), the other(Microsoft) is failing (com.microsoft.aad.msal4j.AcquireTokenByAuthorizationGrantSupplier failed). It seems Spring trying to configure both at once. How do I properly setup multiple OAuth2 Login providers in one login screen?
    1 reply
    pcg_
    @pcg_:matrix.org
    [m]
    Hello everyone. I'm building an REST API which requires JWT signature verification from a JWKS with a .well-known configuration, but I'm struggling to find a clear specification on how to do it with spring-security.
    I've managed to achieve the desire result with fusionauth-jwt. Is there an appropriate documentation on how to do it with the "spring way"?
    Thanks in advance.