如何对不同的域使用基于角色的身份验证?

j7dteeu8  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(383)

有一个项目在上运行SpringBoot后端localhost:8080 and 2个前端Angular 应用localhost:4200 (用户网站)和localhost:4201(管理网站)。如何配置Spring Security ,使其仅允许具有以下角色的用户- ROLE_USER , ROLE_ADMIN 在用户网站和用户的角色- ROLE_ADMIN 应该有权访问管理网站。
目前两个用户都可以访问这两个网站。有没有办法限制某些域,而不是限制用户的路径(URL)。
当前配置-

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{

    @Autowired
    Environment env; 

    @Autowired
    UserSecurityService useSecurityService;

    private BCryptPasswordEncoder passwordEncoder() {
        return SecurityUtility.passwordEncoder();
    }

    private static final String[] PUBLIC_MATHCES= {
            "/css/**",
            "/js/**",
            "/images/**",
            "/book/**",
            "/user/**",
            "/media/**"
    };

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(useSecurityService).passwordEncoder(passwordEncoder());

    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers(PUBLIC_MATHCES).permitAll()
            .anyRequest().authenticated()
            .and();
        http.csrf().disable()
            .cors()
            .and()
            .httpBasic();

    }

      @Bean
      public HttpSessionIdResolver httpSessionStrategy() {
          return  HeaderHttpSessionIdResolver.xAuthToken();
      }

}
bq8i3lrv

bq8i3lrv1#

假设您的所有配置都配置正确,那么您可以使用角色限制机制,如下面的示例所示:

@Override
protected void configure(HttpSecurity http) throws Exception {

    http
        .authorizeRequests(authorize - > {
            authorize
            .antMatchers("/h2-console/**").permitAll() //do not use in production!
            .antMatchers("/css/**", "/js/**", "/images/**", "/book/**", "/user/**", "/media/**").permitAll()
            .antMatchers("/website/find", "/main*").permitAll()
            .antMatchers(HttpMethod.GET, "/userweb/v1/data/**").permitAll()
            .mvcMatchers(HttpMethod.DELETE, "/userweb/v1/info/**").hasRole("ADMIN")
            .mvcMatchers(HttpMethod.GET, "/userweb/v1/item/{upc}").permitAll()
            .mvcMatchers("/admin/main").hasAnyRole("USER", "ADMIN")
            .mvcMatchers(HttpMethod.GET, "/user/api/v1/normal")
            .hasAnyRole("USER", "ADMIN", "FOO");
        })
        .authorizeRequests()
        .anyRequest().authenticated()
        .and()
        .cors()
        .and()
        .httpBasic()
        .and().csrf().disable();
}

相关问题