Spring 安全 Java 配置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22591028/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 16:43:03  来源:igfitidea点击:

Spring Security Java configuration

javaspringspring-mvcspring-security

提问by Dmytro Titov

I have working XML-based security configuration in my Spring MVC project:

我的 Spring MVC 项目中有基于 XML 的安全配置:

<security:http use-expressions="true"
               authentication-manager-ref="authenticationManager">
    <security:intercept-url pattern="/" access="permitAll"/>
    <security:intercept-url pattern="/dashboard/home/**" access="hasAnyRole('ROLE_USER, ROLE_ADMIN')"/>
    <security:intercept-url pattern="/dashboard/users/**" access="hasRole('ROLE_ADMIN')"/>
    <security:intercept-url pattern="/rest/users/**" access="hasRole('ROLE_ADMIN')"/>
    <security:form-login login-page="/"/>
</security:http>

And I have question: is it possible to fully replace it by Java configuration? What annotations and where should I use for "use-expressions", "intercept-url", etc.?

我有一个问题:是否可以用 Java 配置完全替换它?对于“use-expressions”、“intercept-url”等,我应该使用哪些注释以及在哪里使用?

采纳答案by Jean-Philippe Bond

Yes, if you are using Spring security 3.2and above, it will be something like this :

是的,如果您使用Spring security 3.2及以上,它将是这样的:

@Configuration
@EnableWebSecurity
public class MyWebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/resources/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/dashboard/home/**").hasAnyRole("USER", "ADMIN")
                .antMatchers("/dashboard/users/**").hasRole("ADMIN")
                .antMatchers("/rest/users/**").hasRole("ADMIN")
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/")
                .permitAll();
    }

    // Possibly more overridden methods ...
}