提问者:小点点

Spring Security在Rest服务中获取用户信息,适用于经过身份验证和未经身份验证的用户


我有一个Spring rest服务,我想将它用于经过身份验证和未经身份验证的用户。如果用户经过身份验证,我想从SecurityContextHolder.getContext(). getAuthentiation()获取用户信息。

  • 如果我在如下所示的ouath2配置中使用. antMatcher("/app/rest/ask/useraction/list/**"). permitAll(),那么我可以获得经过身份验证的用户的用户信息,但未经过身份验证的用户会出现401错误。
  • 如果我. antMatcher("/app/rest/问题/用户操作/list/**"). permitAll()并通过web.ignoring()忽略WebSecurity中的url... antMatcher("/app/rest/问题/用户操作/list/**")SecurityConfiguration中,如下所示,则所有用户都可以调用该服务,但我无法从SecurityContext获取用户信息。

如何配置我的Spring Security为经过身份验证和非经过身份验证的用户调用url,并在用户登录时从SecurityContext获取用户信息。

@Configuration
@EnableResourceServer
protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

    @Inject
    private Http401UnauthorizedEntryPoint authenticationEntryPoint;

    @Inject
    private AjaxLogoutSuccessHandler ajaxLogoutSuccessHandler;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .exceptionHandling()
                .authenticationEntryPoint(authenticationEntryPoint)
                .and()
                .logout()
                .logoutUrl("/app/logout")
                .logoutSuccessHandler(ajaxLogoutSuccessHandler)
                .and()
                .csrf()
                .requireCsrfProtectionMatcher(new AntPathRequestMatcher("/oauth/authorize"))
                .disable()
                .headers()
                .frameOptions().disable()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers("/views/**").permitAll()
                .antMatchers("/app/rest/authenticate").permitAll()
                .antMatchers("/app/rest/register").permitAll()
                .antMatchers("/app/rest/question/useroperation/list/**").permitAll()
                .antMatchers("/app/rest/question/useroperation/comment/**").authenticated()
                .antMatchers("/app/rest/question/useroperation/answer/**").authenticated()
                .antMatchers("/app/rest/question/definition/**").hasAnyAuthority(AuthoritiesConstants.ADMIN)
                .antMatchers("/app/rest/logs/**").hasAnyAuthority(AuthoritiesConstants.ADMIN)
                .antMatchers("/app/**").authenticated()
                .antMatchers("/websocket/tracker").hasAuthority(AuthoritiesConstants.ADMIN)
                .antMatchers("/websocket/**").permitAll()
                .antMatchers("/metrics/**").hasAuthority(AuthoritiesConstants.ADMIN)
                .antMatchers("/health/**").hasAuthority(AuthoritiesConstants.ADMIN)
                .antMatchers("/trace/**").hasAuthority(AuthoritiesConstants.ADMIN)
                .antMatchers("/dump/**").hasAuthority(AuthoritiesConstants.ADMIN)
                .antMatchers("/shutdown/**").hasAuthority(AuthoritiesConstants.ADMIN)
                .antMatchers("/beans/**").hasAuthority(AuthoritiesConstants.ADMIN)
                .antMatchers("/info/**").hasAuthority(AuthoritiesConstants.ADMIN)
                .antMatchers("/autoconfig/**").hasAuthority(AuthoritiesConstants.ADMIN)
                .antMatchers("/env/**").hasAuthority(AuthoritiesConstants.ADMIN)
                .antMatchers("/trace/**").hasAuthority(AuthoritiesConstants.ADMIN)
                .antMatchers("/api-docs/**").hasAuthority(AuthoritiesConstants.ADMIN)
                .antMatchers("/protected/**").authenticated();

    }

}

证券配置

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {


    @Inject
    private UserDetailsService userDetailsService;


    @Bean
    public PasswordEncoder passwordEncoder() {
        return new StandardPasswordEncoder();
    }

    @Inject
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .userDetailsService(userDetailsService)
                .passwordEncoder(passwordEncoder());
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring()
            .antMatchers("/bower_components/**")
            .antMatchers("/fonts/**")
            .antMatchers("/images/**")
            .antMatchers("/scripts/**")
            .antMatchers("/styles/**")
            .antMatchers("/views/**")
            .antMatchers("/i18n/**")
            .antMatchers("/swagger-ui/**")
            .antMatchers("/app/rest/register")
            .antMatchers("/app/rest/activate")
            .antMatchers("/app/rest/question/useroperation/list/**")
            .antMatchers("/console/**");
    }


    @EnableGlobalMethodSecurity(prePostEnabled = true, jsr250Enabled = true)
    private static class GlobalSecurityConfiguration extends GlobalMethodSecurityConfiguration {
        @Override
        protected MethodSecurityExpressionHandler createExpressionHandler() {
            return new OAuth2MethodSecurityExpressionHandler();
        }

    }
}

共2个答案

匿名用户

permitAll()仍然需要身份验证,对象才能出现在安全上下文中。

对于非 oauth 用户,这可以通过启用匿名访问来实现:

@Override
public void configure(HttpSecurity http) throws Exception {
   http
//some configuration
     .and()
        .anonymous() //allow anonymous access
     .and()
        .authorizeRequests()
           .antMatchers("/views/**").permitAll()
//other security settings

匿名访问将添加其他过滤器:匿名身份验证过滤器到填充匿名身份验证的过滤器链中,以防SecurityContext中没有身份验证对象

匿名用户

我有这个安全配置,用于检查/public/authUser

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.cors().and().authorizeRequests()
           .antMatchers("/api/skills/**", "/api/profile/**", "/api/info/**").authenticated()
           .antMatchers("/api/**").hasAuthority(Role.ROLE_ADMIN.getAuthority())
           .antMatchers("/public/auth").permitAll()
           .and().httpBasic()
           .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
           .and().csrf().disable();
}

@GetMapping(value = "/public/auth")
private ResponseEntity<User> getAuthUser(@AuthenticationPrincipal AuthUser authUser) {
    return authUser == null ? 
               ResponseEntity.notFound().build() :
               ResponseEntity.ok(authUser.getUser());
}