Angular 6 Basic Auth returns 401 from client












1















So I've looked around for the answer to my problem for quite a while now and tried many suggestions but I can't seem to find an answer.



The problem is, when I use Postman to check if basic auth works I get a 200 code back and it's all good, but as soon as I try to authenticate using my Login Component I get the code 401 back and says "Full authentication is required to access this resource".



I'm fairly new to Angular and completely new to using Basic Auth so I have no idea why does it work with Postman and why doesn't it work from the app.



Any help is appreciated



Below are the relevant codes



log-in.component.ts:



onLogin(form: NgForm) {
/* ... */
let headers = new Headers();
let userCredentials = user.userName + ":" + user.password;
headers.append("Origin", "http://localhost:8080");
headers.append("Authorization", "Basic " + btoa(userCredentials));

return this.http.post('http://localhost:8080/api/users/login', headers).subscribe(
(response) => {
/* ... */
},
(error) => {
console.log(error);
}
);
}


Endpoint on the server side:



@PostMapping(LOG_IN)
public ResponseEntity<User> login() {
return ResponseEntity.ok().build();
}


WebSecurityConfig:



@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors()
.and()
.csrf().disable()
.authorizeRequests()
.antMatchers("/h2/**").permitAll()
.anyRequest().authenticated()
.and()
.httpBasic()
.authenticationEntryPoint(getBasicAuthEntryPoint())
.and()
.headers()
.frameOptions().disable()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}

@Autowired
protected void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("admin").password("1234").roles("ADMIN");
}

@Autowired
private UserDetailsService userDetailsService;

@Autowired
protected void configureAuthentication(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(userDetailsService)
.passwordEncoder(passwordEncoder());
}

@Bean
public CustomBasicAuthenticationEntryPoint getBasicAuthEntryPoint(){
return new CustomBasicAuthenticationEntryPoint();
}

@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}


CustomBasicAuthenticationEntryPoint:



public class CustomBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoint {

@Override
public void commence(final HttpServletRequest request,
final HttpServletResponse response,
final AuthenticationException authException) throws IOException, ServletException {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.addHeader("WWW-Authenticate", "Basic realm=" + getRealmName() + "");

PrintWriter writer = response.getWriter();
writer.println("HTTP Status 401 : " + authException.getMessage());
}

@Override
public void afterPropertiesSet() throws Exception {
setRealmName("MY REALM");
super.afterPropertiesSet();
}
}


MyUserDetailsService:



@Service
public class MyUserDetailsService implements UserDetailsService {
@Autowired
private UserRepository userRepository;

@Autowired
private AuthenticatedUser authenticatedUser;

@Override
@Transactional(readOnly = true)
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Optional<User> oUser = userRepository.findByUserName(username);

if (!oUser.isPresent()) {
throw new UsernameNotFoundException(username);
}

User user = oUser.get();
authenticatedUser.setUser(user);
Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
grantedAuthorities.add(new SimpleGrantedAuthority(user.getRole().toString()));

return new org.springframework.security.core.userdetails.User(user.getUserName(), user.getPassword(), grantedAuthorities);
}
}









share|improve this question























  • What the type of your http instance? Http or HtppClient?

    – David
    Nov 20 '18 at 20:05











  • It's Http. Could it cause the issue?

    – sn4ckhun
    Nov 21 '18 at 6:14
















1















So I've looked around for the answer to my problem for quite a while now and tried many suggestions but I can't seem to find an answer.



The problem is, when I use Postman to check if basic auth works I get a 200 code back and it's all good, but as soon as I try to authenticate using my Login Component I get the code 401 back and says "Full authentication is required to access this resource".



I'm fairly new to Angular and completely new to using Basic Auth so I have no idea why does it work with Postman and why doesn't it work from the app.



Any help is appreciated



Below are the relevant codes



log-in.component.ts:



onLogin(form: NgForm) {
/* ... */
let headers = new Headers();
let userCredentials = user.userName + ":" + user.password;
headers.append("Origin", "http://localhost:8080");
headers.append("Authorization", "Basic " + btoa(userCredentials));

return this.http.post('http://localhost:8080/api/users/login', headers).subscribe(
(response) => {
/* ... */
},
(error) => {
console.log(error);
}
);
}


