簡體   English   中英

如何將 angular 9 登錄頁面連接到 Spring Boot 應用程序?

[英]How to connect angular 9 login page to spring boot app?

我在第一個用戶微服務中成功實現了spring security,下面是配置代碼:

   @EnableWebSecurity
    public class MSSecurityConfiguration extends WebSecurityConfigurerAdapter {
    
        @Autowired
        UserDetailsService userDetailsService;
        
        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            
            auth.userDetailsService(userDetailsService);
        }
        
        @Override
        public void configure(WebSecurity web) throws Exception {
            web.ignoring().antMatchers("/users/UserById/*")                   
                          .antMatchers("/users/Activate/**/");
        }
        
        @Bean
        public PasswordEncoder getPasswordEncoder() {
            return new BCryptPasswordEncoder();
        }

角度服務的完整語法是:

return this.http.get<UserObj>(`http://localhost:9023/users/Authenticate?username=aaa&password=bbb`

用戶詳情服務:

@Service
public class MSUserDetailsService implements UserDetailsService {

    @Autowired
    UserRepository userRepository;
    
    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        
        User user = userRepository.getUser(userName);
        if (user != null) {
            return new MSUserDetails(user);
        }
        throw new UsernameNotFoundException("Not found: " + userName);      
    }

}

這是從 angular 處理服務調用的控制器:

@CrossOrigin(origins = "http://localhost:4200", maxAge = 3600)
@RestController
@RequestMapping("/users")
@Slf4j
public class UserController {
    @GetMapping("/Authenticate")    
        public User authenticatie(@RequestParam("username") String username, @RequestParam("password") String password) {
            return userService.authenticatie(username, password);       
        }

我需要知道如何將此身份驗證連接到 spring 安全性,以便下次用戶發送不同的 url 時,它將已經進行身份驗證?

您設置 url 的方式就像彈簧靴也處理應用程序的前端部分一樣。 可能您從教程中獲得了此代碼,如果沒問題,但不打算用於與不同前端的集成。

即使應用程序在同一台服務器上運行,端口也可能是一個問題,我不確定您是否可以克服。

你在評論中告訴我你有一個 RestController 來登錄,這很好,因為這個想法是朝着正確的解決方案發展的。 此端點必須負責驗證用戶(最終針對數據庫,我看到您目前正在使用靜態值)並返回某種令牌以存儲在您的角度(例如 jwt)中。

想法如下,角度登錄頁面必須調用在 spring-boot 中創建為 @RestController 的登錄端點並返回某種 ot 令牌。 Angular 保存在 cookie 或本地存儲中提供的令牌。 然后 angular 將其用於針對 spring boot 的請求。

然后必須在 websecurity 中配置需要身份驗證的 spring boot 端點才能這樣做。 閱讀如何在 Spring Boot 中創建用於驗證的過濾器並實現一個過濾器。

額外注意,可能您還需要允許 cors 從 angular 到 spring boot。

暫無
暫無

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

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