Hey there! Can someone help me with an issue I'm having regarding authentication with spring-security and

Having an issue with my spring security + angular application. Upon clicking the authentication button, even when inputting correct data, I'm seeing this error in the console:

Access to XMLHttpRequest at 'http://localhost:8080/api/v1/basicauth' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

And

GET http://localhost:8080/api/v1/basicauth net::ERR_FAILED

This is the Angular code snippet:

auth.service.ts

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class AuthenticationService {

  // BASE_PATH: 'http://localhost:8080'
  USER_NAME_SESSION_ATTRIBUTE_NAME = 'authenticatedUser'

  public username: String;
  public password: String;

  constructor(private http: HttpClient) {
    // code here
  }

  authenticationService(username: String, password: String) {
    // code here
  }

  createBasicAuthToken(username: String, password: String) {
    // code here
  }

  registerSuccessfulLogin(username, password) {
    // code here
  }

  logout() {
    // code here
  }

  isUserLoggedIn() {
    // code here
  }

  getLoggedInUserName() {
    // code here
  }
}

login.component.ts

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { AuthenticationService } from './auth.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  // code here
}

http.service.ts

import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { AuthenticationService } from './login/auth.service';

@Injectable()
export class HttpInterceptorService implements HttpInterceptor {
  // code here
}

login.component.html

<div class="container col-lg-6">
  <h1 class="text-center">Login</h1>
  <div class="card">
    <div class="card-body">
      <form class="form-group">
        <div class="alert alert-warning" *ngIf='invalidLogin'>{{errorMessage}}</div>
        <div class="alert alert-success" *ngIf='loginSuccess'>{{successMessage}}</div>
        <div class="form-group">
          <label for="email">User Name :</label>
          <input type="text" class="form-control" id="username" [(ngModel)]="username" placeholder="Enter User Name"
            name="username">
        </div>
        <div class="form-group">
          <label for="pwd">Password:</label>
          <input type="password" class="form-control" [(ngModel)]="password" id="password" placeholder="Enter password"
            name="password">
        </div>
        <button (click)=handleLogin() class="btn btn-success">Login</button>
      </form>
    </div>
  </div>
</div>

Java Code Snippet:

package com.shop.shop.security;

import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
    // code here
}

package com.shop.shop.security;

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@CrossOrigin(origins = "http://localhost:4200")
@RestController
@RequestMapping("api/v1")
public class BasicAuthController {
    // code here
}

package com.shop.shop.security;

public class AuthenticationBean {
    // code here
}

If anyone can assist in resolving and understanding this problem, it would be greatly appreciated! Thank you :)

Answer №1

If you're encountering CORS issues, consider implementing the following solution:

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
        throws IOException, ServletException {

    HttpServletRequest request = (HttpServletRequest) servletRequest;
    System.out.println("CORSFilter HTTP Request: " + request.getMethod());

    // Allow all domains to consume the content
    ((HttpServletResponse) servletResponse).addHeader("Access-Control-Allow-Origin", "*");
    ((HttpServletResponse) servletResponse).addHeader("Access-Control-Allow-Methods","GET, OPTIONS, HEAD, PUT, POST");

    HttpServletResponse resp = (HttpServletResponse) servletResponse;

    // Respond with ACCEPTED status code for HTTP OPTIONS method as part of CORS handshake
    if (request.getMethod().equals("OPTIONS")) {
        resp.setStatus(HttpServletResponse.SC_ACCEPTED);
        return;
    }

    // Continue with the filter chain
    chain.doFilter(request, servletResponse);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Running a Spring Boot .jar file with Java Modules: A Step-by-Step Guide

I am in the process of creating a basic Spring Boot application and running it with Java Modules on the most recent Java version. Here is the Main class I have put together: package org.example; import org.springframework.boot.SpringApplication; import o ...

Error message in Angular 2: Unable to locate node module for import

Recently, I encountered an issue while attempting to utilize a specific node module called aws-api-gateway-client Although the installation was successful, I am facing difficulties with importing this module due to an error. Oddly enough, it works seamle ...

Utilizing a Chrome profile is ineffective in WebdriverIO

Instead of dealing with signing in every time, I prefer pre-signing in on my profile. Even though I am using the code below, it's still not loading in the specified profile. What can I do to resolve this issue? const browser = await remote({ capabi ...

What is the process for connecting an Angular .ts file with an existing HTML page?

As I finish up the html pages for my website, I find myself in need of integrating Angular to complete the project. My experience with Angular so far has been with ionic apps, where the CLI generates the html, ts, and css pages. However, I am curious if ...

Using the Javascript API in IONIC 2, determine the distance between two points

Looking to determine the current position of a user and calculate the distance between their location and others? Utilizing a helpful tutorial for this task, available at: Create a Nearby Places List with Google Maps in Ionic 2. Here's some code excer ...

Difficulties in developing a chat room app

I'm currently working on developing a chatroom application for a website, and I'm considering two different approaches: The first option is to implement socket programming by opening a socket at the server and connecting it to all clients in ...

What is the reasoning behind browserify intervening in the gulp build process to compile my TypeScript code for web workers?

I'm currently working on setting up a web worker in a React/Typescript project that utilizes Gulp with Browserify for the build process. This task has proven to be quite challenging. The issue I'm facing right now is that during the typescript co ...

Tips for widening a union data type in a different section?

Is there a way to expand on a union type from another module? Below is an example showcasing the need for this, but I encountered a ts(3200) error due to duplicate identifiers. The Core module @org/core defines a union type called OptionType: // Defined i ...

Utilizing Java to Store HTML Content in MySQL

Currently, I am immersed in a project that requires storing webpages in a database. To accomplish this task, I am utilizing crawler4j for crawling, along with Proxool and MySQL Java Connector to establish connections with my database. During testing, an e ...

Retrieve files by utilizing the find() function in couchdb-nano

As CouchDB doesn't have collections, I decided to add a custom type property to my entities. Now, I want to filter all the entities based on that property, for example, retrieve all users with {type:'user'}. In the CouchDB documentation, I c ...

Run an executable file with elevated privileges using the Runtime.getRuntime().exec method

For my Windows Selenium Java project, I am attempting to execute an AutoHotKey exe file. However, the execution of the exe file requires administrative privileges. How can I run the following command as an administrator? Runtime.getRuntime().exec("C:& ...

Tips for filtering data in JSON results within a Java servlet

I need to filter records by gender that are in a JSON response. I have a method in my DAO class that returns JSON data, so I want to parse the contents to filter by gender type. String results = bedsBean.allBedsInJson(); System.out.println(results); Th ...

Is it possible to store all data in the Redux store while using Angular?

As I develop an Angular form, I find myself working with numerous 'select' fields. I'd like to populate these select field options from the server. Would it be advisable to store this data in the ngrx store? Or would using services suffice t ...

Issue encountered while loading ng2-bootstrap

Encountering an issue with importing ng2-bootstrap. Here is the error message: http://localhost:3002/ng2-bootstrap/ng2-bootstrap.js 404 (Not Found) Error: Error: XHR error (404 Not Found) loading http://localhost:3002/ng2-bootstrap/ng2-bootstrap.js at ...

Can you help me configure proxy settings for Selenium in my Java application?

In my Java application, I am attempting to update the proxy of the selenium server. However, when I set the proxy in the traditional way, the Selenium server does not recognize this setting. I would like for the proxy IP to be displayed instead of my ac ...

Use ngFor to filter content from another ngFor loop

I am in the process of creating a mobile application that involves filtering students based on their classes assigned by a teacher. Initially, I use ngFor to display all the classes taught by the teacher in a div, and then I aim to list the students enroll ...

When implementing ReplaySubject in Angular for a PUT request, the issue of data loss arises

I seem to be encountering a problem with the ReplaySubject. I can't quite pinpoint what I've done wrong, but the issue is that whenever I make a change and save it in the backend, the ReplaySubject fetches new data but fails to display it on the ...

Difficulty Determining Literal Types that Expand a Union of Basic Data Types

Below are the components and function I am working with: interface ILabel<T> { readonly label: string; readonly key: T } interface IProps<T> { readonly labels: Array<ILabel<T>>; readonly defaultValue: T; readonly onChange ...

Encountering an undefined provider in Ionic 3 is a common issue that can often be attributed to the use of 'barrel' index.ts files, leading to circular dependencies

I've encountered an error in my Angular/TypeScript application that seems a bit useless. While we wait for a better error message, what can be done to address this issue? What are the common scenarios that lead to this error? Here are snippets from my ...

Error: The reference to "global" is undefined and was not caught in the promise

After successfully running my project, I encountered an issue upon installing the aws-sdk package from here. Despite trying to find solutions online, I have been unable to resolve this problem. The error message I am facing is: core.js:1673 ERROR Error ...