Endpoint on the server side:



@PostMapping(LOG_IN)
public ResponseEntity<User> login() {
return ResponseEntity.ok().build();
}


WebSecurityConfig:



@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors()
.and()
.csrf().disable()
.authorizeRequests()
.antMatchers("/h2/**").permitAll()
.anyRequest().authenticated()
.and()
.httpBasic()
.authenticationEntryPoint(getBasicAuthEntryPoint())
.and()
.headers()
.frameOptions().disable()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}

@Autowired
protected void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("admin").password("1234").roles("ADMIN");
}

@Autowired
private UserDetailsService userDetailsService;

@Autowired
protected void configureAuthentication(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(userDetailsService)
.passwordEncoder(passwordEncoder());
}

@Bean
public CustomBasicAuthenticationEntryPoint getBasicAuthEntryPoint(){
return new CustomBasicAuthenticationEntryPoint();
}

@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}


CustomBasicAuthenticationEntryPoint:



public class CustomBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoint {

@Override
public void commence(final HttpServletRequest request,
final HttpServletResponse response,
final AuthenticationException authException) throws IOException, ServletException {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.addHeader("WWW-Authenticate", "Basic realm=" + getRealmName() + "");

PrintWriter writer = response.getWriter();
writer.println("HTTP Status 401 : " + authException.getMessage());
}

@Override
public void afterPropertiesSet() throws Exception {
setRealmName("MY REALM");
super.afterPropertiesSet();
}
}


MyUserDetailsService:



@Service
public class MyUserDetailsService implements UserDetailsService {
@Autowired
private UserRepository userRepository;

@Autowired
private AuthenticatedUser authenticatedUser;

@Override
@Transactional(readOnly = true)
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Optional<User> oUser = userRepository.findByUserName(username);

if (!oUser.isPresent()) {
throw new UsernameNotFoundException(username);
}

User user = oUser.get();
authenticatedUser.setUser(user);
Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
grantedAuthorities.add(new SimpleGrantedAuthority(user.getRole().toString()));

return new org.springframework.security.core.userdetails.User(user.getUserName(), user.getPassword(), grantedAuthorities);
}
}









share|improve this question























  • What the type of your http instance? Http or HtppClient?

    – David
    Nov 20 '18 at 20:05











  • It's Http. Could it cause the issue?

    – sn4ckhun
    Nov 21 '18 at 6:14














1












1








1








So I've looked around for the answer to my problem for quite a while now and tried many suggestions but I can't seem to find an answer.



The problem is, when I use Postman to check if basic auth works I get a 200 code back and it's all good, but as soon as I try to authenticate using my Login Component I get the code 401 back and says "Full authentication is required to access this resource".



I'm fairly new to Angular and completely new to using Basic Auth so I have no idea why does it work with Postman and why doesn't it work from the app.



Any help is appreciated



Below are the relevant codes



log-in.component.ts:



onLogin(form: NgForm) {
/* ... */
let headers = new Headers();
let userCredentials = user.userName + ":" + user.password;
headers.append("Origin", "http://localhost:8080");
headers.append("Authorization", "Basic " + btoa(userCredentials));

return this.http.post('http://localhost:8080/api/users/login', headers).subscribe(
(response) => {
/* ... */
},
(error) => {
console.log(error);
}
);
}


Endpoint on the server side:



@PostMapping(LOG_IN)
public ResponseEntity<User> login() {
return ResponseEntity.ok().build();
}


WebSecurityConfig:



@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors()
.and()
.csrf().disable()
.authorizeRequests()
.antMatchers("/h2/**").permitAll()
.anyRequest().authenticated()
.and()
.httpBasic()
.authenticationEntryPoint(getBasicAuthEntryPoint())
.and()
.headers()
.frameOptions().disable()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}

@Autowired
protected void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("admin").password("1234").roles("ADMIN");
}

@Autowired
private UserDetailsService userDetailsService;

@Autowired
protected void configureAuthentication(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(userDetailsService)
.passwordEncoder(passwordEncoder());
}

@Bean
public CustomBasicAuthenticationEntryPoint getBasicAuthEntryPoint(){
return new CustomBasicAuthenticationEntryPoint();
}

