Having difficulty retrieving login credentials from AngularJS to Spring Security

Encountering an issue while developing an app on Angular.js with Spring Security. Unable to send the username and password from UI to spring security, resulting in a null pointer exception. Upon debugging, it was discovered that the username is null. Despite extensive searches on Google, the problem persists. Clicking on the login button directs the debugger to userdetailserviceimpl.java where the username is found to be null when making an AJAX call from the UI.

Here's a snippet of code for SecurityConfig.java:

@Autowired
public void configAuthBuilder(AuthenticationManagerBuilder builder) throws Exception {
    builder.userDetailsService(userDetailServiceImpl);          
}

@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
   .antMatchers("/app/**").permitAll()
   .antMatchers("/login.html").permitAll()
   .anyRequest().authenticated()
   .and()
   .exceptionHandling()
      .authenticationEntryPoint(unauthorisedHandler)
      .accessDeniedHandler(accessDenied)
      .formLogin()
         .loginProcessingUrl("/authenticate")
         .successHandler(authSuccess)
         .usernameParameter("username")
         .passwordParameter("password")
         .permitAll()
      .logout().logoutSuccessHandler(logoutSuccess).permitAll()
      .csrf().disable();      
}

UserDetailServiceImpl.java:

@Service
public class UserDetailServiceImpl implements UserDetailsService {

@Autowired
private LoginDao loginDao;

public UserDetails loadUserByUsername(String username)
        throws UsernameNotFoundException {

    UserInfo userInfo = loginDao.loadUserByUsername(username);
    System.out.println(userInfo.getUserName() + "" + userInfo.getRole());
    GrantedAuthority authority = new SimpleGrantedAuthority(userInfo.getRole());
    UserDetails userDetails = (UserDetails)new User(userInfo.getUserName(), userInfo.getPassword(), Arrays.asList(authority));
    return userDetails;
}

}

Further details about the login process can be found in login.controller.js, login.service.js, and common ajax service sections.

Astraizen

Answer №1

It appears that you are utilizing a wrapper object, whereas Spring is anticipating just the username and password in an object. Adjust

var config = { params: { username: vm.credentials.username, password: vm.credentials.password}};
to
var config = {username: vm.credentials.username, password: vm.credentials.password
. There's also a helpful tutorial available that demonstrates this process simply:

Answer №2

After some trial and error, I was able to resolve the issue by making a small adjustment:

var config = {
                params: {
                 username: vm.credentials.username,
                 password: vm.credentials.password,
                }
               }; 

Instead of the previous configuration, I changed it to:

vm.user = "username="+vm.credentials.username+"&password="+vm.credentials.password;

I want to express my gratitude to everyone who contributed their insights. Hopefully, this solution will prove useful for others in similar situations. :)

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

Connecting the dots between what I observe in Eclipse and the files/folders stored on the disk

I'm struggling to grasp the inner workings of Eclipse. For my Android application project created with the ADT wizard, I noticed that the Projects panel in Eclipse seems to mirror the filesystem directory created in ~/workspaces/MyProjectName. This l ...

looping through the iteration

Here is a link to my original plunker demonstration: http://plnkr.co/edit/9UBZ9E4uxAo1TXXghm1T?p=preview. In the case of div 4 (ng-if="show==4"), I am looking for a way to hide the particular div when the list is empty. Currently, each div is displayed fo ...

Saving Data in an Angular Material Table: A How-to Guide

I have a basic angular material table and I am looking for a way to save the data displayed in each row when a button is clicked. Is it possible to save each row of data as an object and push it to an array? If so, how can I achieve this? <div class=& ...

Guide on developing and releasing a Vuejs component on NPM

I have been diving deep into vue lately and incorporating it into all of the projects at my workplace. As a result, I have developed various components, particularly autocomplete. Although there are plenty of existing options out there, none seem to fulfil ...

Utilizing navigation buttons to move between tabs - material-ui (version 0.18.7)

I'm currently using material ui tabs and attempting to incorporate back and next buttons for tab navigation. However, I've run into an issue - when I click the back or next buttons, the tabs do not switch. Here is my existing code snippet: ... ...

