【问题标题】:Enable Spring security by specific route通过特定路由启用 Spring 安全性
【发布时间】:2018-08-15 04:33:20
【问题描述】:

我如何为某些路由启用 Spring 安全性。例如: 我有一个网站,内容是从不同的路线开始的 '/**'。在这条路线中,我需要禁用弹簧安全性。 但我有另一个网络模块 /admin-panel/** 我必须启用 spring 安全性。

所以,我的安全配置

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/*").permitAll()
                .antMatchers("/admin-panel").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
            .logout()
                .permitAll();
    }

【问题讨论】:

  • permitAll() 禁用身份验证,.antMatchers("/admin-panel").hasRole('ADMIN') 应该可以工作,它将检查用户是否具有 ADMIN 角色。

标签: java spring-mvc spring-security


【解决方案1】:

试试这个:

http.
    .anonymous()
    .and()
    .authorizeRequests()
    .antMatchers("/admin-panel/**").authenticated()
    .anyRequest().permitAll()

匿名访问将添加额外的过滤器:AnonymousAuthenticationFilter 到过滤器链中,在 SecurityContext 中没有 Authentication 对象的情况下将 AnonymousAuthenticationToken 作为身份验证信息填充。

参考,Spring Security get user info in rest service, for authenticated and not authenticated users

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-05
    • 1970-01-01
    • 1970-01-01
    • 2018-01-16
    • 2014-01-04
    • 1970-01-01
    • 2020-02-09
    • 2021-12-22
    相关资源
    最近更新 更多