久久久久久久av_日韩在线中文_看一级毛片视频_日本精品二区_成人深夜福利视频_武道仙尊动漫在线观看

多個WebSecurityConfigurerAdapters:spring security中的JWT認

Multiple WebSecurityConfigurerAdapters: JWT authentication and form login in spring security(多個WebSecurityConfigurerAdapters:spring security中的JWT認證和表單登錄)
本文介紹了多個WebSecurityConfigurerAdapters:spring security中的JWT認證和表單登錄的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!

問題描述

我有帶有 thymeleaf 的 spring boot 應用程序.我正在使用 spring security formLogin 方法來保證安全,現在我只需要為一些 API 添加 JWT.

I have spring boot app with thymeleaf. I am using spring security formLogin method for security and now I need to add JWT for only some APIs.


@EnableWebSecurity
public class SecurityConfigurations {
    @Autowired
    UserDetailsServiceImpl userDetails;

    @Bean
    DaoAuthenticationProvider provider() {
        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
        provider.setPasswordEncoder(encoder());
        provider.setUserDetailsService(userDetails);
        return provider;
    }

    @Bean
    PasswordEncoder encoder() {
        return new BCryptPasswordEncoder();
    }

    @Configuration
    @Order(1)

    public class JWTSecurityConfig extends WebSecurityConfigurerAdapter {

        @Autowired
        private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;

        @Autowired
        private JwtRequestFilter jwtRequestFilter;

        @Autowired
        DaoAuthenticationProvider provider;

        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.authenticationProvider(provider);
        }

        @Bean
        @Override
        public AuthenticationManager authenticationManagerBean() throws Exception {
            return super.authenticationManagerBean();
        }

        @Override
        protected void configure(HttpSecurity httpSecurity) throws Exception {

            httpSecurity.csrf().disable()

                    .authorizeRequests().antMatchers("/api/user/authenticate").permitAll()

                    .antMatchers("/api/user/**").hasRole("USER")
                    .and().
                    exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).and().sessionManagement()
                    .sessionCreationPolicy(SessionCreationPolicy.STATELESS);

            // Add a filter to validate the tokens with every request
            httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
        }
    }

    @Configuration
    public static class FormLoginConfigurationAdapter extends WebSecurityConfigurerAdapter {
        @Autowired
        DaoAuthenticationProvider provider;

        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.authenticationProvider(provider);
        }

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests().antMatchers("/admin/admins**").hasAnyRole("SADMIN").antMatchers("/admin/**")
                    .hasAnyRole("ADMIN", "SADMIN", "WADMIN").antMatchers("/rest/**")
                    .hasAnyRole("ADMIN", "SADMIN", "WADMIN", "USER").antMatchers("/user/**").hasAnyRole("USER")
                    .anyRequest().permitAll().and().formLogin().loginPage("/sign-in-up")
                    .loginProcessingUrl("/signInProcess").usernameParameter("phone").and().logout()
                    .logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/")
                    .invalidateHttpSession(false).and().csrf().disable().cors();

        }
    }

}

通過執行此操作,JWT 可以正常工作,但 formlogin 已停止并調用/signInProcess".現在給404:

by doing this JWT is working fine as just I need but the formlogin has stopped and calling "/signInProcess" now give 404:

注意:如果我更改順序并設置 formLogin @order(1) 它會再次工作,但當然不會工作.

NOTE: if I change the order and make formLogin @order(1) it works again but of course will not work.

我也嘗試像這樣將它們結合起來,現在它們都可以正常工作,但是如果 JWT 身份驗證錯誤將返回 formlogin thymeleaf 錯誤頁面,則會出現異常處理問題:

Also I tried to combine them both like this now it is both works fine but the problem with exception handling if the JWT authentication error will return formlogin thymeleaf error page :

@Override
        protected void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests().antMatchers("/admin/admins**").hasAnyRole("SADMIN").antMatchers("/admin/**")
                    .hasAnyRole("ADMIN", "SADMIN", "WADMIN").antMatchers("/rest/**")
                    .hasAnyRole("ADMIN", "SADMIN", "WADMIN", "USER").antMatchers("/user/**").hasAnyRole("USER")
                    .antMatchers("/api/user/authenticate").permitAll()
                    .antMatchers("/api/user/**").hasRole("USER")
                    .anyRequest().permitAll().and().formLogin().loginPage("/sign-in-up")
                    .loginProcessingUrl("/signInProcess").usernameParameter("phone").and().logout()
                    .logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/")
                    .invalidateHttpSession(false).and().csrf().disable().cors();
            
            http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);

        }

