JWT Authentication fails: Bad CredentialsFailed to load the JNI shared Library (JDK)Security configuration with Spring-bootSpring Security Thymleaf static resources don't loadSpring Boot upgrade results in unresolvable circular referenceSpring boot security consider case insensitive username check for loginCustomize Spring Security for trusted spaceSpring-Security 5 always 302Spring boot security cannot log in after invalid credentialsSpring Boot OAuth2 SSO not working when authorizeRequests antMatcher is not set to root url

Improving Performance of an XY Monte Carlo

Rent contract say that pets are not allowed. Possible repercussions if bringing the pet anyway?

'Us students' - Does this apposition need a comma?

What setting causes my autoindent to add indent on a new line?

Why do banks “park” their money at the European Central Bank?

How do I, an introvert, communicate to my friend and only colleague, an extrovert, that I want to spend my scheduled breaks without them?

Was it ever possible to target a zone?

Why did Khan ask Admiral James T. Kirk about Project Genesis?

Architectural feasibility of a tiered circular stone keep

Lost property on Portuguese trains

Why isn't "I've" a proper response?

Papers on arXiv solving the same problem at the same time

How many String objects would be created when concatenating multiple Strings?

What are some interesting features that are common cross-linguistically but don't exist in English?

What is the difference between "Grippe" and "Männergrippe"?

Round towards zero

Why is the UK so keen to remove the "backstop" when their leadership seems to think that no border will be needed in Northern Ireland?

How do you interpolate outside the range of data?

Duplicate Files

Obtaining the intermediate solutions in AMPL

"Sorry to bother you" in an email?

How to prevent clipped screen edges on my TV, HDMI-connected?

Could George I (of Great Britain) speak English?

Circular Reasoning for Epsilon-Delta Proof?



JWT Authentication fails: Bad Credentials


Failed to load the JNI shared Library (JDK)Security configuration with Spring-bootSpring Security Thymleaf static resources don't loadSpring Boot upgrade results in unresolvable circular referenceSpring boot security consider case insensitive username check for loginCustomize Spring Security for trusted spaceSpring-Security 5 always 302Spring boot security cannot log in after invalid credentialsSpring Boot OAuth2 SSO not working when authorizeRequests antMatcher is not set to root url






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I am using Spring boot 2.1.3 with JWT authentication.



the reference link is https://www.callicoder.com/spring-boot-spring-security-jwt-mysql-react-app-part-2/



@SpringBootApplication
public class LrimspublicApplication extends SpringBootServletInitializer implements CommandLineRunner

@Autowired
private PasswordEncoder passwordEncoder;


public static void main(String[] args)
SpringApplication.run(LrimspublicApplication.class, args);



@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application)
return application.sources(LrimspublicApplication.class);



@Override
public void run(String... args) throws Exception
System.out.println(passwordEncoder.encode("devil@123"));





SpringSecurityConfig.java



@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(
securedEnabled = true,
jsr250Enabled = true,
prePostEnabled = true
)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
CustomUserDetailsService customUserDetailsService;

@Autowired
private JwtAuthenticationEntryPoint unauthorizedHandler;

@Bean
public JwtAuthenticationFilter jwtAuthenticationFilter()
return new JwtAuthenticationFilter();


@Override
public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception
authenticationManagerBuilder
.userDetailsService(customUserDetailsService)
.passwordEncoder(passwordEncoder());


@Bean(BeanIds.AUTHENTICATION_MANAGER)
@Override
public AuthenticationManager authenticationManagerBean() throws Exception
return super.authenticationManagerBean();


@Bean
public PasswordEncoder passwordEncoder()
return PasswordEncoderFactories.createDelegatingPasswordEncoder();


@Override
protected void configure(HttpSecurity http) throws Exception
http
.cors()
.and()
.csrf()
.disable()
.exceptionHandling()
.authenticationEntryPoint(unauthorizedHandler)
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/",
"/favicon.ico",
"/**/*.png",
"/**/*.gif",
"/**/*.svg",
"/**/*.jpg",
"/**/*.html",
"/**/*.css",
"/**/*.js")
.permitAll()
.antMatchers("/api/auth/**")
.permitAll()
.antMatchers("/app/**").permitAll()
.antMatchers("/api/user/checkUsernameAvailability", "/api/user/checkEmailAvailability")
.permitAll()
.antMatchers(HttpMethod.GET, "/api/polls/**", "/api/users/**")
.permitAll()
.anyRequest()
.authenticated();

// Add our custom JWT security filter
http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);




and now i am creating new user using a post API which looks like this



@RequestMapping(value = "/app/user/create", method = RequestMethod.POST)
@ResponseBody
public Tbluser createUser(HttpServletRequest request, HttpServletResponse response) throws ParseException

String district="";
String office=null;
String gender="";
String firstName="";
String middleName="";
String lastName="";
String mobileNumber="";
String emailID="";
String dateOfBirth="";
String address="";
String userName="";
String password="";
String employeeId="";
List<Tbluser> users=null;
Tbluser user=new Tbluser();
String encryptedPassword="";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
DateFormat dateformatter = new SimpleDateFormat("dd-MM-yyyy");
Date dt_dateOfBirth = null;
Tblrole role=new Tblrole();
//String userTypeId="Official";
String userTypeId="4";
String active="1";
String description="";
Date createdDate;
String createdBY="";
String userId="";
String newUserRole="";
String secretcode="";
String firstNameNepali="";
String middleNameNepali ="";
String lastNameNepali = "";

try
trydistrict = ServletRequestUtils.getRequiredStringParameter(request, "ddlAddUserDistrict");catch(Exception ex)
tryoffice = ServletRequestUtils.getRequiredStringParameter(request, "ddlAddUserOffice");catch(Exception ex)
trygender=ServletRequestUtils.getRequiredStringParameter(request, "ddlAddUserGender");catch(Exception ex)
tryfirstName=ServletRequestUtils.getRequiredStringParameter(request, "txtAddUserUserFirstName");catch(Exception ex)
trymiddleName = ServletRequestUtils.getRequiredStringParameter(request, "txtAddUserUserMiddleName");catch(Exception ex)
trylastName = ServletRequestUtils.getRequiredStringParameter(request, "txtAddUserUserLastName"); catch(Exception ex)
trymobileNumber = ServletRequestUtils.getRequiredStringParameter(request, "txtAddUserMobileNumber");catch(Exception ex)
tryemailID = ServletRequestUtils.getRequiredStringParameter(request, "txtAddUserEmailID"); catch(Exception ex)
trydateOfBirth = ServletRequestUtils.getRequiredStringParameter(request, "hidUserDateOfBirth");catch(Exception ex)
tryaddress = ServletRequestUtils.getRequiredStringParameter(request, "txtAddUserAddress"); catch(Exception ex)
tryuserName = ServletRequestUtils.getRequiredStringParameter(request, "txtAddUserUserName");catch(Exception ex)
trypassword = ServletRequestUtils.getRequiredStringParameter(request, "txtAddUserPassword");catch(Exception ex)
tryemployeeId = ServletRequestUtils.getRequiredStringParameter(request, "txtAddUserEmployeeId");catch(Exception ex)
trysecretcode= ServletRequestUtils.getRequiredStringParameter(request, "txtAddUserSecretCode");catch(Exception ex)
if (!dateOfBirth.isEmpty() && dateOfBirth!=null)

//dt_dateOfBirth = df.parse(dateOfBirth);
dt_dateOfBirth = dateformatter.parse(dateOfBirth);

trydescription = ServletRequestUtils.getRequiredStringParameter(request, "txtAddUserDescription"); catch(Exception ex)
trycreatedBY= ServletRequestUtils.getRequiredStringParameter(request, "hid-createdBy");catch(Exception ex)
tryuserId=ServletRequestUtils.getRequiredStringParameter(request, "hid-userId");catch(Exception ex)
trynewUserRole=ServletRequestUtils.getRequiredStringParameter(request, "user_roles");catch(Exception ex)

tryfirstNameNepali=ServletRequestUtils.getRequiredStringParameter(request, "txtAddUserUserFirstNameNepali");catch(Exception ex)
trymiddleNameNepali = ServletRequestUtils.getRequiredStringParameter(request, "txtAddUserUserMiddleNameNepali");catch(Exception ex)
trylastNameNepali = ServletRequestUtils.getRequiredStringParameter(request, "txtAddUserUserLastNameNepali");catch(Exception ex)



//*To save Biometric and Image data*//*
try
String imagedata = ServletRequestUtils.getRequiredStringParameter(request, "imagedataForSeller");
String leftthumbimage = ServletRequestUtils.getRequiredStringParameter(request, "hidUserInformationLeftThumbImpressionImage");
String leftthumbdata = ServletRequestUtils.getRequiredStringParameter(request, "hidUserInformationLeftThumbImpressionData");
String rightthumbimage = ServletRequestUtils.getRequiredStringParameter(request, "hidUserInformationRightThumbImpressionImage");
String rightthumbdata = ServletRequestUtils.getRequiredStringParameter(request, "hidUserInformationRightThumbImpressionData");
String signaturedata = ServletRequestUtils.getRequiredStringParameter(request, "hidOldSellerSignatureImage");

if(user.getSignature() == null
catch(Exception ex)

tryuser.setTbldistrict(districtService.findDistirctById(Long.parseLong(district)));catch(Exception ex)
tryuser.setTbloffice(officeService.findOfficeById(Long.parseLong(office)));catch(Exception ex)
tryuser.setTblgender(genderService.findGenderById(Long.parseLong(gender)));catch(Exception ex)
tryuser.setAddress(address);catch(Exception ex)
tryuser.setUsername(userName);catch(Exception ex)
tryuser.setPassword(passwordEncoder.encode(password));catch (Exception ex)

role=roleService.findRoleByID(Long.parseLong(newUserRole));

//* Role mapping *//*

Set<Tblrole> roleSet = new HashSet<Tblrole>();
roleSet.add(role);
user.setTblroles(roleSet);

user= userService.saveUser(user);
catch(Exception ex)
logger.error(ex);

return user;




The user create api successfully creates/inserts the user into database. now when i try to login it fails and says bad credentials:



my login controller is



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

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

//Tbluser user = userRepository.findByUsername(loginRequest.getUsernameOrEmail());
Optional<Tbluser> user = userRepository.findByUsername(loginRequest.getUsernameOrEmail());

Tbluser u = new Tbluser();
if(user.isPresent())
u = user.get();


Tbluser uu =new Tbluser() ;
// UserPojo userPojo =

Map<String ,Object> map = new HashMap<>();
Set<Tblrole> roleList = uu.getTblroles();


SecurityContextHolder.getContext().setAuthentication(authentication);

UserPrincipal userPrincipal = (UserPrincipal) authentication.getPrincipal();

String accessToken = tokenProvider.generateToken(authentication);
String refreshToken = tokenProvider.generateRefreshToken();

//saveRefreshToken(userPrincipal, refreshToken);

StringBuilder builder = new StringBuilder();
String combinedToken =builder.append(accessToken).append(",").append(refreshToken).toString();

return ResponseEntity.ok().header("Authorization",combinedToken).body(map);



UPDATED:-



@Service
public class CustomUserDetailsService implements UserDetailsService

@Autowired
UserRepository userRepository;

@Override
@Transactional
public UserDetails loadUserByUsername(String usernameOrEmail)
throws UsernameNotFoundException
// Let people login with either username or email
Tbluser user = userRepository.findByUsername(usernameOrEmail)
.orElseThrow(() ->
new UsernameNotFoundException("User not found with username or email : " + usernameOrEmail)
);

return UserPrincipal.create(user);


@Transactional
public UserDetails loadUserById(Long id)
Tbluser user = userRepository.findById(id).orElseThrow(
() -> new ResourceNotFoundException("User", "id", id)
);

return UserPrincipal.create(user);




and UserPrincipal is:-



public class UserPrincipal implements UserDetails 
private Long id;

private String name;

private String username;

@JsonIgnore
private String email;

@JsonIgnore
private String password;

private Collection<? extends GrantedAuthority> authorities;

public UserPrincipal(Long id, String name, String username, String email, String password, Collection<? extends GrantedAuthority> authorities)
this.id = id;
this.name = name;
this.username = username;
this.email = email;
this.password = password;
this.authorities = authorities;


public static UserPrincipal create(Tbluser user)
List<GrantedAuthority> authorities = user.getTblroles().stream().map(role ->
new SimpleGrantedAuthority(role.getRolename())
).collect(Collectors.toList());

return new UserPrincipal(
user.getUserid(),
user.getFirstname(),
user.getUsername(),
user.getEmailid(),
user.getPassword(),
authorities
);


//getter setter excluded



now the interesting part is whenever i replace my password in database with the password generated on console (from commandlinerunner implementation) it successfully generates token.



and now when i see /app/create/user api to create user i see nothing wrong in creating the user.



what have i been missing ? pointing an error will really be a massive help to me.










share|improve this question


























  • Please show your CustomUserDetailsService class code.

    – notionquest
    Mar 27 at 18:25











  • please check again. i have updated the post.

    – sagar limbu
    Mar 27 at 18:28






  • 1





    do you have custom AuthenticationProvider ? Otherwise, Spring uses AnonymousAuthenticationProvider.

    – notionquest
    Mar 27 at 18:38






  • 1





    no there is no any custom authentication provider.

    – sagar limbu
    Mar 27 at 18:39











  • // Add our custom JWT security filter http.addFilterAfter(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class); // it will return the HttpSecurity for further customizations

    – kumar
    Mar 28 at 4:12

















0















I am using Spring boot 2.1.3 with JWT authentication.



the reference link is https://www.callicoder.com/spring-boot-spring-security-jwt-mysql-react-app-part-2/



@SpringBootApplication
public class LrimspublicApplication extends SpringBootServletInitializer implements CommandLineRunner

@Autowired
private PasswordEncoder passwordEncoder;


public static void main(String[] args)
SpringApplication.run(LrimspublicApplication.class, args);



@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application)
return application.sources(LrimspublicApplication.class);



