【问题标题】:Spring secure both web app and rest appSpring 保护 web 应用程序和 rest 应用程序
【发布时间】:2015-05-12 12:00:02
【问题描述】:

我阅读了很多关于如何配置 Spring Security 的手册,但仍然坚持配置。 所以我想配置休息调用和其他http调用。据我了解,我可以创建 /server/** 之类的网址 - 用于 Web 应用程序和 /rest/** - 用于休息应用程序。对于 Web 应用程序 URL 的任何调用,我想创建一个登录页面(当用户未通过身份验证时),但对于其他应用程序,我想触发未经授权的代码。

我通过扩展 WebSecurityConfigurerAdapter 使用 spring 注释来做到这一点

@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");
}

对于服务器它工作正常,但如果我尝试在此处添加 /rest 当我尝试调用 /rest/[something](在浏览器中)时,它总是将我转发到 /login 页面。 我不明白为什么,这让我心烦意乱。 感谢您提供任何有用的回复。

【问题讨论】:

    标签: java spring rest spring-mvc spring-security


    【解决方案1】:

    你有这个:

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

    表示/访问需要ROLE_ACCESS和身份验证,直接到formLogin

    您需要多个身份验证配置。

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

    其中一个你需要这样的东西

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

    【讨论】:

      【解决方案2】:

      如果您不想验证其余网址,则必须再添加一个 .antMatchers("/rest/*").permitAll()

      【讨论】:

        猜你喜欢
        • 2014-10-19
        • 2017-08-09
        • 2010-12-15
        • 1970-01-01
        • 1970-01-01
        • 2018-11-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多