Draaksward
Draaksward

Reputation: 779

Spring Security secure custom pages

Is there a way to configure Spring Security (with Java config) in order to secure custom pages only, or even work upon @PreAuthorized annotation?

The idea is that I want to secure custom calls like /admin and other stuff (without hardcoding every call in the security configuration), which is set up in the controller under the mentioned annotation, but the other stuff shouldn't use authentication at all.

Upvotes: 0

Views: 1031

Answers (2)

Leonardo Beal
Leonardo Beal

Reputation: 734

I had a hard time finding something which would work for me. That does the trick and it's also very readable.

@Override
protected void configure(HttpSecurity http) throws Exception
{
    http.authorizeRequests()
            .antMatchers("/admin/**").access("hasRole('ADMIN')")
            .antMatchers("/**").permitAll()
            .anyRequest().authenticated()
            .and()
            .formLogin();
}

and the full Class for those who are still not on the same page

package com.your.package.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.*;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter
{
    @Override
    protected void configure(HttpSecurity http) throws Exception
    {
        http.authorizeRequests()
                .antMatchers("/admin/**").access("hasRole('ADMIN')")
                .antMatchers("/**").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception
    {
        auth.inMemoryAuthentication().withUser("user").password("password").roles("USER");
    }
}

Note that not calling the formLogin() method would make the default "/login" return a 404 error.

Upvotes: 1

Andrei
Andrei

Reputation: 115

I am not sure if this answers your question, but you could use ant matchers to identify certain pages and ignore others in your security configuration, like so:

.antMatchers("/**").permitAll()

or

.antMatcher("/admin/**")
.authorizeRequests()
.anyRequest().authenticated() 

Upvotes: 0

Related Questions