簡體   English   中英

如何在Spring Boot中實現基本身份驗證?

[英]How to implement basic authentication in Spring boot?

我已經按照這個這個教程創建一個基於Java的后端的Angular.JS應用程序的骨架。 它的代碼可以在這里找到。

它具有身份驗證-在啟動時,Spring Boot會向控制台寫入一個隨機密碼,您可以使用該密碼登錄到啟動的應用程序。 用戶名是user ,並且密碼會在開始時顯示在控制台中:

控制台輸出

現在,我想擁有幾個帶有固定密碼的用戶帳戶(如果它們是硬編碼的,也可以)。

如何在不破壞與AngularJS的兼容性的情況下在該應用程序中執行此操作?

我想我必須在UiApplication中修改SecurityConfiguration並使用類似

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.inMemoryAuthentication()
        .withUser("user")
        .password("password")
        .roles("USER");
}

為解釋在這里 ,但我不知道它會不會打破AngularJS。

那是解決方案:

@Configuration
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
class SecurityConfiguration extends
    WebSecurityConfigurerAdapter {


    @Autowired
    public void registerAuthentication(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
            .withUser("user1")
            .password("password1")
            .roles("ADMIN")
            .and()
            .withUser("user2")
            .password("password2")
            .roles("USER");
    }

只要您不更改身份驗證方案(即BASIC,FORM等),AngularJS都不關心您如何在后端管理用戶帳戶。 當然,如果您將使用固定的用戶名和密碼並將其硬編碼在AngularJS代碼中,則必須對此進行更改。

不會破壞角度兼容性。 但是,除了您提到的代碼更改之外,還需要確保允許匿名訪問/ login URI。 還需要更改重載的configure方法,如下所示:

@Override
protected void configure(HttpSecurity http) throws Exception {
  http
    .httpBasic()
  .and()
    .authorizeRequests()
      .antMatchers("/login.html").permitAll()
  .antMatchers("/index.html", "/home.html").authenticated()
      .antMatchers("/index.html", "/home.html").hasRole("USER")
      .anyRequest().authenticated();
}

暫無
暫無

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

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