简体   繁体   中英

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.

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.

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() 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM