首頁 > Java > 主體

Spring Security 在其餘服務中獲取經過身份驗證和未經過身份驗證的用戶的用戶信息

王林
發布: 2024-02-08 23:00:23
轉載
688 人瀏覽過

在開發網頁應用程式時,安全性是一個重要的考慮因素。為了保護使用者資料和防止未經授權的訪問,我們需要使用一種可靠的身份驗證和授權機制。 Spring Security是一個功能強大且廣泛使用的安全框架,它提供了一套完整的解決方案來保護我們的應用程式。在本文中,我們將探討如何在Spring Security中取得經過身份驗證和未經過身份驗證的使用者的使用者資訊。 php小編百草將向您展示如何利用Spring Security的功能,獲取用戶資訊以及在不同服務之間共享用戶資訊的方法。無論您是初學者還是有經驗的開發人員,本文都將為您提供有關Spring Security的詳細信息,並幫助您提升應用程式的安全性。

問題內容

我有一個 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();
        }

    }
}
登入後複製

解決方法

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
登入後複製

匿名存取將會新增額外的篩選器:anonymousauthenticationfilter到填入anonymousauthenticationtoken作為驗證資訊的篩選器鏈,以防securitycontext中沒有authentication物件

我有這個安全配置用於透過/public/authphpcnendcphp檢查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());
}
登入後複製

以上是Spring Security 在其餘服務中獲取經過身份驗證和未經過身份驗證的用戶的用戶信息的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:stackoverflow.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!