搜尋
首頁JavaSpring Security 在其餘服務中獲取經過身份驗證和未經過身份驗證的用戶的用戶信息

在開發網頁應用程式時,安全性是一個重要的考慮因素。為了保護使用者資料和防止未經授權的訪問,我們需要使用一種可靠的身份驗證和授權機制。 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。如有侵權,請聯絡admin@php.cn刪除

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
1 個月前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
1 個月前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
1 個月前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.聊天命令以及如何使用它們
1 個月前By尊渡假赌尊渡假赌尊渡假赌

熱工具

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具