@Override
public void run(String... args) throws Exception
System.out.println(passwordEncoder.encode("devil@123"));





SpringSecurityConfig.java



@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(
securedEnabled = true,
jsr250Enabled = true,
prePostEnabled = true
)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
CustomUserDetailsService customUserDetailsService;

@Autowired
private JwtAuthenticationEntryPoint unauthorizedHandler;

@Bean
public JwtAuthenticationFilter jwtAuthenticationFilter()
return new JwtAuthenticationFilter();


@Override
public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception
authenticationManagerBuilder
.userDetailsService(customUserDetailsService)
.passwordEncoder(passwordEncoder());


@Bean(BeanIds.AUTHENTICATION_MANAGER)
@Override
public AuthenticationManager authenticationManagerBean() throws Exception
return super.authenticationManagerBean();


@Bean
public PasswordEncoder passwordEncoder()
return PasswordEncoderFactories.createDelegatingPasswordEncoder();


@Override
protected void configure(HttpSecurity http) throws Exception
http
.cors()
.and()
.csrf()
.disable()
.exceptionHandling()
.authenticationEntryPoint(unauthorizedHandler)
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/",
"/favicon.ico",
"/**/*.png",
"/**/*.gif",
"/**/*.svg",
"/**/*.jpg",
"/**/*.html",
"/**/*.css",
"/**/*.js")
.permitAll()
.antMatchers("/api/auth/**")
.permitAll()
.antMatchers("/app/**").permitAll()
.antMatchers("/api/user/checkUsernameAvailability", "/api/user/checkEmailAvailability")
.permitAll()
.antMatchers(HttpMethod.GET, "/api/polls/**", "/api/users/**")
.permitAll()
.anyRequest()
.authenticated();

// Add our custom JWT security filter
http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);




and now i am creating new user using a post API which looks like this



@RequestMapping(value = "/app/user/create", method = RequestMethod.POST)
@ResponseBody
public Tbluser createUser(HttpServletRequest request, HttpServletResponse response) throws ParseException

String district="";
String office=null;
String gender="";
String firstName="";
String middleName="";
String lastName="";
String mobileNumber="";
String emailID="";
String dateOfBirth="";
String address="";
String userName="";
String password="";
String employeeId="";
List<Tbluser> users=null;
Tbluser user=new Tbluser();
String encryptedPassword="";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
DateFormat dateformatter = new SimpleDateFormat("dd-MM-yyyy");
Date dt_dateOfBirth = null;
Tblrole role=new Tblrole();
//String userTypeId="Official";
String userTypeId="4";
String active="1";
String description="";
Date createdDate;
String createdBY="";
String userId="";
String newUserRole="";
String secretcode="";
String firstNameNepali="";
String middleNameNepali ="";
String lastNameNepali = "";

try
trydistrict = ServletRequestUtils.getRequiredStringParameter(request, "ddlAddUserDistrict");catch(Exception ex)
tryoffice = ServletRequestUtils.getRequiredStringParameter(request, "ddlAddUserOffice");catch(Exception ex)
trygender=ServletRequestUtils.getRequiredStringParameter(request, "ddlAddUserGender");catch(Exception ex)
tryfirstName=ServletRequestUtils.getRequiredStringParameter(request, "txtAddUserUserFirstName");catch(Exception ex)
trymiddleName = ServletRequestUtils.getRequiredStringParameter(request, "txtAddUserUserMiddleName");catch(Exception ex)
trylastName = ServletRequestUtils.getRequiredStringParameter(request, "txtAddUserUserLastName"); catch(Exception ex)
trymobileNumber = ServletRequestUtils.getRequiredStringParameter(request, "txtAddUserMobileNumber");catch(Exception ex)
tryemailID = ServletRequestUtils.getRequiredStringParameter(request, "txtAddUserEmailID"); catch(Exception ex)
trydateOfBirth = ServletRequestUtils.getRequiredStringParameter(request, "hidUserDateOfBirth");catch(Exception ex)
tryaddress = ServletRequestUtils.getRequiredStringParameter(request, "txtAddUserAddress"); catch(Exception ex)
tryuserName = ServletRequestUtils.getRequiredStringParameter(request, "txtAddUserUserName");catch(Exception ex)
trypassword = ServletRequestUtils.getRequiredStringParameter(request, "txtAddUserPassword");catch(Exception ex)
tryemployeeId = ServletRequestUtils.getRequiredStringParameter(request, "txtAddUserEmployeeId");catch(Exception ex)
trysecretcode= ServletRequestUtils.getRequiredStringParameter(request, "txtAddUserSecretCode");catch(Exception ex)
if (!dateOfBirth.isEmpty() && dateOfBirth!=null)

//dt_dateOfBirth = df.parse(dateOfBirth);
dt_dateOfBirth = dateformatter.parse(dateOfBirth);

trydescription = ServletRequestUtils.getRequiredStringParameter(request, "txtAddUserDescription"); catch(Exception ex)
trycreatedBY= ServletRequestUtils.getRequiredStringParameter(request, "hid-createdBy");catch(Exception ex)
tryuserId=ServletRequestUtils.getRequiredStringParameter(request, "hid-userId");catch(Exception ex)
trynewUserRole=ServletRequestUtils.getRequiredStringParameter(request, "user_roles");catch(Exception ex)

tryfirstNameNepali=ServletRequestUtils.getRequiredStringParameter(request, "txtAddUserUserFirstNameNepali");catch(Exception ex)
trymiddleNameNepali = ServletRequestUtils.getRequiredStringParameter(request, "txtAddUserUserMiddleNameNepali");catch(Exception ex)
trylastNameNepali = ServletRequestUtils.getRequiredStringParameter(request, "txtAddUserUserLastNameNepali");catch(Exception ex)



//*To save Biometric and Image data*//*
try
String imagedata = ServletRequestUtils.getRequiredStringParameter(request, "imagedataForSeller");
String leftthumbimage = ServletRequestUtils.getRequiredStringParameter(request, "hidUserInformationLeftThumbImpressionImage");
String leftthumbdata = ServletRequestUtils.getRequiredStringParameter(request, "hidUserInformationLeftThumbImpressionData");
String rightthumbimage = ServletRequestUtils.getRequiredStringParameter(request, "hidUserInformationRightThumbImpressionImage");
String rightthumbdata = ServletRequestUtils.getRequiredStringParameter(request, "hidUserInformationRightThumbImpressionData");
String signaturedata = ServletRequestUtils.getRequiredStringParameter(request, "hidOldSellerSignatureImage");

if(user.getSignature() == null
catch(Exception ex)

tryuser.setTbldistrict(districtService.findDistirctById(Long.parseLong(district)));catch(Exception ex)
tryuser.setTbloffice(officeService.findOfficeById(Long.parseLong(office)));catch(Exception ex)
tryuser.setTblgender(genderService.findGenderById(Long.parseLong(gender)));catch(Exception ex)
tryuser.setAddress(address);catch(Exception ex)
tryuser.setUsername(userName);catch(Exception ex)
tryuser.setPassword(passwordEncoder.encode(password));catch (Exception ex)

role=roleService.findRoleByID(Long.parseLong(newUserRole));

//* Role mapping *//*

Set<Tblrole> roleSet = new HashSet<Tblrole>();
roleSet.add(role);
user.setTblroles(roleSet);

user= userService.saveUser(user);
catch(Exception ex)
logger.error(ex);

return user;




The user create api successfully creates/inserts the user into database. now when i try to login it fails and says bad credentials:



my login controller is



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

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

//Tbluser user = userRepository.findByUsername(loginRequest.getUsernameOrEmail());
Optional<Tbluser> user = userRepository.findByUsername(loginRequest.getUsernameOrEmail());

Tbluser u = new Tbluser();
if(user.isPresent())
u = user.get();


Tbluser uu =new Tbluser() ;
// UserPojo userPojo =

Map<String ,Object> map = new HashMap<>();
Set<Tblrole> roleList = uu.getTblroles();


SecurityContextHolder.getContext().setAuthentication(authentication);

UserPrincipal userPrincipal = (UserPrincipal) authentication.getPrincipal();

String accessToken = tokenProvider.generateToken(authentication);
String refreshToken = tokenProvider.generateRefreshToken();

//saveRefreshToken(userPrincipal, refreshToken);

StringBuilder builder = new StringBuilder();
String combinedToken =builder.append(accessToken).append(",").append(refreshToken).toString();

return ResponseEntity.ok().header("Authorization",combinedToken).body(map);



UPDATED:-



@Service
public class CustomUserDetailsService implements UserDetailsService

@Autowired
UserRepository userRepository;

@Override
@Transactional
public UserDetails loadUserByUsername(String usernameOrEmail)
throws UsernameNotFoundException
// Let people login with either username or email
Tbluser user = userRepository.findByUsername(usernameOrEmail)
.orElseThrow(() ->
new UsernameNotFoundException("User not found with username or email : " + usernameOrEmail)
);

return UserPrincipal.create(user);


@Transactional
public UserDetails loadUserById(Long id)
Tbluser user = userRepository.findById(id).orElseThrow(
() -> new ResourceNotFoundException("User", "id", id)
);

return UserPrincipal.create(user);




and UserPrincipal is:-



public class UserPrincipal implements UserDetails 
private Long id;

private String name;

private String username;

@JsonIgnore
private String email;

@JsonIgnore
private String password;

private Collection<? extends GrantedAuthority> authorities;

public UserPrincipal(Long id, String name, String username, String email, String password, Collection<? extends GrantedAuthority> authorities)
this.id = id;
this.name = name;
this.username = username;
this.email = email;
this.password = password;
this.authorities = authorities;


public static UserPrincipal create(Tbluser user)
List<GrantedAuthority> authorities = user.getTblroles().stream().map(role ->
new SimpleGrantedAuthority(role.getRolename())
).collect(Collectors.toList());

return new UserPrincipal(
user.getUserid(),
user.getFirstname(),
user.getUsername(),
user.getEmailid(),
user.getPassword(),
authorities
);


//getter setter excluded



now the interesting part is whenever i replace my password in database with the password generated on console (from commandlinerunner implementation) it successfully generates token.



and now when i see /app/create/user api to create user i see nothing wrong in creating the user.



what have i been missing ? pointing an error will really be a massive help to me.










share|improve this question


























  • Please show your CustomUserDetailsService class code.

    – notionquest
    Mar 27 at 18:25











  • please check again. i have updated the post.

    – sagar limbu
    Mar 27 at 18:28






  • 1





    do you have custom AuthenticationProvider ? Otherwise, Spring uses AnonymousAuthenticationProvider.

    – notionquest
    Mar 27 at 18:38






  • 1





    no there is no any custom authentication provider.

    – sagar limbu
    Mar 27 at 18:39











  • // Add our custom JWT security filter http.addFilterAfter(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class); // it will return the HttpSecurity for further customizations

    – kumar
    Mar 28 at 4:12













0












0








0








I am using Spring boot 2.1.3 with JWT authentication.



the reference link is https://www.callicoder.com/spring-boot-spring-security-jwt-mysql-react-app-part-2/



@SpringBootApplication
public class LrimspublicApplication extends SpringBootServletInitializer implements CommandLineRunner

@Autowired
private PasswordEncoder passwordEncoder;


public static void main(String[] args)
SpringApplication.run(LrimspublicApplication.class, args);



@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application)
return application.sources(LrimspublicApplication.class);



@Override
public void run(String... args) throws Exception
System.out.println(passwordEncoder.encode("devil@123"));





SpringSecurityConfig.java



@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(
securedEnabled = true,
jsr250Enabled = true,
prePostEnabled = true
)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
CustomUserDetailsService customUserDetailsService;

@Autowired
private JwtAuthenticationEntryPoint unauthorizedHandler;

@Bean
public JwtAuthenticationFilter jwtAuthenticationFilter()
return new JwtAuthenticationFilter();


@Override
public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception
authenticationManagerBuilder
.userDetailsService(customUserDetailsService)
.passwordEncoder(passwordEncoder());


@Bean(BeanIds.AUTHENTICATION_MANAGER)
@Override
public AuthenticationManager authenticationManagerBean() throws Exception
return super.authenticationManagerBean();


@Bean
public PasswordEncoder passwordEncoder()
return PasswordEncoderFactories.createDelegatingPasswordEncoder();


@Override
protected void configure(HttpSecurity http) throws Exception
http
.cors()
.and()
.csrf()
.disable()
.exceptionHandling()
.authenticationEntryPoint(unauthorizedHandler)
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/",
"/favicon.ico",
"/**/*.png",
"/**/*.gif",
"/**/*.svg",
"/**/*.jpg",
"/**/*.html",
"/**/*.css",
"/**/*.js")
.permitAll()
.antMatchers("/api/auth/**")
.permitAll()
.antMatchers("/app/**").permitAll()
.antMatchers("/api/user/checkUsernameAvailability", "/api/user/checkEmailAvailability")
.permitAll()
.antMatchers(HttpMethod.GET, "/api/polls/**", "/api/users/**")
.permitAll()
.anyRequest()
.authenticated();

// Add our custom JWT security filter
http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);




and now i am creating new user using a post API which looks like this



@RequestMapping(value = "/app/user/create", method = RequestMethod.POST)
@ResponseBody
public Tbluser createUser(HttpServletRequest request, HttpServletResponse response) throws ParseException

String district="";
String office=null;
String gender="";
String firstName="";
String middleName="";
String lastName="";
String mobileNumber="";
String emailID="";
String dateOfBirth="";
String address="";
String userName="";
String password="";
String employeeId="";
List<Tbluser> users=null;
Tbluser user=new Tbluser();
String encryptedPassword="";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
DateFormat dateformatter = new SimpleDateFormat("dd-MM-yyyy");
Date dt_dateOfBirth = null;
Tblrole role=new Tblrole();
//String userTypeId="Official";
String userTypeId="4";
String active="1";
String description="";
Date createdDate;
String createdBY="";
String userId="";
String newUserRole="";
String secretcode="";
String firstNameNepali="";
String middleNameNepali ="";
String lastNameNepali = "";

try
trydistrict = ServletRequestUtils.getRequiredStringParameter(request, "ddlAddUserDistrict");catch(Exception ex)
tryoffice = ServletRequestUtils.getRequiredStringParameter(request, "ddlAddUserOffice");catch(Exception ex)
trygender=ServletRequestUtils.getRequiredStringParameter(request, "ddlAddUserGender");catch(Exception ex)
tryfirstName=ServletRequestUtils.getRequiredStringParameter(request, "txtAddUserUserFirstName");catch(Exception ex)
trymiddleName = ServletRequestUtils.getRequiredStringParameter(request, "txtAddUserUserMiddleName");catch(Exception ex)
trylastName = ServletRequestUtils.getRequiredStringParameter(request, "txtAddUserUserLastName"); catch(Exception ex)
trymobileNumber = ServletRequestUtils.getRequiredStringParameter(request, "txtAddUserMobileNumber");catch(Exception ex)
tryemailID = ServletRequestUtils.getRequiredStringParameter(request, "txtAddUserEmailID"); catch(Exception ex)
trydateOfBirth = ServletRequestUtils.getRequiredStringParameter(request, "hidUserDateOfBirth");catch(Exception ex)
tryaddress = ServletRequestUtils.getRequiredStringParameter(request, "txtAddUserAddress"); catch(Exception ex)
tryuserName = ServletRequestUtils.getRequiredStringParameter(request, "txtAddUserUserName");catch(Exception ex)
trypassword = ServletRequestUtils.getRequiredStringParameter(request, "txtAddUserPassword");catch(Exception ex)
tryemployeeId = ServletRequestUtils.getRequiredStringParameter(request, "txtAddUserEmployeeId");catch(Exception ex)
trysecretcode= ServletRequestUtils.getRequiredStringParameter(request, "txtAddUserSecretCode");catch(Exception ex)
if (!dateOfBirth.isEmpty() && dateOfBirth!=null)

//dt_dateOfBirth = df.parse(dateOfBirth);
dt_dateOfBirth = dateformatter.parse(dateOfBirth);

trydescription = ServletRequestUtils.getRequiredStringParameter(request, "txtAddUserDescription"); catch(Exception ex)
trycreatedBY= ServletRequestUtils.getRequiredStringParameter(request, "hid-createdBy");catch(Exception ex)
tryuserId=ServletRequestUtils.getRequiredStringParameter(request, "hid-userId");catch(Exception ex)
trynewUserRole=ServletRequestUtils.getRequiredStringParameter(request, "user_roles");catch(Exception ex)

tryfirstNameNepali=ServletRequestUtils.getRequiredStringParameter(request, "txtAddUserUserFirstNameNepali");catch(Exception ex)
trymiddleNameNepali = ServletRequestUtils.getRequiredStringParameter(request, "txtAddUserUserMiddleNameNepali");catch(Exception ex)
trylastNameNepali = ServletRequestUtils.getRequiredStringParameter(request, "txtAddUserUserLastNameNepali");catch(Exception ex)



//*To save Biometric and Image data*//*
try
String imagedata = ServletRequestUtils.getRequiredStringParameter(request, "imagedataForSeller");
String leftthumbimage = ServletRequestUtils.getRequiredStringParameter(request, "hidUserInformationLeftThumbImpressionImage");
String leftthumbdata = ServletRequestUtils.getRequiredStringParameter(request, "hidUserInformationLeftThumbImpressionData");
String rightthumbimage = ServletRequestUtils.getRequiredStringParameter(request, "hidUserInformationRightThumbImpressionImage");
String rightthumbdata = ServletRequestUtils.getRequiredStringParameter(request, "hidUserInformationRightThumbImpressionData");
String signaturedata = ServletRequestUtils.getRequiredStringParameter(request, "hidOldSellerSignatureImage");

if(user.getSignature() == null
catch(Exception ex)

tryuser.setTbldistrict(districtService.findDistirctById(Long.parseLong(district)));catch(Exception ex)
tryuser.setTbloffice(officeService.findOfficeById(Long.parseLong(office)));catch(Exception ex)
tryuser.setTblgender(genderService.findGenderById(Long.parseLong(gender)));catch(Exception ex)
tryuser.setAddress(address);catch(Exception ex)
tryuser.setUsername(userName);catch(Exception ex)
tryuser.setPassword(passwordEncoder.encode(password));catch (Exception ex)

role=roleService.findRoleByID(Long.parseLong(newUserRole));

//* Role mapping *//*

Set<Tblrole> roleSet = new HashSet<Tblrole>();
roleSet.add(role);
user.setTblroles(roleSet);

user= userService.saveUser(user);
catch(Exception ex)
logger.error(ex);

return user;




The user create api successfully creates/inserts the user into database. now when i try to login it fails and says bad credentials:



my login controller is



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

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

//Tbluser user = userRepository.findByUsername(loginRequest.getUsernameOrEmail());
Optional<Tbluser> user = userRepository.findByUsername(loginRequest.getUsernameOrEmail());

Tbluser u = new Tbluser();
if(user.isPresent())
u = user.get();


Tbluser uu =new Tbluser() ;
// UserPojo userPojo =

Map<String ,Object> map = new HashMap<>();
Set<Tblrole> roleList = uu.getTblroles();


SecurityContextHolder.getContext().setAuthentication(authentication);

UserPrincipal userPrincipal = (UserPrincipal) authentication.getPrincipal();

String accessToken = tokenProvider.generateToken(authentication);
String refreshToken = tokenProvider.generateRefreshToken();

//saveRefreshToken(userPrincipal, refreshToken);

StringBuilder builder = new StringBuilder();
String combinedToken =builder.append(accessToken).append(",").append(refreshToken).toString();

return ResponseEntity.ok().header("Authorization",combinedToken).body(map);



UPDATED:-



@Service
public class CustomUserDetailsService implements UserDetailsService

@Autowired
UserRepository userRepository;

@Override
@Transactional
public UserDetails loadUserByUsername(String usernameOrEmail)
throws UsernameNotFoundException
// Let people login with either username or email
Tbluser user = userRepository.findByUsername(usernameOrEmail)
.orElseThrow(() ->
new UsernameNotFoundException("User not found with username or email : " + usernameOrEmail)
);

return UserPrincipal.create(user);


@Transactional
public UserDetails loadUserById(Long id)
Tbluser user = userRepository.findById(id).orElseThrow(
() -> new ResourceNotFoundException("User", "id", id)
);

return UserPrincipal.create(user);




and UserPrincipal is:-



public class UserPrincipal implements UserDetails 
private Long id;

private String name;

private String username;

@JsonIgnore
private String email;

@JsonIgnore
private String password;

private Collection<? extends GrantedAuthority> authorities;

public UserPrincipal(Long id, String name, String username, String email, String password, Collection<? extends GrantedAuthority> authorities)
this.id = id;
this.name = name;
this.username = username;
this.email = email;
this.password = password;
this.authorities = authorities;


public static UserPrincipal create(Tbluser user)
List<GrantedAuthority> authorities = user.getTblroles().stream().map(role ->
new SimpleGrantedAuthority(role.getRolename())
).collect(Collectors.toList());

return new UserPrincipal(
user.getUserid(),
user.getFirstname(),
user.getUsername(),
user.getEmailid(),
user.getPassword(),
authorities
);


//getter setter excluded



now the interesting part is whenever i replace my password in database with the password generated on console (from commandlinerunner implementation) it successfully generates token.



and now when i see /app/create/user api to create user i see nothing wrong in creating the user.



what have i been missing ? pointing an error will really be a massive help to me.










share|improve this question
















I am using Spring boot 2.1.3 with JWT authentication.



the reference link is https://www.callicoder.com/spring-boot-spring-security-jwt-mysql-react-app-part-2/



@SpringBootApplication
public class LrimspublicApplication extends SpringBootServletInitializer implements CommandLineRunner

@Autowired
private PasswordEncoder passwordEncoder;


public static void main(String[] args)
SpringApplication.run(LrimspublicApplication.class, args);



@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application)
return application.sources(LrimspublicApplication.class);



@Override
public void run(String... args) throws Exception
System.out.println(passwordEncoder.encode("devil@123"));





SpringSecurityConfig.java



@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(
securedEnabled = true,
jsr250Enabled = true,
prePostEnabled = true
)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
CustomUserDetailsService customUserDetailsService;

@Autowired
private JwtAuthenticationEntryPoint unauthorizedHandler;

@Bean
public JwtAuthenticationFilter jwtAuthenticationFilter()
return new JwtAuthenticationFilter();


@Override
public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception
authenticationManagerBuilder
.userDetailsService(customUserDetailsService)
.passwordEncoder(passwordEncoder());


@Bean(BeanIds.AUTHENTICATION_MANAGER)
@Override
public AuthenticationManager authenticationManagerBean() throws Exception
return super.authenticationManagerBean();


@Bean
public PasswordEncoder passwordEncoder()
return PasswordEncoderFactories.createDelegatingPasswordEncoder();


@Override
protected void configure(HttpSecurity http) throws Exception
http
.cors()
.and()
.csrf()
.disable()
.exceptionHandling()
.authenticationEntryPoint(unauthorizedHandler)
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/",
"/favicon.ico",
"/**/*.png",
"/**/*.gif",
"/**/*.svg",
"/**/*.jpg",
"/**/*.html",
"/**/*.css",
"/**/*.js")
.permitAll()
.antMatchers("/api/auth/**")
.permitAll()
.antMatchers("/app/**").permitAll()
.antMatchers("/api/user/checkUsernameAvailability", "/api/user/checkEmailAvailability")
.permitAll()
.antMatchers(HttpMethod.GET, "/api/polls/**", "/api/users/**")
.permitAll()
.anyRequest()
.authenticated();

// Add our custom JWT security filter
http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);




and now i am creating new user using a post API which looks like this



@RequestMapping(value = "/app/user/create", method = RequestMethod.POST)
@ResponseBody
public Tbluser createUser(HttpServletRequest request, HttpServletResponse response) throws ParseException

String district="";
String office=null;
String gender="";
String firstName="";
String middleName="";
String lastName="";
String mobileNumber="";
String emailID="";
String dateOfBirth="";
String address="";
String userName="";
String password="";
String employeeId="";
List<Tbluser> users=null;
Tbluser user=new Tbluser();
String encryptedPassword="";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
DateFormat dateformatter = new SimpleDateFormat("dd-MM-yyyy");
Date dt_dateOfBirth = null;
Tblrole role=new Tblrole();
//String userTypeId="Official";
String userTypeId="4";
String active="1";
String description="";
Date createdDate;
String createdBY="";
String userId="";
String newUserRole="";
String secretcode="";
String firstNameNepali="";
String middleNameNepali ="";
String lastNameNepali = "";

try
trydistrict = ServletRequestUtils.getRequiredStringParameter(request, "ddlAddUserDistrict");catch(Exception ex)
tryoffice = ServletRequestUtils.getRequiredStringParameter(request, "ddlAddUserOffice");catch(Exception ex)
trygender=ServletRequestUtils.getRequiredStringParameter(request, "ddlAddUserGender");catch(Exception ex)
tryfirstName=ServletRequestUtils.getRequiredStringParameter(request, "txtAddUserUserFirstName");catch(Exception ex)
trymiddleName = ServletRequestUtils.getRequiredStringParameter(request, "txtAddUserUserMiddleName");catch(Exception ex)
trylastName = ServletRequestUtils.getRequiredStringParameter(request, "txtAddUserUserLastName"); catch(Exception ex)
trymobileNumber = ServletRequestUtils.getRequiredStringParameter(request, "txtAddUserMobileNumber");catch(Exception ex)
tryemailID = ServletRequestUtils.getRequiredStringParameter(request, "txtAddUserEmailID"); catch(Exception ex)
trydateOfBirth = ServletRequestUtils.getRequiredStringParameter(request, "hidUserDateOfBirth");catch(Exception ex)
tryaddress = ServletRequestUtils.getRequiredStringParameter(request, "txtAddUserAddress"); catch(Exception ex)
tryuserName = ServletRequestUtils.getRequiredStringParameter(request, "txtAddUserUserName");catch(Exception ex)
trypassword = ServletRequestUtils.getRequiredStringParameter(request, "txtAddUserPassword");catch(Exception ex)
tryemployeeId = ServletRequestUtils.getRequiredStringParameter(request, "txtAddUserEmployeeId");catch(Exception ex)
trysecretcode= ServletRequestUtils.getRequiredStringParameter(request, "txtAddUserSecretCode");catch(Exception ex)
if (!dateOfBirth.isEmpty() && dateOfBirth!=null)

//dt_dateOfBirth = df.parse(dateOfBirth);
dt_dateOfBirth = dateformatter.parse(dateOfBirth);

trydescription = ServletRequestUtils.getRequiredStringParameter(request, "txtAddUserDescription"); catch(Exception ex)
trycreatedBY= ServletRequestUtils.getRequiredStringParameter(request, "hid-createdBy");catch(Exception ex)
tryuserId=ServletRequestUtils.getRequiredStringParameter(request, "hid-userId");catch(Exception ex)
trynewUserRole=ServletRequestUtils.getRequiredStringParameter(request, "user_roles");catch(Exception ex)

tryfirstNameNepali=ServletRequestUtils.getRequiredStringParameter(request, "txtAddUserUserFirstNameNepali");catch(Exception ex)
trymiddleNameNepali = ServletRequestUtils.getRequiredStringParameter(request, "txtAddUserUserMiddleNameNepali");catch(Exception ex)
trylastNameNepali = ServletRequestUtils.getRequiredStringParameter(request, "txtAddUserUserLastNameNepali");catch(Exception ex)



//*To save Biometric and Image data*//*
try
String imagedata = ServletRequestUtils.getRequiredStringParameter(request, "imagedataForSeller");
String leftthumbimage = ServletRequestUtils.getRequiredStringParameter(request, "hidUserInformationLeftThumbImpressionImage");
String leftthumbdata = ServletRequestUtils.getRequiredStringParameter(request, "hidUserInformationLeftThumbImpressionData");
String rightthumbimage = ServletRequestUtils.getRequiredStringParameter(request, "hidUserInformationRightThumbImpressionImage");
String rightthumbdata = ServletRequestUtils.getRequiredStringParameter(request, "hidUserInformationRightThumbImpressionData");
String signaturedata = ServletRequestUtils.getRequiredStringParameter(request, "hidOldSellerSignatureImage");

