Angular Basic Auth Spring Boot





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







0















i work with this tutorial https://spring.io/guides/tutorials/spring-security-and-angular-js/#_sso_with_oauth2_angular_js_and_spring_security_part_v using angular 7 and spring boot 2.1.0



my authenticate function in the frontend looks like:



  private api = 'http://localhost:8080/v1/api';

authenticate(credentials): Observable<User> {
const headers = new HttpHeaders(credentials ? {
authorization: 'Basic ' + btoa(credentials.username + ':' + credentials.password)
} : {});

return this.http.get<User>(`${this.api}/user`, {headers: headers})
.pipe(
retry(3),
map(user => this.currentUser = user),
catchError(this.errorHandler)
);
}


My security config like that:



@Throws(Exception::class)
override fun configure(http: HttpSecurity) {
http.cors()
.and().httpBasic()
.and().authorizeRequests().antMatchers("/index.html", "/", "/home", "/login").permitAll()
.anyRequest().authenticated()
.and().csrf().disable()
}

@Bean
fun corsConfigurationSource(): CorsConfigurationSource {
val configuration = CorsConfiguration()
configuration.allowedOrigins = Arrays.asList("http://localhost:4200")
configuration.allowedMethods = Arrays.asList("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS")
configuration.allowedHeaders = Arrays.asList("authorization", "content-type", "x-auth-token")
configuration.exposedHeaders = Arrays.asList("x-auth-token")
val source = UrlBasedCorsConfigurationSource()
source.registerCorsConfiguration("/**", configuration)
return source
}


And my Browser sends a OPTIONS with the following headers:



Accept  text/html,application/xhtml+xm…plication/xml;q=0.9,*/*;q=0.8 
Accept-Encoding gzip, deflate
Accept-Language de,en-US;q=0.7,en;q=0.3
Access-Control-Request-Headers authorization,x-requested-with
Access-Control-Request-Method GET
Cache-Control no-cache
Connection keep-alive
Host localhost:8080
Origin http://localhost:4200
Pragma no-cache
Referer http://localhost:4200/login
User-Agent Mozilla/5.0 (Windows NT 10.0; …) Gecko/20100101 Firefox/64.0


Spring Boot answers with 200 OK



Access-Control-Allow-Headers    authorization
Access-Control-Allow-Methods GET,POST,PUT,PATCH,DELETE,OPTIONS
Access-Control-Allow-Origin http://localhost:4200
Access-Control-Expose-Headers x-auth-token
Cache-Control no-cache, no-store, max-age=0, must-revalidate
Content-Length 0
Date Thu, 22 Nov 2018 19:43:53 GMT
Expires 0
Pragma no-cache
Vary Origin
Vary Access-Control-Request-Method
Vary Access-Control-Request-Headers
X-Content-Type-Options nosniff
X-Frame-Options DENY
X-XSS-Protection 1; mode=block


as far as i understand with cors the browser should send the get request with the auth header afterwards? But nothing happened ... what is wrong?



thx










share|improve this question































    0















    i work with this tutorial https://spring.io/guides/tutorials/spring-security-and-angular-js/#_sso_with_oauth2_angular_js_and_spring_security_part_v using angular 7 and spring boot 2.1.0



    my authenticate function in the frontend looks like:



      private api = 'http://localhost:8080/v1/api';

    authenticate(credentials): Observable<User> {
    const headers = new HttpHeaders(credentials ? {
    authorization: 'Basic ' + btoa(credentials.username + ':' + credentials.password)
    } : {});

    return this.http.get<User>(`${this.api}/user`, {headers: headers})
    .pipe(
    retry(3),
    map(user => this.currentUser = user),
    catchError(this.errorHandler)
    );
    }


    My security config like that:



    @Throws(Exception::class)
    override fun configure(http: HttpSecurity) {
    http.cors()
    .and().httpBasic()
    .and().authorizeRequests().antMatchers("/index.html", "/", "/home", "/login").permitAll()
    .anyRequest().authenticated()
    .and().csrf().disable()
    }

    @Bean
    fun corsConfigurationSource(): CorsConfigurationSource {
    val configuration = CorsConfiguration()
    configuration.allowedOrigins = Arrays.asList("http://localhost:4200")
    configuration.allowedMethods = Arrays.asList("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS")
    configuration.allowedHeaders = Arrays.asList("authorization", "content-type", "x-auth-token")
    configuration.exposedHeaders = Arrays.asList("x-auth-token")
    val source = UrlBasedCorsConfigurationSource()
    source.registerCorsConfiguration("/**", configuration)
    return source
    }


    And my Browser sends a OPTIONS with the following headers:



    Accept  text/html,application/xhtml+xm…plication/xml;q=0.9,*/*;q=0.8 
    Accept-Encoding gzip, deflate
    Accept-Language de,en-US;q=0.7,en;q=0.3
    Access-Control-Request-Headers authorization,x-requested-with
    Access-Control-Request-Method GET
    Cache-Control no-cache
    Connection keep-alive
    Host localhost:8080
    Origin http://localhost:4200
    Pragma no-cache
    Referer http://localhost:4200/login
    User-Agent Mozilla/5.0 (Windows NT 10.0; …) Gecko/20100101 Firefox/64.0


    Spring Boot answers with 200 OK



    Access-Control-Allow-Headers    authorization
    Access-Control-Allow-Methods GET,POST,PUT,PATCH,DELETE,OPTIONS
    Access-Control-Allow-Origin http://localhost:4200
    Access-Control-Expose-Headers x-auth-token
    Cache-Control no-cache, no-store, max-age=0, must-revalidate
    Content-Length 0
    Date Thu, 22 Nov 2018 19:43:53 GMT
    Expires 0
    Pragma no-cache
    Vary Origin
    Vary Access-Control-Request-Method
    Vary Access-Control-Request-Headers
    X-Content-Type-Options nosniff
    X-Frame-Options DENY
    X-XSS-Protection 1; mode=block


    as far as i understand with cors the browser should send the get request with the auth header afterwards? But nothing happened ... what is wrong?



    thx










    share|improve this question



























      0












      0








      0








      i work with this tutorial https://spring.io/guides/tutorials/spring-security-and-angular-js/#_sso_with_oauth2_angular_js_and_spring_security_part_v using angular 7 and spring boot 2.1.0



      my authenticate function in the frontend looks like:



        private api = 'http://localhost:8080/v1/api';

      authenticate(credentials): Observable<User> {
      const headers = new HttpHeaders(credentials ? {
      authorization: 'Basic ' + btoa(credentials.username + ':' + credentials.password)
      } : {});

      return this.http.get<User>(`${this.api}/user`, {headers: headers})
      .pipe(
      retry(3),
      map(user => this.currentUser = user),
      catchError(this.errorHandler)
      );
      }


      My security config like that:



      @Throws(Exception::class)
      override fun configure(http: HttpSecurity) {
      http.cors()
      .and().httpBasic()
      .and().authorizeRequests().antMatchers("/index.html", "/", "/home", "/login").permitAll()
      .anyRequest().authenticated()
      .and().csrf().disable()
      }

      @Bean
      fun corsConfigurationSource(): CorsConfigurationSource {
      val configuration = CorsConfiguration()
      configuration.allowedOrigins = Arrays.asList("http://localhost:4200")
      configuration.allowedMethods = Arrays.asList("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS")
      configuration.allowedHeaders = Arrays.asList("authorization", "content-type", "x-auth-token")
      configuration.exposedHeaders = Arrays.asList("x-auth-token")
      val source = UrlBasedCorsConfigurationSource()
      source.registerCorsConfiguration("/**", configuration)
      return source
      }


      And my Browser sends a OPTIONS with the following headers:



      Accept  text/html,application/xhtml+xm…plication/xml;q=0.9,*/*;q=0.8 
      Accept-Encoding gzip, deflate
      Accept-Language de,en-US;q=0.7,en;q=0.3
      Access-Control-Request-Headers authorization,x-requested-with
      Access-Control-Request-Method GET
      Cache-Control no-cache
      Connection keep-alive
      Host localhost:8080
      Origin http://localhost:4200
      Pragma no-cache
      Referer http://localhost:4200/login
      User-Agent Mozilla/5.0 (Windows NT 10.0; …) Gecko/20100101 Firefox/64.0


      Spring Boot answers with 200 OK



      Access-Control-Allow-Headers    authorization
      Access-Control-Allow-Methods GET,POST,PUT,PATCH,DELETE,OPTIONS
      Access-Control-Allow-Origin http://localhost:4200
      Access-Control-Expose-Headers x-auth-token
      Cache-Control no-cache, no-store, max-age=0, must-revalidate
      Content-Length 0
      Date Thu, 22 Nov 2018 19:43:53 GMT
      Expires 0
      Pragma no-cache
      Vary Origin
      Vary Access-Control-Request-Method
      Vary Access-Control-Request-Headers
      X-Content-Type-Options nosniff
      X-Frame-Options DENY
      X-XSS-Protection 1; mode=block


      as far as i understand with cors the browser should send the get request with the auth header afterwards? But nothing happened ... what is wrong?



      thx










      share|improve this question
















      i work with this tutorial https://spring.io/guides/tutorials/spring-security-and-angular-js/#_sso_with_oauth2_angular_js_and_spring_security_part_v using angular 7 and spring boot 2.1.0



      my authenticate function in the frontend looks like:



        private api = 'http://localhost:8080/v1/api';

      authenticate(credentials): Observable<User> {
      const headers = new HttpHeaders(credentials ? {
      authorization: 'Basic ' + btoa(credentials.username + ':' + credentials.password)
      } : {});

      return this.http.get<User>(`${this.api}/user`, {headers: headers})
      .pipe(
      retry(3),
      map(user => this.currentUser = user),
      catchError(this.errorHandler)
      );
      }


      My security config like that:



      @Throws(Exception::class)
      override fun configure(http: HttpSecurity) {
      http.cors()
      .and().httpBasic()
      .and().authorizeRequests().antMatchers("/index.html", "/", "/home", "/login").permitAll()
      .anyRequest().authenticated()
      .and().csrf().disable()
      }

      @Bean
      fun corsConfigurationSource(): CorsConfigurationSource {
      val configuration = CorsConfiguration()
      configuration.allowedOrigins = Arrays.asList("http://localhost:4200")
      configuration.allowedMethods = Arrays.asList("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS")
      configuration.allowedHeaders = Arrays.asList("authorization", "content-type", "x-auth-token")
      configuration.exposedHeaders = Arrays.asList("x-auth-token")
      val source = UrlBasedCorsConfigurationSource()
      source.registerCorsConfiguration("/**", configuration)
      return source
      }


      And my Browser sends a OPTIONS with the following headers:



      Accept  text/html,application/xhtml+xm…plication/xml;q=0.9,*/*;q=0.8 
      Accept-Encoding gzip, deflate
      Accept-Language de,en-US;q=0.7,en;q=0.3
      Access-Control-Request-Headers authorization,x-requested-with
      Access-Control-Request-Method GET
      Cache-Control no-cache
      Connection keep-alive
      Host localhost:8080
      Origin http://localhost:4200
      Pragma no-cache
      Referer http://localhost:4200/login
      User-Agent Mozilla/5.0 (Windows NT 10.0; …) Gecko/20100101 Firefox/64.0


      Spring Boot answers with 200 OK



      Access-Control-Allow-Headers    authorization
      Access-Control-Allow-Methods GET,POST,PUT,PATCH,DELETE,OPTIONS
      Access-Control-Allow-Origin http://localhost:4200
      Access-Control-Expose-Headers x-auth-token
      Cache-Control no-cache, no-store, max-age=0, must-revalidate
      Content-Length 0
      Date Thu, 22 Nov 2018 19:43:53 GMT
      Expires 0
      Pragma no-cache
      Vary Origin
      Vary Access-Control-Request-Method
      Vary Access-Control-Request-Headers
      X-Content-Type-Options nosniff
      X-Frame-Options DENY
      X-XSS-Protection 1; mode=block


      as far as i understand with cors the browser should send the get request with the auth header afterwards? But nothing happened ... what is wrong?



      thx







      angular spring-boot spring-security basic-authentication angular7






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 30 '18 at 15:48









      Goncalo Peres

      1,4771721




      1,4771721










      asked Nov 22 '18 at 19:53









      IEE1394IEE1394

      331114




      331114
























          1 Answer
          1






          active

          oldest

          votes


















          0














          okay got it:



          changed the spring config to



          http.cors()
          .and().httpBasic()
          .and().authorizeRequests().antMatchers("/index.html", "/", "/home", "/login").permitAll()
          .anyRequest().authenticated()
          .and().csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());


          and add the HttpClientXsrfModule to my angular app. not it works fine.






          share|improve this answer



















          • 1





            It should also work with your configuration in your question. You only added CSRF, but that has nothing to do with CORS. The real problem is on client-side. Your client fix should be enough.

            – dur
            Nov 22 '18 at 20:21











          • yes i could also use the HttpClientXsrfModule.disabled() function ... but with csrf would be much better i guess

            – IEE1394
            Nov 22 '18 at 22:43












          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53437338%2fangular-basic-auth-spring-boot%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          0














          okay got it:



          changed the spring config to



          http.cors()
          .and().httpBasic()
          .and().authorizeRequests().antMatchers("/index.html", "/", "/home", "/login").permitAll()
          .anyRequest().authenticated()
          .and().csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());


          and add the HttpClientXsrfModule to my angular app. not it works fine.






          share|improve this answer



















          • 1





            It should also work with your configuration in your question. You only added CSRF, but that has nothing to do with CORS. The real problem is on client-side. Your client fix should be enough.

            – dur
            Nov 22 '18 at 20:21











          • yes i could also use the HttpClientXsrfModule.disabled() function ... but with csrf would be much better i guess

            – IEE1394
            Nov 22 '18 at 22:43
















          0














          okay got it:



          changed the spring config to



          http.cors()
          .and().httpBasic()
          .and().authorizeRequests().antMatchers("/index.html", "/", "/home", "/login").permitAll()
          .anyRequest().authenticated()
          .and().csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());


          and add the HttpClientXsrfModule to my angular app. not it works fine.






          share|improve this answer



















          • 1





            It should also work with your configuration in your question. You only added CSRF, but that has nothing to do with CORS. The real problem is on client-side. Your client fix should be enough.

            – dur
            Nov 22 '18 at 20:21











          • yes i could also use the HttpClientXsrfModule.disabled() function ... but with csrf would be much better i guess

            – IEE1394
            Nov 22 '18 at 22:43














          0












          0








          0







          okay got it:



          changed the spring config to



          http.cors()
          .and().httpBasic()
          .and().authorizeRequests().antMatchers("/index.html", "/", "/home", "/login").permitAll()
          .anyRequest().authenticated()
          .and().csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());


          and add the HttpClientXsrfModule to my angular app. not it works fine.






          share|improve this answer













          okay got it:



          changed the spring config to



          http.cors()
          .and().httpBasic()
          .and().authorizeRequests().antMatchers("/index.html", "/", "/home", "/login").permitAll()
          .anyRequest().authenticated()
          .and().csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());


          and add the HttpClientXsrfModule to my angular app. not it works fine.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 22 '18 at 20:18









          IEE1394IEE1394

          331114




          331114








          • 1





            It should also work with your configuration in your question. You only added CSRF, but that has nothing to do with CORS. The real problem is on client-side. Your client fix should be enough.

            – dur
            Nov 22 '18 at 20:21











          • yes i could also use the HttpClientXsrfModule.disabled() function ... but with csrf would be much better i guess

            – IEE1394
            Nov 22 '18 at 22:43














          • 1





            It should also work with your configuration in your question. You only added CSRF, but that has nothing to do with CORS. The real problem is on client-side. Your client fix should be enough.

            – dur
            Nov 22 '18 at 20:21











          • yes i could also use the HttpClientXsrfModule.disabled() function ... but with csrf would be much better i guess

            – IEE1394
            Nov 22 '18 at 22:43








          1




          1





          It should also work with your configuration in your question. You only added CSRF, but that has nothing to do with CORS. The real problem is on client-side. Your client fix should be enough.

          – dur
          Nov 22 '18 at 20:21





          It should also work with your configuration in your question. You only added CSRF, but that has nothing to do with CORS. The real problem is on client-side. Your client fix should be enough.

          – dur
          Nov 22 '18 at 20:21













          yes i could also use the HttpClientXsrfModule.disabled() function ... but with csrf would be much better i guess

          – IEE1394
          Nov 22 '18 at 22:43





          yes i could also use the HttpClientXsrfModule.disabled() function ... but with csrf would be much better i guess

          – IEE1394
          Nov 22 '18 at 22:43




















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53437338%2fangular-basic-auth-spring-boot%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          How to change which sound is reproduced for terminal bell?

          Can I use Tabulator js library in my java Spring + Thymeleaf project?

          Title Spacing in Bjornstrup Chapter, Removing Chapter Number From Contents