Where communities thrive

  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
Repo info
    Ola Petersson

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


    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

              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? =
                .oauth2ResourceServer { it.opaqueToken(withDefaults()) }

    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
    @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
    @willladislaw have you already seen spring-projects/spring-security#9047 ?
    I have not.
    Josh Cummings
    There is some discussion on that ticket about configuring Spring Security for Apple login.
    Does it work?
    Josh Cummings
    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.
    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
    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
    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
    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
    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
    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

    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 {
                    .sendStrategy(new AwsEmailSendStrategy())
                        .generationStrategy(new SixDigitAuthCodeGenerationStrategy())

    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:


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

        public void setup() {
            this.rest = WebTestClient
                // add Spring Security test Support

    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


    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

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

        http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);



    Thanks for help


    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


    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:

            protected void configure(HttpSecurity http) throws Exception {
                                new ApiKeyAuthenticationFilter(authenticationManager()),

    and the ApiKeyAuthenticationFilter is:

    public class ApiKeyAuthenticationFilter extends AbstractAuthenticationProcessingFilter {                          
        public ApiKeyAuthenticationFilter(AuthenticationManager authenticationManager) {                              
            super(new AntPathRequestMatcher("/api/special/url", "GET"));                                                                                             
        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);                                                    
        protected void successfulAuthentication(
                HttpServletRequest request,
                HttpServletResponse response,
                FilterChain chain,
                Authentication authResult)
                throws IOException, ServletException {
            chain.doFilter(request, response);

    any idea how to resolve this?

    3 replies
    Ken Yee
    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
    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
    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
    @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
    Thanks @nickcaballero !
    This works:
    private fun authenticationToken(jwtToken: Jwt): AbstractAuthenticationToken {
        return JwtAuthenticationConverter().apply {
    private fun setupJwtMvcContext() {
        val jwt = Jwt.withTokenValue(ID_TOKEN)
            .header("alg", "none")
            .claim("sub", "kyee@mycompany.com")
        SecurityContextHolder.getContext().authentication = authenticationToken(jwt)
        val authInjector = SecurityContextHolderAwareRequestFilter()
        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" +

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


    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

    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?


                .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 {
    2 replies
    Christopher Davis
    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

    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
    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
    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
    hi, is there a digest authentication for spring security webflux?
    2 replies
    1 reply

    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
    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.
    class TestController(
        webClientBuilder: WebClient.Builder,
    ) {
        private val webClient = webClientBuilder
        fun createNewValue(
            authentication: JwtAuthenticationToken,
        ): Mono<String> = webClient.post()
            .headers {
    3 replies
    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
    Spring Security OAuth not redirecting authorization URL given YML file. can someone help me with this
    1 reply
    Knut Schleßelmann
    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
    Is there a way to turn off OAuthResourceServer JWT authentication easily to run locally?
    5 replies
    Benjamin DeLillo

    What is the difference, in a WebSecurityConfigurerAdapter subclass, between


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



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


    2 replies
    Benjamin DeLillo
    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
    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
    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
    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.