簡體   English   中英

Spring 安全 2 種登錄方式

[英]Spring Security 2 types of login

我正在嘗試讓用戶登錄和管理員登錄。 目前只有管理員登錄有效,另一個只是輸出錯誤。 我不太確定它為什么不工作,如果有人能理解為什么不工作,你能告訴我。 這是我的安全配置。

@EnableWebSecurity
public class AdminSecurityConfig extends WebSecurityConfigurerAdapter {
 @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
        .withUser("admin").password("12345").roles("ADMIN")
        .and()
        .withUser("tester").password("56789").roles("ADMIN");
        
    }
    @Override
 protected void configure(HttpSecurity http) throws Exception {
         http.authorizeRequests()
            .antMatchers("/").permitAll()
            .antMatchers("/login")
            .permitAll()
                .antMatchers("/newUser")
                .permitAll()
                .antMatchers("/admin")
                .hasAnyRole("ADMIN")
            .and()
            .formLogin()
            .loginPage("/login1")
            .defaultSuccessUrl("/admin")
            .failureUrl("/login?error=true")
            .permitAll()
                .and()
                .formLogin()
                .loginPage("/login")
                .loginProcessingUrl("/login2")
                .defaultSuccessUrl("/success")
                .failureUrl("/login?error==true")
                .permitAll()
                    .and()
                .logout()
                .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                .logoutSuccessUrl("/")
                .deleteCookies("JSESSIONID")
                .invalidateHttpSession(true) 
            .and()
                .csrf()
                .disable()

            ;
  }
         
    @Bean
    public UserDetailsService userDetailsService() {
        return new CustomUserDetailsService();
    }
    @Autowired
    public void configurationGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService()).passwordEncoder(passwordEncoder());
    }
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

這是用戶的登錄頁面 - 無法正常工作的頁面。

<body id="body">
<div id="container">
<h1>Authorised Users Only</h1>
<div id="box">
<form:form name='user' action="/login2" method='POST'>

             <form:errors path="username" />
    
      <label for="username">Email address</label>
            <input type='text' class="form-control" name='username' value='' placeholder="Enter Email address"></td>
            <label for="password">Password: </label>
            <input type='password' class="form-control" name='password' /></td>
       
        
<input name="submit" class="btn btn-primary" type="submit" value="submit" /></td>
        

</form:form>

所以當我輸入用戶名=“測試”和密碼=“123”這是正確的值時,它會輸出“錯誤==真”。 任何人都可以提供有關我可以做些什么來解決這個問題的見解。

這是“/succsess”的requestMapping

    @RequestMapping(value = "/success", method = RequestMethod.GET)
    public String successLogin() {
        return "redirect:/home";
    }
@RequestMapping("/home")
public String homepage( Model model) {
    model.addAttribute("vols", volrepo.findAll());
    return "Homepage";
}

列出兩個.formLogin聲明並不符合您的想法。 相反,您需要兩個單獨的安全配置。

如果您使用的是 Spring Security 5.4,您可以執行以下操作:

@Bean
@Order(1)
SecurityFilterChain adminFilters(HttpSecurity http) throws Exception {
    http
        .requestMatchers((matchers) -> matchers.mvcMatchers("/admin/**"))
        .authorizeRequests((requests) -> requests.anyRequest().hasRole("ADMIN"))
        .formLogin((form) -> form
            .defaultSuccessUrl("/admin/home")
            .loginPage("/admin/login").permitAll()
        );

    return http.build();
}

@Bean
@Order(2)
SecurityFilterChain userFilters(HttpSecurity http) throws Exception {
    http
        .authorizeRequests((requests) -> requests.anyRequest().authenticated())
        .formLogin(Customizers.withDefaults());

    return http.build();
}

@Bean
UserDetailsService userDetailsService() { ... }

@Bean
PasswordEncoder passwordEncoder() { ... }

或者,如果您使用的是早期版本,則可以發布兩個WebSecurityConfigurerAdapter

@Configuration
public class SecurityConfig {
    @Component
    @Order(1)
    static class AdminConfig extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                .requestMatchers((matchers) -> matchers.mvcMatchers("/admin/**"))
                .authorizeRequests((r) -> r.anyRequest().hasRole("ADMIN"))
                .formLogin((form) -> form
                    .defaultSuccessUrl("/admin/home")
                    .loginPage("/admin/login").permitAll()
                );

            return http.build();       
        }
    }

    @Component
    @Order(2)
    static class UserConfig extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                .authorizeRequests((r) -> r.anyRequest().authenticated())
                .formLogin(Customizer.withDefaults());

            return http.build();       
        }
    }

    @Bean
    UserDetailsService userDetailsService() { ... }

    @Bean
    PasswordEncoder passwordEncoder() { ... }
}

無論哪種方式,都會為任何具有/admin/**模式的 URL 調用第一個過濾器鏈。 如果您選擇將所有管理頁面放在同一路徑中,那么您就可以只有一個匹配器。

將為任何其他 URL 調用第二個過濾器鏈。

UserDetailsServicePasswordEncoder將由兩個過濾器鏈共享。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM