viq
viq

Reputation: 417

Spring secure both web app and rest app

I read a lot of manual of how to configure spring security, but still stuck with configuration. So i want to configure rest calls and other http calls. As i understand i can create urls like /server/** - for web application and /rest/** - for rest application. For any call of web application urls i want to create a login page (when user not authenticated), but for rest app, i want to fire Unauthorised code.

I do it with spring annotations by extend WebSecurityConfigurerAdapter

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable().authorizeRequests()
            .antMatchers("/").access("hasRole('ROLE_USER')")
            .antMatchers("/server/*").access("hasRole('ROLE_USER')")
            .and()
            .formLogin().loginPage("/login").permitAll().failureUrl("/login?error")
            .usernameParameter("username")
            .passwordParameter("password")
            .and()
            .exceptionHandling()
            .accessDeniedPage("/accessDenied");
}

for server it works fine, but if i try to add /rest here when i try to call /rest/[something] (in browser), it always forwards me to /login page. I don't understand why and it is break my mind. Thanks for any helpful responses.

Upvotes: 1

Views: 961

Answers (2)

Gokhan Oner
Gokhan Oner

Reputation: 3257

You have this:

.antMatchers("/").access("hasRole('ROLE_USER')")
            .antMatchers("/server/*").access("hasRole('ROLE_USER')")
            .and()
            .formLogin()

means / access need ROLE_ACCESS and for authentication, direct to formLogin

You need multiple authentication conf.

see http://docs.spring.io/autorepo/docs/spring-security/4.0.0.CI-SNAPSHOT/reference/htmlsingle/

And in one of them you need something like this

http
        .antMatcher("/rest/**")
        .exceptionHandling().authenticationEntryPoint(new AccessDenyEntryPoint()).and()                
        .authorizeRequests().antMatchers("/spring/**").denyAll();

Upvotes: 2

Aninda Bhattacharyya
Aninda Bhattacharyya

Reputation: 1251

You have to add one more .antMatchers("/rest/*").permitAll() if you don't want to validate your rest urls.

Upvotes: 0

Related Questions