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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25230861/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 07:38:29  来源:igfitidea点击:

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

javaspringauthenticationspring-securityjhipster

提问by fyelci

I have a spring rest service, I want to use it for authenticated and not authenticated users. And I want to get user information from SecurityContextHolder.getContext().getAuthentication()if user is authenticated.

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

  • If I use .antMatchers("/app/rest/question/useroperation/list/**").permitAll()in ouath2 configuration like below, then I can get user info for authenticated user, but 401 error for not authenticated users.
  • If I .antMatchers("/app/rest/question/useroperation/list/**").permitAll()and ignore the url in WebSecurity by web.ignoring()..antMatchers("/app/rest/question/useroperation/list/**")in SecurityConfigurationlike below, then all users can call the service, but I cant get user information from SecurityContext.
  • 如果我 .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中获取用户信息。

How can configure my spring security to call a url for authenticated and not authenticated users and get user info from SecurityContext if user logged in.

如果用户登录,如何配置我的 spring 安全来为经过身份验证和未经过身份验证的用户调用 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();

    }

}

SecurityConfiguration

安全配置

@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();
        }

    }
}

回答by zeldigas

permitAll()still requires Authenticationobject to present in SecurityContext.

permitAll()仍然需要Authentication对象出现在SecurityContext.

For not oauth users this can be achieved with anonymous access enabled:

对于非 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

Anonymous access will add additional filter: AnonymousAuthenticationFilterto the filter chain that populate AnonymousAuthenticationTokenas Authentication information in case no Authenticationobject in SecurityContext

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

回答by Grigory Kislin

I've this security config for check AuthUser by /public/auth:

我有这个安全配置来检查 AuthUser /public/auth

@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());
}