【问题标题】:Spring Security get user info in rest service, for authenticated and not authenticated usersSpring Security 在休息服务中获取用户信息,用于经过身份验证和未经过身份验证的用户
【发布时间】:2014-10-03 13:09:59
【问题描述】:

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

  • 如果我使用 .antMatchers("/app/rest/question/useroperation/list/**").permitAll() 在 ouath2 配置中,如下所示,然后我可以获得用户信息 经过身份验证的用户,但未经过身份验证的用户出现 401 错误。
  • 如果我 .antMatchers("/app/rest/question/useroperation/list/**").permitAll() 并忽略 WebSecurity 中的 url web.ignoring()..antMatchers("/app/rest/question/useroperation/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();
        }

    }
}

【问题讨论】:

    标签: java spring authentication spring-security jhipster


    【解决方案1】:

    permitAll() 仍然需要 Authentication 对象才能出现在 SecurityContext 中。

    对于非 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 中没有Authentication 对象的情况下将额外的过滤器:AnonymousAuthenticationFilter 添加到将AnonymousAuthenticationToken 作为身份验证信息填充的过滤器链中

    【讨论】:

      【解决方案2】:

      我有这个安全配置,用于通过/public/auth检查 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());
      }
      

      【讨论】:

        猜你喜欢
        • 2014-01-12
        • 1970-01-01
        • 2016-11-30
        • 1970-01-01
        • 1970-01-01
        • 2020-11-15
        • 2016-01-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多