Java based configuration to enable spring anonymous access

I want to enable the use of "ROLE_ANONYMOUS" to allow anonymous access to some URLs in my application. And I used the configuration below.

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .requestCache()
            .requestCache(new NullRequestCache()).and()
        .anonymous().authorities("ROLE_ANONYMOUS").and()
        .exceptionHandling().and()
        .servletApi().and()
        .headers().cacheControl().and()
        .authorizeRequests()
            .antMatchers("/").permitAll()
            .antMatchers("/profile/image").permitAll()
            .antMatchers("/favicon.ico").permitAll()
            .antMatchers("/resources/**").permitAll()

            //.antMatchers(HttpMethod.GET, "/login/**").permitAll()
            //.antMatchers(HttpMethod.GET, "/location/**").permitAll()

            .anyRequest().authenticated()/*.and()
            .apply(new SpringSocialConfigurer())*/;

        // custom Token based authentication based on the header previously given to the client
        //.addFilterBefore(new StatelessAuthenticationFilter(tokenAuthenticationService), UsernamePasswordAuthenticationFilter.class);
}

My controller looks like this:

@RestController
@RequestMapping(value="/login", produces="application/json")
public class LoginController {


    @Secured( value={"ROLE_ANONYMOUS"})
    @RequestMapping(method=RequestMethod.GET)
    public String get(){
        return "hello";
    }
}

But when I try to press "/ login", I get a 403 rejection error. Please help me, how can I enable anonymous anonymous access.

+4
source share
2 answers

As Faraj Faruk wrote, you must allow access to the URL of your login page. You commented on the corresponding line:

@Override
protected void configure(HttpSecurity http) throws Exception {
     http
        .anonymous()
            .authorities("ROLE_ANONYMOUS")
            .and()
        .headers()
             .cacheControl()
             .and()
        .authorizeRequests()
            .antMatchers("/").permitAll()
            .antMatchers("/profile/image").permitAll()
            .antMatchers("/favicon.ico").permitAll()
            .antMatchers("/resources/**").permitAll()

            .antMatchers(HttpMethod.GET, "/login/**").permitAll()

            .anyRequest().authenticated()
}

permitAll(), hasAuthority("ROLE_ANONYMOUS"). @Secured( value={"ROLE_ANONYMOUS"}).

+2

.

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        ...
        .formLogin().loginPage("/login").permitAll()
        ...

allowAll, roled ( , , ), .

@Secured("ROLE_ANONYMOUS")
@RequestMapping(method=RequestMethod.GET)
public String get(){
    ...
+1

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


All Articles