Where communities thrive

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

    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

    Hi All,

    Below is the code I have

    String[] allowedEndpoints = new String[]{"/preauth/**", "/.~~spring-boot!~/restart/**", "/h2-console/**"};    
    public SecurityFilterChain defaultSecurityFilterChain(final HttpSecurity http) throws Exception { // NOPMD
      .csrf().ignoringAntMatchers(allowedEndpoints) //used to allow http post
    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
    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

    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?
    Config class

    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;
        OAuth2AuthorizedClientManager authorizedClientManager(ClientRegistrationRepository clientRegistrationRepository,
                                                              OAuth2AuthorizedClientRepository authorizedClientRepository) {
            OAuth2AuthorizedClientProvider authorizedClientProvider =
            DefaultOAuth2AuthorizedClientManager authorizedClientManager = new DefaultOAuth2AuthorizedClientManager(
                    clientRegistrationRepository, authorizedClientRepository);
            return authorizedClientManager;
        public RequestInterceptor oauth2FeignRequestInterceptor() {
            return new RequestInterceptor() {
                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()));


    server.port: 8090
        name: message-viewer-service
                client-id: 0oa9zxjby89FnYgz2345
                client-secret: NhxijpJoW_zFr96H2TsoYsgs8WxVcaw4dnwoq4Mx
                authorization-grant-type: client_credentials
                scope: custom_mod
                provider: okta
                issuer-uri: https://dev-95784560.okta.com/oauth2/default
    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
    @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
    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.
    Hi all, question, anyone have sample how to enable/create and use-info endpoint in a autorization service?
    Any pointers/references available for Apple's Social Login?
    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?

    1 reply
    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