80 thoughts to “Spring Boot, MongoDB: JWT Authentication with Spring Security”

  1. When I try to enter with JWT token in /api/test/user Postman gives me a 403 Forbiden error. Where can be possible the error??

  2. Thank you so much I was days and days trying to solve how to put a controller to made a login in my API.

  3. Hello, First of all thanks for the tutorial, as a newcomer in spring boot it really helps.

    Tho I have an error when trying to run my spring app, and I have trouble understanding what is going on, and how to fix it.

    The error message is something like this :
    2021-11-12 15:35:40.261 ERROR 19252 — [ main] o.s.b.web.embedded.tomcat.TomcatStarter : Error starting Tomcat context. Exception: org.springframework.beans.factory.UnsatisfiedDependencyException. Message: Error creating bean with name ‘webSecurityConfig’: Unsatisfied dependency expressed through field ‘userDetailsService’; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name ‘userDetailsServiceImpl’ defined in file [C:\Users\fkuhl\Workflow\SpringCourse\target\classes\com\Thiiamas\SpringCourse\Security\Services\UserDetailsServiceImpl.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘userRepository’ defined in com.Thiiamas.SpringCourse.Repository.UserRepository defined in @EnableMongoRepositories declared on MongoRepositoriesRegistrar.EnableMongoRepositoriesConfiguration: Invocation of init method failed; nested exception is org.springframework.data.repository.query.QueryCreationException: Could not create query for public abstract java.lang.Boolean com.Thiiamas.SpringCourse.Repository.UserRepository.existByUsername(java.lang.String)! Reason: No property existByUsername found for type User!; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property existByUsername found for type User!

    I tried adding “@Repository” annotation to the repositiory, I also generated a constructor on UserDetailsImpl, but it doesn’t really help.

    If you could help me, or explaining what is going on please ! I’m really new to everything server side so i’m kinda lost.

    Florian

  4. Dude, You are a lifesaver. Your tutorials are the same as official documents and you follow best practices. thank you!

  5. 2021-09-29 15:56:23.793 ERROR 15380 — [nio-8084-exec-4] c.b.s.j.m.s.jwt.AuthEntryPointJwt : Unauthorized error: Full authentication is required to access this resource
    please help me

  6. Thanks for the explanation.

    How would you tackle the issue that everyone would be able to add an admin role to their account when using postman to create it (e.g. when they figure out the endpoint to create a new account via networks tab in chrome).

    Thanks!

  7. I’ve got this working as far as I can create a user. But when I try to login I get an error in the console:
    “Encoded password does not look like BCrypt”
    I can see the password is stored as “$2a$10$vjr9VD7P.qPwbxoL66XC1e9AsW9OZUIGXyKBZ0mXW6tdsofcEdnU.” which looks valid to me.
    Is there anything obvious this could be?

    1. Hi, you need to make signin request first, then use the token for accessing test/user.

  8. hi sir,

    All functions are working fine! but when I login as the moderator, the dashboard displays ”Moderator Board” and “User”. when I click one of these option, I can see error “Error: Unauthorized” (I used frontend for your React JWT Authentication (without Redux) example )

    and also throwing error in spring boot console –
    ” ERROR[0;39m [35m18012[0;39m [2m—[0;39m [2m[nio-8080-exec-2][0;39m [36mc.b.s.j.m.s.jwt.AuthEntryPointJwt [0;39m [2m:[0;39m Unauthorized error: Full authentication is required to access this resource”

    when I remove @PreAuthorize(“hasAuthority(‘MODERATOR’)”) it is working.. but that way anyone can access right? I actually find out many ways and try but it didn’t work.

    would you mind giving me a solution for that sir!

    Thank you very much!

    1. I found the error where is sir! the error occurred frontend auth-header.js file. actually not an error that spring boot return access token method is commented and node js access token return is enabled. that’s the case.

      thank you!

  9. Hi,
    I have tried to implement it using dynamodb instead of mongodb. I am getting 401 Unauthorized for all requests.
    Have created the roles table , inserted the roles as well.
    Any idea?

  10. Thank You so much ; )
    Dude, I am working as a trainee in a company and we are forced to work on case study without any training, we are just left to study from youtube and finally got you. You literally saved me. Thanks Once again.

      1. hi and thanks you very much but when i try to sing in i get this message Unauthorized error: Failed to instantiate com.example.Educart.models.User using constructor NO_CONSTRUCTOR with arguments pls can you help me up

  11. It works but when I try to use the other controllers developed by me it seems all autowired classes are null. Do you have any idea why ?

    1. I found the problem. It seems some methods were declared private. Changing to public solved the problem.

  12. I’m getting “Unauthorized User” 401 error on signup and signin requests. Can you please tell me what can be the possible issue? Thanks in advance.

    1. Hi Elie, the possible issue can be that you are using a different role name instead of the ROLE_ADMIN or ROLE_MODERATOR … the roles got to be with the ROLE_ prefix like in the tutorial… other thing is that when you try to access admin-restricted endpoint you got to generate the token and use the authorization header with this value … “Bearer oajjsodijoi3jijdoiajd2dioajsd”

      oajjsodijoi3jijdoiajd2dioajsd mean your access token that was generated. Hope it helps someone… if you are struggling with this tutorial please send me a message and i will help you.

      My email is [email protected]

      Have a nice day.

      1. Hi Jones. when i am using the signup api . its asking for username password. Not sure why , can you please help.

  13. This tutorial saved my life! The only one absolutely complete and clear.

    Thank You!

  14. for a class WebSecurityConfig extends WebSecurityConfigurerAdapter
    a method with configure shows the following error as
    The method userDetailsService(T) in the type AuthenticationManagerBuilder is not applicable for the arguments (UserDetailsImpl) at line authenticationManagerBuilder.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());

    1. I encountered the same error but I realized I did implement the interface on UserDetailsService on my source project instead of referencing the one in the spring library. After deleting UserDetailsService.java I mistakenly created, and referenced the one in the Spring security library, I did not get the errors anymore.

  15. When running under JDK 9/10/11, add these dependencies to your pom file to prevent class not found errors:

    jakarta.xml.bind
    jakarta.xml.bind-api
    2.3.2

    org.glassfish.jaxb
    jaxb-runtime
    2.3.2

  16. Can we use the email in place of username, because like you know apps are modified the way the client want, what if he don’t want a username

  17. Hi, Can i use this reference with Couchbase DB, If yes then how can i add predefined ROLE

  18. Hello Guys ! When you are using the authentication URL: / api / auth / signin and a conversion error occurs you will need to include these libraries in the project, this problem occurred to me, I am forwarding it in case anyone needs help with this problem.

    jakarta.xml.bind
    jakarta.xml.bind-api

    org.glassfish.jaxb
    jaxb-runtime

  19. Thank you for the tutorial. Very detailed and appreciate the visuals.

    I’m getting an error when attempting to POST a request for api/auth/signin using Postman.
    {
    “message”: “Handler dispatch failed; nested exception is java.lang.NoClassDefFoundError: javax/xml/bind/DatatypeConverter”,
    “details”: “uri=/api/v1/auth/signin”
    }

    My research points to a parse error linked to the xml conversion of the data using DatatypeConverter class. I’m using java 8 and believe the dependency module is included.

    Tried importing the DatatypeConvert class in JwtUtils class to parse the secret key but still getting the error. Hopefully you have some ideas? Thank you in advance.

    // get username from JWT
    public String getUserNameFromJwtToken(String token) {
    return Jwts.parser().setSigningKey(DatatypeConverter.parseBase64Binary(jwtSecret)).parseClaimsJws(token).getBody().getSubject();
    }

    // validate a JWT
    public boolean validateJwtToken(String authToken) {

    try {
    Jwts.parser().setSigningKey(DatatypeConverter.parseBase64Binary(jwtSecret)).parseClaimsJws(authToken);
    return true;
    }

    }

    1. Managed to solve this issue. Added the following dependencies. I’m running JDK 8.

      javax.xml.bind
      jaxb-api

      com.sun.xml.bind
      jaxb-impl
      2.3.0

      com.sun.xml.bind
      jaxb-core
      2.3.0

      javax.activation
      activation
      1.1.1

  20. I suppose that the collections roles and users would be auto created after running the project.
    But that’s not the case, can you please explain why?

  21. Thanks a lot for your tutorial. May I know How to implement log-out functionality? Also, How to retrieve email Id from Authentication principal UserDetails?

    1. Hi,
      – for logout in Spring back-end:

      SecurityContextHolder.getContext().setAuthentication(null);
      /code>

      - for Email, you can use UserDetailsImpl:

      UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
      userDetails.getEmail();
      
      1. You mean something like this?

        @PostMapping("/logout")
        	@PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')")
        	public ResponseEntity logoutUser() {
        		SecurityContext securityContext = SecurityContextHolder.getContext();
        		securityContext.setAuthentication(null);
        		return ResponseEntity.ok(new MessageResponse("logout successful"));
        	}
        
      2. s’il vous plait comment on gère la le mot de passe oublié ,comment récupérer le mail ,ici j’ai vu que t’as pas déclaré authentification pour faire getPrincipale ()

      3. Hi, I do not understand why do we have to call logout in the backend. I’m new to this. Don’t we just clear local storage or cookies, and that’s enough? Please correct me if I’m wrong. Thank you.

  22. Hello! Please may you implement “Password Reset” functionality, however I’m looking for a guide to follow. I’ve searched but I didn’t found it I’m always found jwt using another tool.
    So can you plan a serie on that topic.
    Best regards.

  23. Hi i am getting error {“timestamp”:”2020-04-16T06:20:27.849+0000″,”status”:500,”error”:”Internal Server Error”,”message”:”Error: Role is not found.”,”path”:”/api/auth/signup”}

    1. Hi, what is the payload? And did you set 'Content-Type': 'application/json' for HTTP request Header?

      1. Hi I’m also getting this error
        {“timestamp”: “2020-10-19T07:22:47.901+00:00”,
        “status”: 500,
        “error”: “Internal Server Error”,
        “message”: “”,
        “path”: “/api/auth/signup”}
        so what is the solution for this

  24. Hi!
    I faced this problem even I insert ROLE into roles document so please can you help me
    Error: Role is not found.

          1. Sorry I just saw your comment you should first insert roles into your database then problem fixed

          2. Hi, i did as below and worked:
            i use mongodb compass app ,
            first creat new database “bezkoder_db” with colleciton”roles”
            then use bottom >_mongodsh beta , type: use roles
            then copy paste the insert command i

        1. bro can u solve my error role not found….. even though i created the roles in database…..

  25. I have a doubt in reactjs that how we can register with roles.I tried by using dropdown select option but im not getting the exact output.can you give some idea for login ,logout, registration with roles using JWT

  26. hi,
    i have a doubt in these part…

    if (strRoles == null) {
      Role userRole = roleRepository.findByName(ERole.ROLE_USER)
          .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
      roles.add(userRole);
    } else {
      strRoles.forEach(role -> {
        switch (role) {
        case "admin":
          Role adminRole = roleRepository.findByName(ERole.ROLE_ADMIN)
              .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
          roles.add(adminRole);
          break;
        case "mod":
          Role modRole = roleRepository.findByName(ERole.ROLE_MODERATOR)
              .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
          roles.add(modRole);
          break;
        default:
          Role userRole = roleRepository.findByName(ERole.ROLE_USER)
              .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
          roles.add(userRole);
        }
      });
    }
    

    when if part executes.i checked in postman if am giving null the role user is not saved .can u pls explain these briefly

    1. Hi, I think you forgot to run following MongoDB insert statements:

      db.roles.insertMany([
         { name: "ROLE_USER" },
         { name: "ROLE_MODERATOR" },
         { name: "ROLE_ADMIN" },
      ])
      
      1. I am new to mongoDb and I am getting below error
        Error: Role is not found.

        I have already run insert statement in cmd

      2. i am getting an error like “ROLE is not found” .. i have done all the steps

    2. 2020-06-11 16:42:32.272 ERROR 13972 — [nio-8089-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.RuntimeException: Error: Role is not found.] with root cause

      java.lang.RuntimeException: Error: Role is not found.

      I am getting above error message, I have already inserted role.

Comments are closed to reduce spam. If you have any question, please send me an email.