Maison  >  Article  >  Spring Security obtient des informations sur les utilisateurs authentifiés et non authentifiés dans les services restants

Spring Security obtient des informations sur les utilisateurs authentifiés et non authentifiés dans les services restants

王林
王林avant
2024-02-08 23:00:23691parcourir

La sécurité est une considération importante lors du développement d'applications Web. Pour protéger les données des utilisateurs et empêcher tout accès non autorisé, nous devons utiliser un mécanisme d'authentification et d'autorisation fiable. Spring Security est un framework de sécurité puissant et largement utilisé qui fournit un ensemble complet de solutions pour protéger nos applications. Dans cet article, nous explorerons comment obtenir des informations utilisateur pour les utilisateurs authentifiés et non authentifiés dans Spring Security. L'éditeur PHP Baicao vous montrera comment utiliser les fonctions de Spring Security pour obtenir des informations utilisateur et partager des informations utilisateur entre différents services. Que vous soyez débutant ou développeur expérimenté, cet article vous fournira des informations détaillées sur Spring Security et vous aidera à améliorer la sécurité de votre application.

Contenu de la question

J'ai un service Spring Rest et je souhaite l'utiliser à la fois pour les utilisateurs authentifiés et non authentifiés. Si l'utilisateur est authentifié, je souhaite obtenir les informations utilisateur de securitycontextholder.getcontext().getauthentication().

  • Si j'utilise .antmatchers("/app/rest/question/useroperation/list/**").permitall() Dans la configuration ouath2 comme indiqué ci-dessous, je peux alors obtenir les informations utilisateur Les utilisateurs authentifiés, mais les utilisateurs non authentifiés, obtiennent une erreur 401.
  • Si je .antmatchers("/app/rest/question/useroperation/list/**").permitall() et ignorer l'URL dans Websecurity web.ignoring()..antmatchers("/app/rest/question/useroperation/list/**") Dans securityconfiguration comme ci-dessous, tous les utilisateurs peuvent appeler service mais je ne parviens pas à obtenir les informations utilisateur à partir du contexte de sécurité.

Comment configurer ma sécurité Spring pour appeler l'URL des utilisateurs authentifiés et non authentifiés et obtenir les informations utilisateur du contexte de sécurité lorsque l'utilisateur se connecte.

@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 de sécurité

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

    }
}

Solution

permitall() 仍然需要 authentication 对象出现在 securitycontext dans.

Pour les utilisateurs non-oauth, cela peut être réalisé en activant l'accès anonyme :

@override
public void configure(httpsecurity http) throws exception {
   http
//some configuration
     .and()
        .anonymous() //allow anonymous access
     .and()
        .authorizerequests()
           .antmatchers("/views/**").permitall()
//other security settings

L'accès anonyme ajoutera un filtre supplémentaire : anonymousauthenticationfilter到填充anonymousauthenticationtoken作为身份验证信息的过滤器链,以防securitycontext中没有authentication objet

J'ai cette configuration de sécurité pour vérifier l'utilisateur via /public/authphpcnendcphp Chinois :

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

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Cet article est reproduit dans:. en cas de violation, veuillez contacter admin@php.cn Supprimer