访问安全URL时,不会调用Spring Security的身份验证过滤器

时间:2016-11-04 09:27:56

标签: java spring spring-security

用户无需提示登录即可访问受保护的URL。 下面是这样一个URL的示例,应该提示用户登录但无需身份验证即可访问该用户。

http://localhost:9090/HospitalProject/web/patient/home

安全配置:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    Environment env;

    @Autowired
    public void configureAuthentication(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
                .withUser("root")
                .password("root")
                .roles("ADMIN");
        auth
            .inMemoryAuthentication()
                .withUser("notroot")
                .password("notroot")
                .roles("SUPER_ADMIN");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
      http
          .csrf().disable()
          .authorizeRequests()
              .antMatchers("/web/login").permitAll()
              .antMatchers("/web/**").access("hasRole('ADMIN') or hasRole('SUPER_ADMIN')")
              .and()
          .formLogin()
              .loginPage("/web/login")
              .loginProcessingUrl("/web/login")
              .usernameParameter("username")
              .passwordParameter("password")
              .and()
          .logout().logoutSuccessUrl("/login?logout");
    }
}

安全初始化程序:

public class SecurityWebApplicationIntializer extends AbstractSecurityWebApplicationInitializer {

    public SecurityWebApplicationIntializer() {
        super(SecurityConfig.class);
    }
}

控制器:

@Controller
public class MasterController {

    @GetMapping(value={"/", "/web/login"})
    public ModelAndView loginForm(){
        ModelAndView mv = new ModelAndView("login");
        mv.addObject("loginForm", new LoginForm());
        return mv;
    }
}

有什么想法?

1 个答案:

答案 0 :(得分:1)

管理员对不同网址的单独角色权限

试,

authorizeRequests()    
    .antMatchers("/web/admin/**").access("hasRole('ADMIN') or hasRole('SUPER_ADMIN')")
    .anyRequest().authenticated()    
    .and()
    .formLogin().loginPage("/web/login").permitAll(); 
    .loginProcessingUrl("/web/login")
    .usernameParameter("username").passwordParameter("password")
    .and()
    .logout().logoutSuccessUrl("/login?logout")
    .and()
    .csrf().disable();

如果您使用spring mvc,则需要将SecurityConfig添加到xxxServletInitializer而不是AbstractSecurityWebApplicationInitializer

public class SpringMvcInitializer
       extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[] { SecurityConfig.class };
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return null;
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }

}