@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}


CustomBasicAuthenticationEntryPoint:



public class CustomBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoint {

@Override
public void commence(final HttpServletRequest request,
final HttpServletResponse response,
final AuthenticationException authException) throws IOException, ServletException {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.addHeader("WWW-Authenticate", "Basic realm=" + getRealmName() + "");

PrintWriter writer = response.getWriter();
writer.println("HTTP Status 401 : " + authException.getMessage());
}

@Override
public void afterPropertiesSet() throws Exception {
setRealmName("MY REALM");
super.afterPropertiesSet();
}
}


MyUserDetailsService:



@Service
public class MyUserDetailsService implements UserDetailsService {
@Autowired
private UserRepository userRepository;

@Autowired
private AuthenticatedUser authenticatedUser;

@Override
@Transactional(readOnly = true)
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Optional<User> oUser = userRepository.findByUserName(username);

if (!oUser.isPresent()) {
throw new UsernameNotFoundException(username);
}

User user = oUser.get();
authenticatedUser.setUser(user);
Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
grantedAuthorities.add(new SimpleGrantedAuthority(user.getRole().toString()));

return new org.springframework.security.core.userdetails.User(user.getUserName(), user.getPassword(), grantedAuthorities);
}
}









share|improve this question














So I've looked around for the answer to my problem for quite a while now and tried many suggestions but I can't seem to find an answer.



The problem is, when I use Postman to check if basic auth works I get a 200 code back and it's all good, but as soon as I try to authenticate using my Login Component I get the code 401 back and says "Full authentication is required to access this resource".



I'm fairly new to Angular and completely new to using Basic Auth so I have no idea why does it work with Postman and why doesn't it work from the app.



Any help is appreciated



Below are the relevant codes



log-in.component.ts:



onLogin(form: NgForm) {
/* ... */
let headers = new Headers();
let userCredentials = user.userName + ":" + user.password;
headers.append("Origin", "http://localhost:8080");
headers.append("Authorization", "Basic " + btoa(userCredentials));

return this.http.post('http://localhost:8080/api/users/login', headers).subscribe(
(response) => {
/* ... */
},
(error) => {
console.log(error);
}
);
}


Endpoint on the server side:



@PostMapping(LOG_IN)
public ResponseEntity<User> login() {
return ResponseEntity.ok().build();
}


WebSecurityConfig:



@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors()
.and()
.csrf().disable()
.authorizeRequests()
.antMatchers("/h2/**").permitAll()
.anyRequest().authenticated()
.and()
.httpBasic()
.authenticationEntryPoint(getBasicAuthEntryPoint())
.and()
.headers()
.frameOptions().disable()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}

@Autowired
protected void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("admin").password("1234").roles("ADMIN");
}

@Autowired
private UserDetailsService userDetailsService;

@Autowired
protected void configureAuthentication(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(userDetailsService)
.passwordEncoder(passwordEncoder());
}

@Bean
public CustomBasicAuthenticationEntryPoint getBasicAuthEntryPoint(){
return new CustomBasicAuthenticationEntryPoint();
}

@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}


CustomBasicAuthenticationEntryPoint:



public class CustomBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoint {

@Override
public void commence(final HttpServletRequest request,
final HttpServletResponse response,
final AuthenticationException authException) throws IOException, ServletException {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.addHeader("WWW-Authenticate", "Basic realm=" + getRealmName() + "");

PrintWriter writer = response.getWriter();
writer.println("HTTP Status 401 : " + authException.getMessage());
}

@Override
public void afterPropertiesSet() throws Exception {
setRealmName("MY REALM");
super.afterPropertiesSet();
}
}


MyUserDetailsService:



@Service
public class MyUserDetailsService implements UserDetailsService {
@Autowired
private UserRepository userRepository;

@Autowired
private AuthenticatedUser authenticatedUser;

@Override
@Transactional(readOnly = true)
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Optional<User> oUser = userRepository.findByUserName(username);

if (!oUser.isPresent()) {
throw new UsernameNotFoundException(username);
}

User user = oUser.get();
authenticatedUser.setUser(user);
Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
grantedAuthorities.add(new SimpleGrantedAuthority(user.getRole().toString()));

return new org.springframework.security.core.userdetails.User(user.getUserName(), user.getPassword(), grantedAuthorities);
}
}






java angular angular6 basic-authentication






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 20 '18 at 19:04









sn4ckhunsn4ckhun

343




343













  • What the type of your http instance? Http or HtppClient?

    – David
    Nov 20 '18 at 20:05











  • It's Http. Could it cause the issue?

    – sn4ckhun
    Nov 21 '18 at 6:14



















  • What the type of your http instance? Http or HtppClient?

    – David
    Nov 20 '18 at 20:05











  • It's Http. Could it cause the issue?

    – sn4ckhun
    Nov 21 '18 at 6:14

















What the type of your http instance? Http or HtppClient?

– David
Nov 20 '18 at 20:05





What the type of your http instance? Http or HtppClient?

– David
Nov 20 '18 at 20:05













It's Http. Could it cause the issue?

– sn4ckhun
Nov 21 '18 at 6:14





It's Http. Could it cause the issue?

– sn4ckhun
Nov 21 '18 at 6:14












2 Answers
2






active

oldest

votes


















1














You need to pass the headers as 3rd parameter for the post method. The 2nd one is the body



return this.http.post('http://localhost:8080/api/users/login', {}, {headers}).subscribe(
(response) => {


If you are using angular 6, you should really be using the new HttpClient class, the old Http class being deprecated






share|improve this answer
























  • Oh my god thank you! I can't believe I've spent hours of debugging and googling only to realize it was a typo like this all along! Thank you very much! :D

    – sn4ckhun
    Nov 21 '18 at 17:18



















0














This is because the browser send OPTION method to the server before send your request, , try to update your security configuration by allowing OPTION method. like this



protected void configure(HttpSecurity http) throws Exception
{
http
.csrf().disable()
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS,"/path/to/allow").permitAll()//allow CORS option calls
.antMatchers("/resources/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.httpBasic();
}





share|improve this answer
























  • I've already tried that once before. I've tried it again but it doesn't help at all. In chrome devtools in network tab I see 2 login requests, one is OPTIONS and that returns with a 200 but the one after is POST and that returns with 401. I assume the OPTIONS one is the preflight?

    – sn4ckhun
    Nov 20 '18 at 19:17











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%2f53399850%2fangular-6-basic-auth-returns-401-from-client%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























2 Answers
2






active

oldest

votes








2 Answers
2






active

oldest

votes









active

oldest

votes






active

oldest

votes









1














You need to pass the headers as 3rd parameter for the post method. The 2nd one is the body



return this.http.post('http://localhost:8080/api/users/login', {}, {headers}).subscribe(
(response) => {


If you are using angular 6, you should really be using the new HttpClient class, the old Http class being deprecated






share|improve this answer
























  • Oh my god thank you! I can't believe I've spent hours of debugging and googling only to realize it was a typo like this all along! Thank you very much! :D

    – sn4ckhun
    Nov 21 '18 at 17:18
















1














You need to pass the headers as 3rd parameter for the post method. The 2nd one is the body



return this.http.post('http://localhost:8080/api/users/login', {}, {headers}).subscribe(
(response) => {


If you are using angular 6, you should really be using the new HttpClient class, the old Http class being deprecated






share|improve this answer
























  • Oh my god thank you! I can't believe I've spent hours of debugging and googling only to realize it was a typo like this all along! Thank you very much! :D

    – sn4ckhun
    Nov 21 '18 at 17:18














1












1








1







You need to pass the headers as 3rd parameter for the post method. The 2nd one is the body



return this.http.post('http://localhost:8080/api/users/login', {}, {headers}).subscribe(
(response) => {


If you are using angular 6, you should really be using the new HttpClient class, the old Http class being deprecated






share|improve this answer













You need to pass the headers as 3rd parameter for the post method. The 2nd one is the body



return this.http.post('http://localhost:8080/api/users/login', {}, {headers}).subscribe(
(response) => {


If you are using angular 6, you should really be using the new HttpClient class, the old Http class being deprecated







share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 21 '18 at 6:29









DavidDavid

11.5k63653




11.5k63653













  • Oh my god thank you! I can't believe I've spent hours of debugging and googling only to realize it was a typo like this all along! Thank you very much! :D

    – sn4ckhun
    Nov 21 '18 at 17:18



















  • Oh my god thank you! I can't believe I've spent hours of debugging and googling only to realize it was a typo like this all along! Thank you very much! :D

    – sn4ckhun
    Nov 21 '18 at 17:18

















Oh my god thank you! I can't believe I've spent hours of debugging and googling only to realize it was a typo like this all along! Thank you very much! :D

– sn4ckhun
Nov 21 '18 at 17:18





Oh my god thank you! I can't believe I've spent hours of debugging and googling only to realize it was a typo like this all along! Thank you very much! :D

– sn4ckhun
Nov 21 '18 at 17:18













0














This is because the browser send OPTION method to the server before send your request, , try to update your security configuration by allowing OPTION method. like this



protected void configure(HttpSecurity http) throws Exception
{
http
.csrf().disable()
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS,"/path/to/allow").permitAll()//allow CORS option calls
.antMatchers("/resources/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.httpBasic();
}





share|improve this answer
























  • I've already tried that once before. I've tried it again but it doesn't help at all. In chrome devtools in network tab I see 2 login requests, one is OPTIONS and that returns with a 200 but the one after is POST and that returns with 401. I assume the OPTIONS one is the preflight?

    – sn4ckhun
    Nov 20 '18 at 19:17
















0














This is because the browser send OPTION method to the server before send your request, , try to update your security configuration by allowing OPTION method. like this



protected void configure(HttpSecurity http) throws Exception
{
http
.csrf().disable()
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS,"/path/to/allow").permitAll()//allow CORS option calls
.antMatchers("/resources/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.httpBasic();
}





share|improve this answer
























  • I've already tried that once before. I've tried it again but it doesn't help at all. In chrome devtools in network tab I see 2 login requests, one is OPTIONS and that returns with a 200 but the one after is POST and that returns with 401. I assume the OPTIONS one is the preflight?

    – sn4ckhun
    Nov 20 '18 at 19:17














0












0








0







This is because the browser send OPTION method to the server before send your request, , try to update your security configuration by allowing OPTION method. like this



protected void configure(HttpSecurity http) throws Exception
{
http
.csrf().disable()
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS,"/path/to/allow").permitAll()//allow CORS option calls
.antMatchers("/resources/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.httpBasic();
}





share|improve this answer













This is because the browser send OPTION method to the server before send your request, , try to update your security configuration by allowing OPTION method. like this



protected void configure(HttpSecurity http) throws Exception
{
http
.csrf().disable()
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS,"/path/to/allow").permitAll()//allow CORS option calls
.antMatchers("/resources/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.httpBasic();
}






share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 20 '18 at 19:10









Christian Altamirano AyalaChristian Altamirano Ayala

161210




161210













  • I've already tried that once before. I've tried it again but it doesn't help at all. In chrome devtools in network tab I see 2 login requests, one is OPTIONS and that returns with a 200 but the one after is POST and that returns with 401. I assume the OPTIONS one is the preflight?

    – sn4ckhun
    Nov 20 '18 at 19:17



















  • I've already tried that once before. I've tried it again but it doesn't help at all. In chrome devtools in network tab I see 2 login requests, one is OPTIONS and that returns with a 200 but the one after is POST and that returns with 401. I assume the OPTIONS one is the preflight?

    – sn4ckhun
    Nov 20 '18 at 19:17

















I've already tried that once before. I've tried it again but it doesn't help at all. In chrome devtools in network tab I see 2 login requests, one is OPTIONS and that returns with a 200 but the one after is POST and that returns with 401. I assume the OPTIONS one is the preflight?

– sn4ckhun
Nov 20 '18 at 19:17





I've already tried that once before. I've tried it again but it doesn't help at all. In chrome devtools in network tab I see 2 login requests, one is OPTIONS and that returns with a 200 but the one after is POST and that returns with 401. I assume the OPTIONS one is the preflight?

– sn4ckhun
Nov 20 '18 at 19:17


















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%2f53399850%2fangular-6-basic-auth-returns-401-from-client%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

Guess what letter conforming each word

Port of Spain

Run scheduled task as local user group (not BUILTIN)