by

Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Repo info
Activity
    choubani amir
    @amirensit
    but now I get an error of 404 not found after being redirected to http://localhost:port/login
    James Howe
    @OrangeDog
    Is there a reason why AuthenticationEntryPoints don't return a 500 on InternalAuthenticationServiceExceptions?
    René S
    @reneschroeder0000

    hi, what is the best way to mock an oauth2-openid connect server for my client? i would like to have something like a local test repository that doesnt need to query other services.

    my current implementation is as follows:

    @TestConfiguration
    class OAuth2TestConfiguration {
    
        @Bean
        fun getInMemoryReactiveClientRegistrationRepository(
                @Value("\${spring.security.oauth2.client.registration.foo.client-id}") clientId: String,
                @Value("\${spring.security.oauth2.client.registration.foo.client-secret}") clientSecret: String,
                @Value("\${foobar.token-uri}") tokenUri: String
        ): ReactiveClientRegistrationRepository {
            return InMemoryReactiveClientRegistrationRepository(
                    ClientRegistration.withRegistrationId("foo")
                            .tokenUri(tokenUri)
                            .clientId(clientId)
                            .clientSecret(clientSecret)
                            .scope("doesnt matter here")
                            .authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS)
                            .build()
            )
        }
    
        @Bean
        fun getServerOAuth2AuthorizedClientRepository(
                @Autowired authorizedClientService: ReactiveOAuth2AuthorizedClientService
        ): AuthenticatedPrincipalServerOAuth2AuthorizedClientRepository {
            val repo = AuthenticatedPrincipalServerOAuth2AuthorizedClientRepository(authorizedClientService)
            repo.setAnonymousAuthorizedClientRepository(UnAuthenticatedServerOAuth2AuthorizedClientRepository())
            return repo
        }
    
        @Bean
        fun getInMemoryReactiveOAuth2AuthorizedClientService(
                @Autowired repository: ReactiveClientRegistrationRepository
        ): ReactiveOAuth2AuthorizedClientService = InMemoryReactiveOAuth2AuthorizedClientService(repository)
    
        @MockBean
        lateinit var jwtDecoder: ReactiveJwtDecoder
    }

    and wiremock for the tokenUri:

    {
      "request": {
        "method": "POST",
        "url": "/token"
      },
      "response": {
        "status": 200,
        "headers": {
          "Content-Type": "application/json"
        },
        "jsonBody": {
          "access_token": "some token",
          "token_type": "Bearer"
        }
      }
    }
    Josh Cummings
    @jzheaux
    @OrangeDog, InternalAuthenticationServiceException means that the user's attempt to authenticate failed due to an internal error, so handling that case isn't really in the realm of an entry point. An AuthenticationFailureHandler would be a better fit for that. An entry point simply recognizes that the user isn't authenticated and responds accordingly, like with a redirect to a login page or with a 401.
    Josh Cummings
    @jzheaux
    Your question, @OrangeDog, makes me think that bearer token authentication in the Resource Server ought to expose a failure handler, so I've created a ticket for that. spring-projects/spring-security#7009
    Josh Cummings
    @jzheaux
    @reneschroeder0000 Your approach seems fine, e.g. with wiremock. I've used MockWebServer in the past to achieve similar ends. Is there something that your current approach is not allowing you to do, or are you asking if there is an easier way than what you already have?
    James Howe
    @OrangeDog
    @jzheaux it's the Authorization Server that's giving me problems, when the ClientDetailsService thows an exception
    see also spring-projects/spring-security-oauth#483
    I added some AfterThrowing advice so at least it gets logged
    David Steiman
    @xetys

    hey guys, I've got a weird behavior when forwarding OAuth2 JWT access token in an @Async thread. In details: I am using a FeignClient to communicate with another microservice and use SecurityContextHolder.getContext().getAuthentication().getDetails (which is a OAuth2AuthenticationDetails) to forward the same auth header, which was found in the users' origin request. When NOT using @Async, this works fine. As soon as I use the feign client inside a async method, the request fails as SecurityContextHolder.getContext().getAuthentication() is NULL. This issue can be solved by setting the strategy to SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_INHERITABLETHREADLOCAL). But when I do this, there comes another issue: the async thread remembers the first security context it gets and ignores new tokens. So when an access token expired, all communication is broken.

    The only solution I've found so far is setting the strategy to MODE_GLOBAL. But I am not sure if that is a good solution, and which risks I have opened by this

    Josh Cummings
    @jzheaux
    @matin-reza Are you using opaque tokens or JWTs? If opaque tokens, then you can use @Cacheable to cache the results of RemoteTokenServices#loadAuthentication.
    Josh Cummings
    @jzheaux
    @xetys Would you be able to provide a sample so I could take a look?
    René S
    @reneschroeder0000

    @reneschroeder0000 Your approach seems fine, e.g. with wiremock. I've used MockWebServer in the past to achieve similar ends. Is there something that your current approach is not allowing you to do, or are you asking if there is an easier way than what you already have?

    its fine, but just doesnt feel quite right. especially setting the anonymous client repo explicitly. i thought that maybe there would be some test support.

    choubani amir
    @amirensit
    hello. Any idea what will be tha value of redirectUris in ClientDetailsServiceConfigurer for prod use (implicit flow) ?
    The front end user is a mobile hybrid app.
    in dev here is my configuration:
    @Override
        public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
           clients.inMemory().withClient("sampleClientId")
                .authorizedGrantTypes("implicit")
                .scopes("read", "write", "mobile")
                .redirectUris("http://localhost:8100") // how shall I set this value ?
                .autoApprove(true)
                .accessTokenValiditySeconds(1800);
    }
    Subham Ashish
    @SubhamAshish

    hello all i am using spring secuirty basic
    Spring boot version is 1.5.14.

    i wanted to prevent session hijacking is there any way to do?

    i am facing an issue like once i logged in chrome browser, after that i copied the session and with the same session i tried login different browser and its successful , how to prevent that?
    @josiahhaswell
    Subham Ashish
    @SubhamAshish
    @jzheaux please have a look
    James Howe
    @OrangeDog
    @amirensit it should be something that the app has selected, that it is able to intercept.
    choubani amir
    @amirensit
    @OrangeDog :thumbsup:
    Caleb Cushing
    @xenoterracide
      @Bean
        open fun configure(http: ServerHttpSecurity): SecurityWebFilterChain {
            return http.authorizeExchange()
                // .mvcMatchers(HttpMethod.PUT, "/monitor/**").permitAll()
                .anyExchange().authenticated()
                .and()
                .cors().disable()
                .csrf().disable()
                .build()
        }
    is it possible to do an mvc matcher with reactive, or only ant matchers?
    KayKoder
    @kmaverick
    Anyone know how to make an ssl connection in java
    Caleb Cushing
    @xenoterracide
    @kmaverick that's a big, depends on what you are trying to achieve. if you're making an https connection to a site with a cert signed by a pretrusted CA it's easy, however I suspect you're not trying to do that
    KayKoder
    @kmaverick
    @xenoterracide That is exactly what I am trying to do
    @xenoterracide Yes
    I have the cert, and the trust store ca and the cert password
    I just dont know the most simple way to establish the ssl conneciotn
    connection
    Caleb Cushing
    @xenoterracide
    @kmaverick if you're trying to do an https connection, just go ahead and make one with your http client
    KayKoder
    @kmaverick
    but how do I use the server key and passwords
    @xenoterracide I am not sure how to use the keys after I make a servlet and establish an http connection
    Felipe Adorno
    @FelipeAdorno
    hi guys I have problem when try use RedisTokenStore when clientId has a hyphen, anyone knows about this?
    I change the code to this and works fine:
    byte[] clientId = serializeKey(CLIENT_ID_TO_ACCESS
                    + authentication.getOAuth2Request().getClientId().replace("-", ""));
    Knut Schleßelmann
    @kschlesselmann

    Hi! Right now I try to add https://docs.spring.io/spring-security/site/docs/5.1.5.RELEASE/reference/htmlsingle/#preauth as a new possible way to authenticate users. To fetch the token I have to read a provided cookie. Which parts do I have to provide to get such a setup in a Spring Boot application up and running? Right now I have a AbstractPreAuthenticatedProcessingFilter reading the cookie,

    @Configuration
    class SecurityConfiguration : WebSecurityConfigurerAdapter() {
    
        override fun configure(http: HttpSecurity) {
            val filter = CookieFilter()
            filter.setAuthenticationManager(authenticationManager())
    
            http
                    .addFilterBefore(filter, AbstractPreAuthenticatedProcessingFilter::class.java)
                    .authorizeRequests()
                    .anyRequest().authenticated()
        }
    }

    setting up the filter and a @Service AuthenticationUserDetailsService<PreAuthenticatedAuthenticationToken> which should build the UserDetails based on the token value. I think I'm missing one little step of plumbing here so that everything works together?

    Nasibulloh
    @Nasibulloh
    @dsyer Hi, I am using spring-security-oauth2 . I am sending a request but I am getting the only previous token until the token has expired. But I don't need getting a single token for a user. I want to get a new token for every request. This for multiple users session. The problem is when I get a token, I use it in a device. But I have multiple devices with a single account. If I want to log out(invalidate the token), All my sessions are logging out. This is not a suitable way.
    Ruslan Stelmachenko
    @xak2000
    @Nasibulloh You can implement your own AuthenticationKeyGenerator which can take into account some request param like device_id. Then you can pass this generator to your tokenStore and it will generate new access token based on different keys (returned from AuthenticationKeyGenerator.extractKey). The uniqueness of this key determines if same or new access token will be used.
    Mohsin AR
    @iammohsinar

    hello guys i am implementing user authentication in spring security i am stuck at when authentication exception occur at loginfilter then method of LoginFilter.java

    @Override
        protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
                AuthenticationException failed) throws IOException, ServletException {
            super.unsuccessfulAuthentication(request, response, failed);
            ObjectMapper mapper = new ObjectMapper();
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(mapper.writeValueAsString(authException.getAuthentication().getInfo()));
    
        }

    gets executed in above method i have added Info object in response.
    now my question is that after LoginFilter AuthFilter(present in spring security configuration) is executed but only in error or any java exception i don't want this to executed on exception because if user enter wrong user and pass then i want to send response from LoginFilter.

    LoginFilter.java

    public class LoginFilter extends AbstractAuthenticationProcessingFilter {
    // constructor and beans;
    @Override
        public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
                throws AuthenticationException, IOException, ServletException {
          // other logic
            return auth;
        }
    @Override
        protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain,
                Authentication authResult) throws IOException, ServletException {
    // logic
    }
    
    @Override
        protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
                AuthenticationException failed) throws IOException, ServletException {
            super.unsuccessfulAuthentication(request, response, failed);       
    // this method is executed when user attempt wrong username or pass
            ObjectMapper mapper = new ObjectMapper();
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(mapper.writeValueAsString(authException.getAuthentication().getInfo()));
        }

    AuthFilter.java

    public class AuthFilter extends GenericFilterBean {
    @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
                throws IOException, ServletException {
    // some other logic
    if (auth.isAuthenticated())
                    chain.doFilter(request, response);
                else {
                    ObjectMapper mapper = new ObjectMapper();
                    res.getWriter().write(mapper.writeValueAsString(auth.getInfo()));
                }
    
    }
    }

    security config

    .and()
    .addFilterBefore(new LoginFilter(new AntPathRequestMatcher("/budget/login")),
                            UsernamePasswordAuthenticationFilter.class)
                    .addFilterBefore(new AuthFilter(),
                            UsernamePasswordAuthenticationFilter.class);
    Mohsin AR
    @iammohsinar
    BTW AuthFilter is for if user is already authenticated so it is working fine for that purpose. i need to stop execute this on exception which occurs in LoginFilter for wrong user and pass
    Hamza Ouni
    @HamzaOuni17_twitter
    Hello, how can i add a custom attribute to samlRequest (im my case the attribute specify the sending channel : web or mobile).
    i do some research about this , i found two solutions either put this in extensions element or in the relayState?
    Sivabalan
    @jofisiva
    Hello Team
    We are currently using wso2 for identity access management and SSO integration with ADFS .Plan to cut down WSO2 dependency
    Is Spring Security 5 can give all functionality ?
    Any thoughts
    we are looking some kind of open source access identity access management
    With SSO capabilities
    James Howe
    @OrangeDog
    There are Spring Security implementations of SAML and OpenID Connect
    Sivabalan
    @jofisiva
    thanks James
    Keerthi Meda
    @krmeda

    Hello Team...
    I am trying to make a starter library (for reactive microservices) for my organization where in I want to configure only the /actuator/** endpoints. I managed to isolate the configuration into an auto-configuration library and am defining the securityWebFilterChain bean where i am able to use a securityMatcher and perform the filtering...

    Further down the chain, when one of the microservices using this library wants to add their own authentication scheme (e.g JWT checking) to the path, they are now having to re-define the full bean including the actuator config to get the required results.

    Is there a built in way of allowing for this customization and injection of additional securityMatchers downstream if a library does the init upstream?

    Sanjeev Ghimire
    @sanjeevghimire
    is it possible to debug @PreAuthorize?
    I added a ROLE at runtime and when I try to hit the API which has that role in hasAnyRole the API gives me Access Denied Exception
    Any Idea?
    when I get that user I see that ROLE in the list of authorities