Home >Java >Spring Security gets user information for authenticated and unauthenticated users in remaining services

Spring Security gets user information for authenticated and unauthenticated users in remaining services

王林
王林forward
2024-02-08 23:00:23762browse

Security is an important consideration when developing web applications. To protect user data and prevent unauthorized access, we need to use a reliable authentication and authorization mechanism. Spring Security is a powerful and widely used security framework that provides a complete set of solutions to protect our applications. In this article, we will explore how to get user information for authenticated and unauthenticated users in Spring Security. PHP editor Baicao will show you how to use the functions of Spring Security to obtain user information and share user information between different services. Whether you are a beginner or an experienced developer, this article will provide you with detailed information about Spring Security and help you improve the security of your application.

Question content

I have a spring rest service and I want to use it for both authenticated and unauthenticated users. If the user is authenticated, I want to get the user information from securitycontextholder.getcontext().getauthentication().

  • If I use .antmatchers("/app/rest/question/useroperation/list/**").permitall() In the ouath2 configuration as shown below, then I can get the user information Authenticated users, but unauthenticated users get a 401 error.
  • If I .antmatchers("/app/rest/question/useroperation/list/**").permitall() and ignore url in websecurity web.ignoring()..antmatchers("/app/rest/question/useroperation/list/**") In securityconfiguration as shown below, then all users can call service, but I can't get the user information from the securitycontext.

How do I configure my spring security to call urls for authenticated and unauthenticated users and get the user information from the securitycontext when the user logs in.

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

    }

}

Security Configuration

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

    }
}

Workaround

permitall() Still requires the authentication object to be present in the securitycontext.

For non-oauth users, this can be achieved by enabling anonymous access:

@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 an additional filter: anonymousauthenticationfilter to the filter chain that populates anonymousauthenticationtoken as authentication information, in case there is no ## in securitycontext #authenticationObject

I have this security configuration for checking authuser via

/public/authphpcnendcphp Chinese: <pre class="brush:php;toolbar:false;">@Override protected void configure(HttpSecurity http) throws Exception { http.cors().and().authorizeRequests() .antMatchers(&quot;/api/skills/**&quot;, &quot;/api/profile/**&quot;, &quot;/api/info/**&quot;).authenticated() .antMatchers(&quot;/api/**&quot;).hasAuthority(Role.ROLE_ADMIN.getAuthority()) .antMatchers(&quot;/public/auth&quot;).permitAll() .and().httpBasic() .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and().csrf().disable(); } @GetMapping(value = &quot;/public/auth&quot;) private ResponseEntity&lt;User&gt; getAuthUser(@AuthenticationPrincipal AuthUser authUser) { return authUser == null ? ResponseEntity.notFound().build() : ResponseEntity.ok(authUser.getUser()); }</pre>

The above is the detailed content of Spring Security gets user information for authenticated and unauthenticated users in remaining services. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete