Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Repo info
Activity
    Sanjeev Ghimire
    @sanjeevghimire
    this is my API definition:
    @GetMapping("/browse/{videoCatalogType}")
        @PreAuthorize("hasAnyRole(\"" + AuthoritiesConstants.ADMIN + "," + AuthoritiesConstants.CHALCHITRA + "," + AuthoritiesConstants.SUBSCRIBED + "\")")
    Ruslan Stelmachenko
    @xak2000
    @sanjeevghimire Make sure the roles you passed in to hasAnyRole method doesn't contain a ROLE_ prefix. If they contain that prefix, use hasAnyAuthorityinstead.
    piyush-devnow-io
    @piyush-devnow-io
    Hi, I have an api which registers a user into my system. I call it signup api which takes a request including email, password and username and creates a record in the database.
    There is another api which logs in the user (the sign in api) which provides an access token, its expiration duration, emailId as a response.
    My question is -> Can I provide an access token in the response of the signup api as a separate data node in the response? Is it a good design practice ? Is there any other reason why I should not include a access token in the signup api response ?
    Rakesh
    @ravening
    Hi, Im implementing security using JWT in spring boot by following the guide in https://auth0.com/blog/implementing-jwt-authentication-on-spring-boot/ . I am unable to handle the TokenExpiredExcpetion. Does anyone have experience or code samples in doing so?
    Andrew Zurn
    @AndrewZurn

    I'm trying to enable spring security only on the actuator endpoints, and allow all other requests, regardless of auth scheme to pass into the app code (which handles security in it's own regard).

    Right now this is what I have:

        @Bean
        fun securityWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
            // NOTE: This will only add spring security to the actuator endpoints, all other endpoints will be handled
            // by the JWT auth handling.
            // https://stackoverflow.com/questions/38403740/authenticate-only-selected-rest-end-points-spring-boot
            return http.authorizeExchange()
                .pathMatchers("/actuator/**").authenticated()
                .anyExchange().permitAll()
                .and().httpBasic()
                .and().csrf().disable()
                .build()
        }
    
        @Bean
        fun userDetailsService(): MapReactiveUserDetailsService {
            return MapReactiveUserDetailsService(
                User.withDefaultPasswordEncoder()
                    .username(actuatorAdminUsername)
                    .password(actuatorAdminPassword)
                    .roles("SUPERUSER")
                    .build()
            )
        }

    This works to ensure that:
    1) http basic auth can be used to access the actuator endpoints
    2) any bearer request is passed through into the app code (which is what I want)

    but doesn't allow an http basic auth request to pass through and be handled by my app code. I've tried a few different incantations to get it working as expected, but mostly get the current state or I get it to pass through http basic requests (at which case my auth on the actuator endpoints doesn't work). Any pointers?

    Andrew Zurn
    @AndrewZurn
    Something else of interest, if I change the Authorization header key on the request I'm sending to Proxy-Authentication, it passes through just fine.
    Andrew Zurn
    @AndrewZurn
    Looks like using the securityMatcher on the http object and setting up separate filters seems to have done the trick.
    Marco Zanghì
    @marcozanghi
    Hi everyone, I am trying to save to db an acl entry using acl spring. I am using the mustableaclservice but i can't see any new record in the db. (I am using also ehcache) any ideas?
    choubani amir
    @amirensit
    hello.
    Please any idea what is the difference between these two dependencies:
    spring-security-config and spring-security-web ?
    James Howe
    @OrangeDog
    @amirensit they do completely different things, as indicated by the names
    Marco Zanghì
    @marcozanghi
    hi @OrangeDog, do you have any ideas how to save acl entries by using spring security support? It is possible to do that whit jdbc mutable service?
    James Howe
    @OrangeDog
    That's literally what JdbcMutableAclService says it's for
    Marco Zanghì
    @marcozanghi
    Sì, ma quando eseguo un updateAcl non ho la relativa voce acl nella tabella acl_entry
    I am using ehcache .
    Yes but when i perform an updateAcl i don't have the related acl entry into acl_entry table
    James Howe
    @OrangeDog
    transaction settings perhaps
    Marco Zanghì
    @marcozanghi
    thanks.. the problem was the @transactional annotation. I have deleted it and now it works
    Caleb Cushing
    @xenoterracide
    @jgrandja https://stackoverflow.com/q/56844287/206466 could you verify whether what Ii'm asking is possible? if it's not I think I should open a ticket to make it possible
    Mohsin AR
    @iammohsinar
    how to secure both web browser request (thymeleaf) and Restful request in one spring boot project ??
    Caleb Cushing
    @xenoterracide
    molexx
    @molexx
    Is there a correct way for a REST API to return a simple short text message along with a 403? I've tried various combinations of setting the contentType and response.writer.println() and response.writer.write()but I can't get it to display in the browser.
    Ruslan Stelmachenko
    @xak2000

    @molexx How did you setup this? You need to create a custom AccessDeniedHandler implementation and set it through HttpSecurity.exceptionHandling().accessDeniedHandler(myAccessDeniedHandler). Then you can implement handle method as you wish.
    For example:

            response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
            response.setStatus(HttpStatus.FORBIDDEN.value());
            response.getWriter().write(objectMapper.writeValueAsString(responseBody));

    Or, in your case, you can set content-type to text/plain and write a String.

    molexx
    @molexx
    @xak2000 thanks yes I have the accessDeniedHandler set up, looks very similar to that but not exactly, I'll try those thanks!
    molexx
    @molexx
    @xak2000 done that, thanks, looking in the Firefox devtools its a 403 with responseType 'json' but there is no body - it just says 'No response data available for this request'. I'm logging to ensure that code is being run and a message is being written.
    response content-length is 0
    Ruslan Stelmachenko
    @xak2000
    It's strange. Maybe some filter/interceptor started the output before using response.getOutputStream()? Then response.getWriter() will not work AFAIK.
    Also try to add response.flushBuffer() at the end of the handle() execution.
    molexx
    @molexx
    @xak2000 no flushBuffer() doesn't help :-( it's the last line of the handler.
    molexx
    @molexx
    It was setting some cookies but I've commented that out now. Nothing else touching the response in the handler.
    molexx
    @molexx
    Works when I call writer.close(), didn't think I'd have to. Thanks for the pointers!
    Marco Zanghì
    @marcozanghi
    Can I ask you how it is possible to force ehcache to persists a record in db when i update acl. I am trying to test it into a junit test but it seems that the acl update is stored only in memory
    James Howe
    @OrangeDog
    @marcozanghi it will be transaction config again
    I go to http://demo.bkit.vn , login success, then redirect to http://localhost:8081/desktop , then web-app fail.
    Marco Zanghì
    @marcozanghi
    @OrangeDog thanks my fault!
    James Howe
    @OrangeDog
    Is it possible to @PostFilter a Page?
    Filip Hanik
    @fhanik
    @donhuvy https://docs.spring.io/spring-boot/docs/1.1.3.RELEASE/reference/html/howto-embedded-servlet-containers.html#howto-use-tomcat-behind-a-proxy-server
    server.tomcat.remote-ip-header=x-forwarded-for
    server.tomcat.protocol-header=x-forwarded-proto
    Nasibulloh
    @Nasibulloh
    @xak2000 Thanks a lot
    compfantasy
    @compfantasy
    Hello team, several days ago, I found I can not use jwsAlogrithm but RS256 because it is hard coded in the authentication provider, please refer to spring-projects/spring-security#6883, per Joe Grandja's advice, I upgrade the version of spring-security-oauth2-client and spring-secuirty-oauth2-core to 5.2.0.M2, but I don't know how to change the jwsAlgorithmResolver for OidcAuthorizationCodeAuthenticationProvider, would you please kindly give me some tips?
    hersonalfarogl
    @hersonalfarogl

    @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"
        }
      }
    }

    Have you guys found a way to do Unit Testing on either @OAuth2Client or @ResourceServer mode when using WebFlux? spring-security-test examples (https://docs.spring.io/spring-security/site/docs/current/reference/html/test.html#test-method) only demonstrate how to mock Basic Auth.
    If there's a RTFM link, I would appreciate it as well.

    Henrique Luis Schmidt
    @henriquels25
    Hi team,
    I created a question related to testing an oauth2 resource server using @WebMvcTest (https://stackoverflow.com/questions/57103518/spring-security-oauth2-resource-server-tests).
    I would appreciate if someone could take a look at that.
    choubani amir
    @amirensit
    hello.
    I am implementing implicit-flow with oauth2. The problem I am having now is what should be the value of redirectUris for a mobile application.
    I tried this window.location.origin but It does not work. Any idea please. (I am using ionic 4 as front end client). For dev I set http://localhost:8100 and It works.
    James Howe
    @OrangeDog

    I'm trying to add a token granter with spring-security-oauth2, but it seems to be very difficult. The default one is an anonymous class that wraps a CompositeTokenGranter created on first use. There's no way to modify the list of granters it will use, nor modify them after it's been made. To construct any granter (in order to set one onAuthorizationServerEndpointsConfigurer) you need to already have three other of the objects managed by that configurer.

    Am I missing something?

    James Howe
    @OrangeDog
    Right now I've got this horrible thing
    @Bean
    public TokenGranter internalTokenGranter(AuthorizationServerEndpointsConfiguration endpoints)
            throws ReflectiveOperationException
    {
        AuthorizationServerEndpointsConfigurer configurer = endpoints.getEndpointsConfigurer();
        TokenGranter tokenGranter = configurer.getTokenGranter();
        tokenGranter.grant(null, null);
        Field field = tokenGranter.getClass().getDeclaredField("delegate");
        field.setAccessible(true);
        CompositeTokenGranter compositeTokenGranter = (CompositeTokenGranter) field.get(tokenGranter);
        compositeTokenGranter.addTokenGranter(new InternalTokenGranter(
                configurer.getTokenServices(),
                configurer.getClientDetailsService(),
                configurer.getOAuth2RequestFactory()
        ));
        return tokenGranter;
    }
    Filip Hanik
    @fhanik

    @OrangeDog There are different ways to solve this, I'm just showing you one way.
    The Cloud Foundry UAA project created a class called AddTokenGranter (link)

    The library exposes the composite granter as oauth2TokenGranter, in the UAA xml they add token granters in 3 different places as such:

        <bean id="addUserTokenGranter"
              class="org.cloudfoundry.identity.uaa.oauth.token.AddTokenGranter">
            <constructor-arg name="userTokenGranter" ref="userTokenGranter"/>
            <constructor-arg name="compositeTokenGranter" ref="oauth2TokenGranter"/>
        </bean>
    James Howe
    @OrangeDog
    @fhanik How do they get the composite granter though? That's the messy bit.
    Sudhakar
    @sudhakarbetha

    Hello,
    I am trying to secure my /api/* via OAuth2 Authroization Code, I have the oauth2 working for endpoint
    http://localhost:8080/ where the redirect url is http://localhost:8080/login/oauth2/code/azure

    but when I try to hit http://localhost:8080/api/user , I get
    "The reply url specified in the request does not match the reply urls "
    where the redirect_uri=http://localhost:8080/api/user

    Here is my SecurityConfig

      http.authorizeRequests()
                    .anyRequest().authenticated()
                    .and()
                    .oauth2Login();
    James Howe
    @OrangeDog
    @sudhakarbetha you seem confused about how oauth works. An authorization code is a grant to obtain an access token from an authorisation server. It doesn't secure a resource server.
    Sudhakar
    @sudhakarbetha

    THanks @OrangeDog I was trying to write an OAuthClient, redirect the user to login against Azure Active Directory and then provide access to my /api/* upon successful login
    I was able to do that now, but when I try to do

     String response = oAuth2RestTemplate.getForObject("https://graph.microsoft.com/v1.0/me", String.class);

    This request is redirecting again to Azure AD and failing at "The reply url specified in the request does not match the reply urls "
    I thought oAuth2RestTemplate does not redirect to Azure AD when accessing graph API instead, it will use the same access token obtained earlier

    Is there anything I am missing ? @OrangeDog