Having trouble locating the error in my Angular and Spring Security application

I am currently working on a project that involves integrating Spring Security with an Angular client. I have encountered an issue where, despite checking for null values in the login form on the Angular side before sending it to the Java application, the Java app returns a message stating that the input is null.

I would greatly appreciate any assistance in resolving this issue as I am unable to pinpoint what may be causing this error. Thank you!

Below are the relevant code snippets and logs:

Log: 2019-07-15 15:30:12.127 WARN 8156 --- [nio-8080-exec-2] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.bind.MethodArgumentNotValidException: Validation failed for argument at index 0 in method: public org.springframework.http.ResponseEntity com.grokonez.jwtauthentication.controller.AuthRestAPIs.authenticateUser(com.grokonez.jwtauthentication.message.request.LoginForm), with 1 error(s): [Field error in object 'loginForm' on field 'username': rejected value [null]; codes [NotBlank.loginForm.username,NotBlank.username,NotBlank.java.lang.String,NotBlank]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [loginForm.username,username]; arguments []; default message [username]]; default message [не может быть пусто]] ]

Java code:

  Model:

public class LoginForm {
    @NotBlank
    @Size(min=3, max = 60)
    private String username;

    @NotBlank
    @Size(min = 6, max = 40)
    private String password; ...

Controller:

@PostMapping("/signin")
    public ResponseEntity<?> authenticateUser(@Valid @RequestBody LoginForm loginRequest) {

        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()));

        SecurityContextHolder.getContext().setAuthentication(authentication);

        String jwt = jwtProvider.generateJwtToken(authentication);
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        return ResponseEntity.ok(new JwtResponse(jwt, userDetails.getUsername(), userDetails.getAuthorities()));
    }

Angular part:

Service:

   const httpOptions = {
  headers: new HttpHeaders({'Content-Type': 'application/json'})
};
@Injectable({
  providedIn: 'root'
})
export class AuthService {

  private loginUrl = 'http://localhost:8080/api/auth/signin';
  private registrationUrl = 'http://localhost:8080/api/auth/signup';

  constructor(private http: HttpClient) { }

  signUp(registrationInfo: RegistrationInfo): Observable<string> {
    return this.http.post<string>(this.registrationUrl, registrationInfo, httpOptions);
  }
  login(loginInfo: LoginInfo): Observable<JwtInfo> {
    console.log(loginInfo)
    return this.http.post<JwtInfo>(this.loginUrl, loginInfo, httpOptions);
  }

Component:

login(data) {
    this.loginInfo = new LoginInfo(data.userName, data.password);
    console.log(data.userName, data.password);
    this.authService.login(this.loginInfo).subscribe(
      (jwtResponse: JwtInfo) => {
        this.tokenStorage.saveToken(jwtResponse.accessToken);
        this.tokenStorage.saveUserName(jwtResponse.username);
        this.tokenStorage.saveAutorities(jwtResponse.authorities);

        this.username = this.tokenStorage.getUserName();
        this.authorities = this.tokenStorage.getAutorities();
        this.isLoggedIn = true;

        this.reloadPage();
      }, error => {
        this.warningMessage = error.error.message;
        this.isLoginFailed = true;
      }
      );
  }

Log with problem: 2019-07-15 15:30:12.127 WARN 8156 --- [nio-8080-exec-2] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.bind.MethodArgumentNotValidException: Validation failed for argument at index 0 in method: public org.springframework.http.ResponseEntity com.grokonez.jwtauthentication.controller.AuthRestAPIs.authenticateUser(com.grokonez.jwtauthentication.message.request.LoginForm), with 1 error(s): [Field error in object 'loginForm' on field 'username': rejected value [null]; codes [NotBlank.loginForm.username,NotBlank.username,NotBlank.java.lang.String,NotBlank]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [loginForm.username,username]; arguments []; default message [username]]; default message [не может быть пусто]] ]

Answer №1

It appears that the LoginForm model has 'username' in lowercase, but you are sending console.log(data.userName, data.password);

There seems to be a case sensitivity issue with 'userName'... try converting the angular login model to use lowercase for the username field

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

Angular's detectChanges method seems to be failing when called on a child component

I've encountered an issue with change detection in my Angular application. For some reason, the change detection stops at the first child in the hierarchy. When I manually invoke change detection one level deeper (in `sch-job-detail`), then the values ...

Encountering an error in testing with Typescript, Express, Mocha, and Chai

After successfully creating my first server using Express in TypeScript, I decided to test the routes in the app. import app from './Server' const server = app.listen(8080, '0.0.0.0', () => { console.log("Server is listening on ...

Is there a way to display the real value instead of [[Ljava.lan.Number]?

I have a series of numeric data points that I am organizing in a List containing timestamps and values. The following code showcases my approach: List<Number> samples = {55,67,57,67}; List<Number[]> dps = Lists.newArrayList(); Calendar c1; c1 ...

What is the proper way to add and verify a list within a list of lists using Java?

In a particular scenario, I am faced with the task of maintaining a list of lists and performing operations based on it. My goal is to obtain a list structured as follows: [{peter,se,red},{peter,da,red},{mark,se,red}] To achieve this, I first create a si ...

JSON Parser - Retrieve information - Not compatible with primitive types

Currently, I am working with JMeter 5.1.1 and attempting to run a load test. To extract user context from a GET Request, I have added a JSON Extractor with the following settings: Names of created variables: schoolId; teacherAccountId; teacherProfileId ...

Convert your socket.io syntax to TypeScript by using the `import` statement instead

const io = require('socket.io')(server, { cors: { origin: '*', } }); Is there a way to convert this code to TypeScript using the syntax import {} from ''; ...

Steps to refresh a variable when the SMS read plugin successfully completes

I'm attempting to make a post call within the success callback of my SMS read plugin code. I can successfully print _this.otpnumber in the console. Please refer to my stack trace image link getSMS(){ var _this= this; var fil ...

Only apply patches to untouched values

Looking for a way to patch only the pristine properties of my reactive form in Angular. Received updates from a websocket service regarding user data, and want to update the form based on the payload without changing dirty properties. Below is the code s ...

"Efficiently Distributing HTTP Requests Among Simultaneous Observers using RxJS

Currently, I am working on a feature in my Angular application that requires handling multiple concurrent fetches for the same data with only one HTTP request being made. This request should be shared among all the subscribers who are requesting the data s ...

In Angular 2+, as you loop through an array of objects, make sure to create a new row (<tr>) for each property of the object

I'm currently grappling with a scenario where I need to utilize tables to achieve the following: Array of objects [ { name:'Jhon', email:'<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail=" ...

Currently honing my skills in Angular 2, but encountering an error stating "Bindings cannot contain assignments."

<app-employeecount [all]= "gettotalemployeescount()" <app-employeecount [all]= "gettotalemployeescount()" [male]= "gettotalmaleemployeescount()" [female]="gettotalfemaleemployeescount()" (on ...

`Managing a large set of options with Angular Material Select``

Currently, I am utilizing the Angular Material select form control to populate a list of options. However, I have encountered an issue where the list could potentially contain up to 100k elements. Although storing this large list is not problematic, displa ...

Shut down application upon browser closure

Currently working on creating a Chrome driver with the following code: ChromeOptions chromeOptions = new ChromeOptions(); chromeOptions.setBinary(CHROME); chromeOptions.addArguments("user-data-dir=" + USER_DATA_DIR); ChromeDriver chromeDriver = new Chrom ...

Learn how to extend components in Typescript and determine necessary arguments. Discover how to apply this knowledge in an Angular use case by extending mat-side-nav

Background: The Angular Material Design component known as mat-side-nav operates in a specific structure for its dynamics: <mat-sidenav-container> <mat-sidenav> </mat-sidenav> <mat-sidenav-content> </mat-sidenav-conten ...

Troubleshooting: Black textures appearing in OpenGL ES 2 rendering

I need assistance with rendering a 2D texture on a quad created from 2 triangles. Despite passing the texture and texture coordinates to the shaders, the output is rendering black. Any help would be greatly appreciated! Render function: public void rende ...

Getting a date object that is three months prior to the current date in Typescript

I need to retrieve the date object that is 3 months before the current date by using the following code snippet: toDate = new Date(); fromDate = this.toDate.getMonth() - 3; The issue I am facing is that the variable fromDate only contains a number, but I ...

What is the process of incorporating a function into an object?

My current object has: public functions = { chosenYearHandler: null, chosenMonthHandler: null }; There is a method within the object: public chosenMonthHandler(normalizedYear: any) { this.form.controls["date"].setValue(normalizedYear); ...

Sorting a JSONArray of JSONObjects that contain nested JSONObjects - here's how!

Sorting a JSONArray of JSONObject is something I can do, but I encountered an issue when trying to sort an array structured like this: [{ "key1": "value1", "key2": "value2", "key3": { "key4": "value4", "key5": "value5" } }, ...

A quick guide on automatically populating text boxes with characteristics of the item chosen from a drop-down menu

On my webpage, I am looking to automatically populate textboxes with information (such as common name, location, etc.) of the selected shop from a dropdown list without having to refresh the page. Here is the dropdown list: <select id="shops" class="f ...

Generate diagnostic logs in Visual Studio Code without using a language server

I have a straightforward extension for Visual Studio Code where I am looking to add warnings without the need to create a whole new language server. Is there a way to achieve this on the document or editor objects directly? My attempts at inspecting the ...