Code for asynchronous routing in Node.js

My current setup involves using node with express version 4.0, and I've noticed a lack of information online (including in the documentation) regarding embedding asynchronous code within a route. With middleware, it's straightforward: app.use(& ...

Guide to locating and substituting two integer values within a string using JavaScript

Given a string such as: "Total duration: 5 days and 10 hours", where there are always two integers in the order of days and then hours. If I need to update the old string based on calculations using fields and other values, what is the most efficient meth ...

Utilize C++ libraries in Android development with Java integration

Can a C++ library be integrated into an Android application? If so, what is the process? Although I am new to Android development (with some background in Java programming), I am curious to know if incorporating a C++ library into an Android app is feasib ...

Transforming JSON arrays into object representations

I have a collection of components structured like this: var names = 1)"lat: 40.6447077, lng: -73.878421, address: 1600 Pennsylvania Avenue, Brooklyn, NY 11239, USA" 2)"lat: 40.609099, lng: -73.931516, address: 2015 E. 35th street, Brooklyn, Ny, Un ...

Updating the video tag's source attribute using JSON information

I am in the process of creating a unique video player using HTML and Javascript that will sequentially play a set of videos until all 6 have been displayed. The URLs for these videos are stored within an array that is mapped in a .json file named clips.jso ...

Utilizing AngularJS to dynamically apply CSS classes based on the $index value

Is there a way to style my div based on the ng-repeat index, applying different styles for odd and even rows? The row with an even index should have all classes specified for the odd one plus additional classes. Controller: var odd = { 'class1&apos ...

Is there a way to retrieve the data instead of receiving an undefined result when making an asynchronous call?

subject in user.subjects = subjects below is undefined instead of being an array of subjects. Context: I am working with three database tables - users, subjects, and a relationship table between users and subjects known as users_subjects. The objective i ...

CSS responsive grid - adding a horizontal separator between rows

I currently have a responsive layout featuring a grid of content blocks. For desktop view, each row consists of 4 blocks. When viewed on a tablet, each row displays 3 blocks. On mobile devices, each row showcases 2 blocks only. I am looking to add a ho ...

Transforming text to emojis in Android EditText dynamically

Is there a way to dynamically replace the text in an EditText with an emoticon? For example, changing "nice to meet you :)" to "nice to meet you [pic]smiley[pic]" Editest.addTextChangedListener(new TextWatcher() { public void onTextChanged( ...

Troubleshooting: Why is jQuery Autocomplete failing to function with JSON PHP to JavaScript integration?

I need to implement an AutoComplete feature with a list of countries from a SQL database. 1. Using PHP: $sql_list_countries=(SQL request) var_dump: array (size=2) 0 => object(stdClass)[3] public 'meta_value' => string &apos ...

Utilizing Google APIs to split a route among multiple locations

I am facing a scenario where A laundry company operates from one shop location. The laundry company has 3 trucks available (n trucks). The laundry company needs to deliver washed clothes to multiple locations (n locations). https://i.sstatic.net/ULup8.pn ...

Unexpected behavior with Ember.js Ajax request

I recently started using the Ember.js framework. While attempting to make an AJAX call from the framework, I encountered unexpected results. Below is the code snippet on the page - Link to the first AJAX call, which is functioning as intended. {{#linkT ...

Include the URL as a parameter in the query when utilizing Tesseract OCR

I have successfully implemented the tesseract ocr, but I am wondering if it is possible to run tesseract with a URL as a parameter. I want to achieve the following: localhost/test.html/?othersite.com/image/image2.jpg Here are some image URLs for demonst ...

Using Javascript's OnChange event to dynamically update data

Attempting to achieve a seemingly straightforward task, but encountering obstacles. The goal is to trigger a JavaScript onChange command and instantly update a radar chart when a numerical value in a form is altered. While the initial values are successful ...

Tips for handling 429 errors while using axios in a react native application

My React Native app is connected to a MongoDB database using Express and Node.js, with Axios handling client-server communication. The app frequently exchanges data with the database, sometimes up to 4 requests per second when in use. While everything wor ...