任何建議使這項工作.謝謝.

any suggestions to make this work. thank you.

推薦答案

您的 WebSecurityConfigurerAdapters 將按順序處理傳入的請求.
由于 JWTSecurityConfig 帶有 @Order(1) 注釋,它會首先處理請求.

Your WebSecurityConfigurerAdapters will process the incoming requests in order.
Since JWTSecurityConfig is annotated with @Order(1) it will process the requests first.

你沒有為這個Adapter指定一個antMatcher,所以它會匹配所有的請求.
這意味著請求永遠不會到達 FormLoginConfigurationAdapter,因為 JWTSecurityConfig 匹配所有這些.

You have not specified a antMatcher for this Adapter, so it will match all requests.
This means that a request will never reach FormLoginConfigurationAdapter, since JWTSecurityConfig matches them all.

如果您希望 JWTSecurityConfig 僅適用于某些請求,您可以在安全配置中指定 antMatcher.
下面是一個例子:

If you want JWTSecurityConfig to only apply to certain requests, you can specify an antMatcher in your security configuration.
Below is an example:

@EnableWebSecurity
public class SecurityConfigurations {

    @Configuration
    @Order(1)
    public class JWTSecurityConfig extends WebSecurityConfigurerAdapter {

        @Override
        protected void configure(HttpSecurity http) throws Exception {
           http
              .requestMatchers(matchers -> matchers
                  .antMatchers("/api/**") // apply JWTSecurityConfig to requests matching "/api/**"
              )
              .authorizeRequests(authz -> authz
                  .anyRequest().authenticated()
              )
              .addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
        }
    }

    @Configuration
    public class FormLoginConfigurationAdapter extends WebSecurityConfigurerAdapter {

        @Override
        protected void configure(HttpSecurity http) throws Exception {
           http
              .authorizeRequests(authz -> authz
                  .anyRequest().authenticated()
              )
              .formLogin();
        }
    }
}

關于多個WebSecurityConfigurerAdapter的更多細節,可以查看multiple HttpSecurity 部分.

For more details on multiple WebSecurityConfigurerAdapter, you can see the multiple HttpSecurity section in the Spring Security reference docs.

authorizeRequests()requestMatchers() 的更多區別可以看這個 Stack Overflow 問題.

For more details on the difference between authorizeRequests() and requestMatchers(), you can see this Stack Overflow question.

這篇關于多個WebSecurityConfigurerAdapters:spring security中的JWT認證和表單登錄的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!

【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!

相關文檔推薦

How to wrap text around components in a JTextPane?(如何在 JTextPane 中的組件周圍環繞文本?)
MyBatis, how to get the auto generated key of an insert? [MySql](MyBatis,如何獲取插入的自動生成密鑰?[MySql])
Inserting to Oracle Nested Table in Java(在 Java 中插入 Oracle 嵌套表)
Java: How to insert CLOB into oracle database(Java:如何將 CLOB 插入 oracle 數據庫)
Why does Spring-data-jdbc not save my Car object?(為什么 Spring-data-jdbc 不保存我的 Car 對象?)
Use threading to process file chunk by chunk(使用線程逐塊處理文件)
主站蜘蛛池模板: 亚洲综合视频 | 在线观看成年人视频 | 国产精品明星裸体写真集 | 一区二区小视频 | 久久免费精品 | 99在线免费视频 | 免费高清av | 国产综合网址 | 中文字幕在线视频一区二区三区 | 亚洲精选久久 | 国产ts人妖系列高潮 | av不卡一区 | 日韩毛片免费视频 | 亚洲国产精品第一区二区 | 欧美一区二区在线看 | 国产偷自视频区视频 | 欧美最猛黑人xxxx黑人 | 久久aⅴ乱码一区二区三区 91综合网 | 欧美福利视频一区 | 久久亚洲欧美日韩精品专区 | 国产一在线观看 | 国产精品成人久久久久 | 欧美亚洲另类丝袜综合网动图 | 国产精品久久久久久久免费大片 | 日韩高清成人 | 秋霞a级毛片在线看 | 在线观看中文字幕 | 午夜视频在线免费观看 | 成人亚洲 | 中文字幕av在线播放 | 国产日韩欧美一区二区 | 国产在线播 | 亚洲一区日韩 | 亚洲日本国产 | 久久国产激情视频 | 国产精品综合久久 | 国产精品一区二区在线免费观看 | 日韩中文字幕网 | 久久久国产一区二区三区四区小说 | 久久午夜视频 | 中文字幕91 |