Spring REST same endpoint with and without token

The following endpoint:

@RequestMapping(value = "/activated",method = RequestMethod.GET)
    public GameHolder getAllGames(){
        return gameService.getActivatedGames();
    }

receives several games, and this path can be requested without a token (WebSecurityConifugurerAdapter):

@Override
    public void configure(WebSecurity web) throws Exception {
        //Add Paths which should be ignored by authentication
        web.ignoring().antMatchers("/games/activated");
}

But I call userService and load some additional data if the user is logged in, but now the problem is that ignoring () completely ignores authentication, how can I enter authentication when a token is provided?

I hope you understand what I mean

Edit1

My "doFilterInternal" looks like this:

    @Override
        protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        final String authorization = httpServletRequest.getHeader("Authorization");
                try{
                    if(authorization != null && !authorization.isEmpty() && authorization.toLowerCase().startsWith(tokenType.toLowerCase() + " ")){
                        String[] tokenTypeAndToken = authorization.split(" ");
                        final UserAuthentication tokenAuthentication = new UserAuthentication();
                        tokenAuthentication.setCredentials(tokenTypeAndToken[1]);
                        SecurityContextHolder.getContext().setAuthentication(authenticationManager.authenticate(tokenAuthentication));
                    }
                    else{
                        throw new HttpClientErrorException(HttpStatus.UNAUTHORIZED,"No token provided!");
                    }
                    filterChain.doFilter(httpServletRequest,httpServletResponse);


 }
+4
source share
1 answer

Try overriding configure(HttpSecurity http), and instead of ignoring it, try permitAll. I use the same for my use cases like this.

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
        .antMatchers("/games/activated").permitAll()
}
+2
source

Source: https://habr.com/ru/post/1686813/


All Articles