if(user.getSignature() == null
catch(Exception ex)

tryuser.setTbldistrict(districtService.findDistirctById(Long.parseLong(district)));catch(Exception ex)
tryuser.setTbloffice(officeService.findOfficeById(Long.parseLong(office)));catch(Exception ex)
tryuser.setTblgender(genderService.findGenderById(Long.parseLong(gender)));catch(Exception ex)
tryuser.setAddress(address);catch(Exception ex)
tryuser.setUsername(userName);catch(Exception ex)
tryuser.setPassword(passwordEncoder.encode(password));catch (Exception ex)

role=roleService.findRoleByID(Long.parseLong(newUserRole));

//* Role mapping *//*

Set<Tblrole> roleSet = new HashSet<Tblrole>();
roleSet.add(role);
user.setTblroles(roleSet);

user= userService.saveUser(user);
catch(Exception ex)
logger.error(ex);

return user;




The user create api successfully creates/inserts the user into database. now when i try to login it fails and says bad credentials:



my login controller is



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

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

//Tbluser user = userRepository.findByUsername(loginRequest.getUsernameOrEmail());
Optional<Tbluser> user = userRepository.findByUsername(loginRequest.getUsernameOrEmail());

Tbluser u = new Tbluser();
if(user.isPresent())
u = user.get();


Tbluser uu =new Tbluser() ;
// UserPojo userPojo =

Map<String ,Object> map = new HashMap<>();
Set<Tblrole> roleList = uu.getTblroles();


SecurityContextHolder.getContext().setAuthentication(authentication);

UserPrincipal userPrincipal = (UserPrincipal) authentication.getPrincipal();

String accessToken = tokenProvider.generateToken(authentication);
String refreshToken = tokenProvider.generateRefreshToken();

//saveRefreshToken(userPrincipal, refreshToken);

StringBuilder builder = new StringBuilder();
String combinedToken =builder.append(accessToken).append(",").append(refreshToken).toString();

return ResponseEntity.ok().header("Authorization",combinedToken).body(map);



UPDATED:-



@Service
public class CustomUserDetailsService implements UserDetailsService

@Autowired
UserRepository userRepository;

@Override
@Transactional
public UserDetails loadUserByUsername(String usernameOrEmail)
throws UsernameNotFoundException
// Let people login with either username or email
Tbluser user = userRepository.findByUsername(usernameOrEmail)
.orElseThrow(() ->
new UsernameNotFoundException("User not found with username or email : " + usernameOrEmail)
);

return UserPrincipal.create(user);


@Transactional
public UserDetails loadUserById(Long id)
Tbluser user = userRepository.findById(id).orElseThrow(
() -> new ResourceNotFoundException("User", "id", id)
);

return UserPrincipal.create(user);




and UserPrincipal is:-



public class UserPrincipal implements UserDetails 
private Long id;

private String name;

private String username;

@JsonIgnore
private String email;

@JsonIgnore
private String password;

private Collection<? extends GrantedAuthority> authorities;

public UserPrincipal(Long id, String name, String username, String email, String password, Collection<? extends GrantedAuthority> authorities)
this.id = id;
this.name = name;
this.username = username;
this.email = email;
this.password = password;
this.authorities = authorities;


public static UserPrincipal create(Tbluser user)
List<GrantedAuthority> authorities = user.getTblroles().stream().map(role ->
new SimpleGrantedAuthority(role.getRolename())
).collect(Collectors.toList());

return new UserPrincipal(
user.getUserid(),
user.getFirstname(),
user.getUsername(),
user.getEmailid(),
user.getPassword(),
authorities
);


//getter setter excluded



now the interesting part is whenever i replace my password in database with the password generated on console (from commandlinerunner implementation) it successfully generates token.



and now when i see /app/create/user api to create user i see nothing wrong in creating the user.



what have i been missing ? pointing an error will really be a massive help to me.







java spring-boot spring-security






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 27 at 18:42







sagar limbu

















asked Mar 27 at 18:22









sagar limbusagar limbu

5111 gold badge8 silver badges28 bronze badges




5111 gold badge8 silver badges28 bronze badges















  • Please show your CustomUserDetailsService class code.

    – notionquest
    Mar 27 at 18:25











  • please check again. i have updated the post.

    – sagar limbu
    Mar 27 at 18:28






  • 1





    do you have custom AuthenticationProvider ? Otherwise, Spring uses AnonymousAuthenticationProvider.

    – notionquest
    Mar 27 at 18:38






  • 1





    no there is no any custom authentication provider.

    – sagar limbu
    Mar 27 at 18:39











  • // Add our custom JWT security filter http.addFilterAfter(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class); // it will return the HttpSecurity for further customizations

    – kumar
    Mar 28 at 4:12

















  • Please show your CustomUserDetailsService class code.

    – notionquest
    Mar 27 at 18:25











  • please check again. i have updated the post.

    – sagar limbu
    Mar 27 at 18:28






  • 1





    do you have custom AuthenticationProvider ? Otherwise, Spring uses AnonymousAuthenticationProvider.

    – notionquest
    Mar 27 at 18:38






  • 1





    no there is no any custom authentication provider.

    – sagar limbu
    Mar 27 at 18:39











  • // Add our custom JWT security filter http.addFilterAfter(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class); // it will return the HttpSecurity for further customizations

    – kumar
    Mar 28 at 4:12
















Please show your CustomUserDetailsService class code.

– notionquest
Mar 27 at 18:25





Please show your CustomUserDetailsService class code.

– notionquest
Mar 27 at 18:25













please check again. i have updated the post.

– sagar limbu
Mar 27 at 18:28





please check again. i have updated the post.

– sagar limbu
Mar 27 at 18:28




1




1





do you have custom AuthenticationProvider ? Otherwise, Spring uses AnonymousAuthenticationProvider.

– notionquest
Mar 27 at 18:38





do you have custom AuthenticationProvider ? Otherwise, Spring uses AnonymousAuthenticationProvider.

– notionquest
Mar 27 at 18:38




1




1





no there is no any custom authentication provider.

– sagar limbu
Mar 27 at 18:39





no there is no any custom authentication provider.

– sagar limbu
Mar 27 at 18:39













// Add our custom JWT security filter http.addFilterAfter(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class); // it will return the HttpSecurity for further customizations

– kumar
Mar 28 at 4:12





// Add our custom JWT security filter http.addFilterAfter(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class); // it will return the HttpSecurity for further customizations

– kumar
Mar 28 at 4:12












0






active

oldest

votes










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%2f55384138%2fjwt-authentication-fails-bad-credentials%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























0






active

oldest

votes








0






active

oldest

votes









active

oldest

votes






active

oldest

votes




Is this question similar to what you get asked at work? Learn more about asking and sharing private information with your coworkers using Stack Overflow for Teams.







Is this question similar to what you get asked at work? Learn more about asking and sharing private information with your coworkers using Stack Overflow for Teams.



















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%2f55384138%2fjwt-authentication-fails-bad-credentials%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

Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript