spring boot + Angular + JWT: Not getting Authentication from Context









up vote
-1
down vote

favorite












I trying to authenticate and authorize by Spring Security. I am able to authenticate and authorize when I use Postman pulgin. But when I integrate the application with Frontend (i.e angular) the SecurityContextHolder.getContext().getAuthentication() returns null.



Any help would be great appreciated. I have been trying to do this since past 3-4 weeks. As there are many classes for this configuration, I am not putting all code here. Please let me know what code (apart from below code) you need, so I can get a help from you. Fyi: initially when I was calling /authenticateAndGenerateToken and then call /student, it was not getting the authentication. So I added code to put the authentication in the controller(as shown below). I am using auth0/angular-jwt



Thanks in advance!!



JwtAuthenticationFilter.java



public class JwtAuthenticationFilter extends OncePerRequestFilter 

@Autowired
private JwtTokenProvider tokenProvider;

private static final Logger logger = LoggerFactory.getLogger(JwtAuthenticationFilter.class);

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException
String jwt = getJwtFromRequest(request);
String url = getFullURL(request);
System.out.println("URL:..............." + url);
if(jwt == null && !url.contains("api/security/authentication/authenticateAndGenerateToken"))
jwt = "No Token Provided";

if (StringUtils.hasText(jwt))
if(tokenProvider.validateToken(jwt))
UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

SecurityContextHolder.getContext().setAuthentication(authentication);
else
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Required headers not specified in the request");
System.out.println("Token Validation Failed.....");


filterChain.doFilter(request, response);


private String getJwtFromRequest(HttpServletRequest request)
String bearerToken = request.getHeader("Authorization");
if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer "))
return bearerToken.substring(7, bearerToken.length());

return null;


public String getFullURL(HttpServletRequest request)
StringBuilder requestURL = new StringBuilder(request.getRequestURL().toString());
String queryString = request.getQueryString();

if (queryString == null)
return requestURL.toString();
else
return requestURL.append('?').append(queryString).toString();





AuthenticationController.java



 @RestController
@RequestMapping("/api/auth")
@CrossOrigin
public class AuthController
@SuppressWarnings( "unchecked", "rawtypes" )
@PostMapping("/authenticateAndGenerateToken")
public ResponseEntity<?> authenticateUser(@RequestBody LoginRequest loginRequest)
if(loginRequest.getUsername().isEmpty()










share|improve this question

























    up vote
    -1
    down vote

    favorite












    I trying to authenticate and authorize by Spring Security. I am able to authenticate and authorize when I use Postman pulgin. But when I integrate the application with Frontend (i.e angular) the SecurityContextHolder.getContext().getAuthentication() returns null.



    Any help would be great appreciated. I have been trying to do this since past 3-4 weeks. As there are many classes for this configuration, I am not putting all code here. Please let me know what code (apart from below code) you need, so I can get a help from you. Fyi: initially when I was calling /authenticateAndGenerateToken and then call /student, it was not getting the authentication. So I added code to put the authentication in the controller(as shown below). I am using auth0/angular-jwt



    Thanks in advance!!



    JwtAuthenticationFilter.java



    public class JwtAuthenticationFilter extends OncePerRequestFilter 

    @Autowired
    private JwtTokenProvider tokenProvider;

    private static final Logger logger = LoggerFactory.getLogger(JwtAuthenticationFilter.class);

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException
    String jwt = getJwtFromRequest(request);
    String url = getFullURL(request);
    System.out.println("URL:..............." + url);
    if(jwt == null && !url.contains("api/security/authentication/authenticateAndGenerateToken"))
    jwt = "No Token Provided";

    if (StringUtils.hasText(jwt))
    if(tokenProvider.validateToken(jwt))
    UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

    SecurityContextHolder.getContext().setAuthentication(authentication);
    else
    response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Required headers not specified in the request");
    System.out.println("Token Validation Failed.....");


    filterChain.doFilter(request, response);


    private String getJwtFromRequest(HttpServletRequest request)
    String bearerToken = request.getHeader("Authorization");
    if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer "))
    return bearerToken.substring(7, bearerToken.length());

    return null;


    public String getFullURL(HttpServletRequest request)
    StringBuilder requestURL = new StringBuilder(request.getRequestURL().toString());
    String queryString = request.getQueryString();

    if (queryString == null)
    return requestURL.toString();
    else
    return requestURL.append('?').append(queryString).toString();





    AuthenticationController.java



     @RestController
    @RequestMapping("/api/auth")
    @CrossOrigin
    public class AuthController
    @SuppressWarnings( "unchecked", "rawtypes" )
    @PostMapping("/authenticateAndGenerateToken")
    public ResponseEntity<?> authenticateUser(@RequestBody LoginRequest loginRequest)
    if(loginRequest.getUsername().isEmpty()










    share|improve this question























      up vote
      -1
      down vote

      favorite









      up vote
      -1
      down vote

      favorite











      I trying to authenticate and authorize by Spring Security. I am able to authenticate and authorize when I use Postman pulgin. But when I integrate the application with Frontend (i.e angular) the SecurityContextHolder.getContext().getAuthentication() returns null.



      Any help would be great appreciated. I have been trying to do this since past 3-4 weeks. As there are many classes for this configuration, I am not putting all code here. Please let me know what code (apart from below code) you need, so I can get a help from you. Fyi: initially when I was calling /authenticateAndGenerateToken and then call /student, it was not getting the authentication. So I added code to put the authentication in the controller(as shown below). I am using auth0/angular-jwt



      Thanks in advance!!



      JwtAuthenticationFilter.java



      public class JwtAuthenticationFilter extends OncePerRequestFilter 

      @Autowired
      private JwtTokenProvider tokenProvider;

      private static final Logger logger = LoggerFactory.getLogger(JwtAuthenticationFilter.class);

      @Override
      protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException
      String jwt = getJwtFromRequest(request);
      String url = getFullURL(request);
      System.out.println("URL:..............." + url);
      if(jwt == null && !url.contains("api/security/authentication/authenticateAndGenerateToken"))
      jwt = "No Token Provided";

      if (StringUtils.hasText(jwt))
      if(tokenProvider.validateToken(jwt))
      UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
      UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
      authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

      SecurityContextHolder.getContext().setAuthentication(authentication);
      else
      response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Required headers not specified in the request");
      System.out.println("Token Validation Failed.....");


      filterChain.doFilter(request, response);


      private String getJwtFromRequest(HttpServletRequest request)
      String bearerToken = request.getHeader("Authorization");
      if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer "))
      return bearerToken.substring(7, bearerToken.length());

      return null;


      public String getFullURL(HttpServletRequest request)
      StringBuilder requestURL = new StringBuilder(request.getRequestURL().toString());
      String queryString = request.getQueryString();

      if (queryString == null)
      return requestURL.toString();
      else
      return requestURL.append('?').append(queryString).toString();





      AuthenticationController.java



       @RestController
      @RequestMapping("/api/auth")
      @CrossOrigin
      public class AuthController
      @SuppressWarnings( "unchecked", "rawtypes" )
      @PostMapping("/authenticateAndGenerateToken")
      public ResponseEntity<?> authenticateUser(@RequestBody LoginRequest loginRequest)
      if(loginRequest.getUsername().isEmpty()










      share|improve this question













      I trying to authenticate and authorize by Spring Security. I am able to authenticate and authorize when I use Postman pulgin. But when I integrate the application with Frontend (i.e angular) the SecurityContextHolder.getContext().getAuthentication() returns null.



      Any help would be great appreciated. I have been trying to do this since past 3-4 weeks. As there are many classes for this configuration, I am not putting all code here. Please let me know what code (apart from below code) you need, so I can get a help from you. Fyi: initially when I was calling /authenticateAndGenerateToken and then call /student, it was not getting the authentication. So I added code to put the authentication in the controller(as shown below). I am using auth0/angular-jwt



      Thanks in advance!!



      JwtAuthenticationFilter.java



      public class JwtAuthenticationFilter extends OncePerRequestFilter 

      @Autowired
      private JwtTokenProvider tokenProvider;

      private static final Logger logger = LoggerFactory.getLogger(JwtAuthenticationFilter.class);

      @Override
      protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException
      String jwt = getJwtFromRequest(request);
      String url = getFullURL(request);
      System.out.println("URL:..............." + url);
      if(jwt == null && !url.contains("api/security/authentication/authenticateAndGenerateToken"))
      jwt = "No Token Provided";

      if (StringUtils.hasText(jwt))
      if(tokenProvider.validateToken(jwt))
      UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
      UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
      authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

      SecurityContextHolder.getContext().setAuthentication(authentication);
      else
      response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Required headers not specified in the request");
      System.out.println("Token Validation Failed.....");


      filterChain.doFilter(request, response);


      private String getJwtFromRequest(HttpServletRequest request)
      String bearerToken = request.getHeader("Authorization");
      if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer "))
      return bearerToken.substring(7, bearerToken.length());

      return null;


      public String getFullURL(HttpServletRequest request)
      StringBuilder requestURL = new StringBuilder(request.getRequestURL().toString());
      String queryString = request.getQueryString();

      if (queryString == null)
      return requestURL.toString();
      else
      return requestURL.append('?').append(queryString).toString();





      AuthenticationController.java



       @RestController
      @RequestMapping("/api/auth")
      @CrossOrigin
      public class AuthController
      @SuppressWarnings( "unchecked", "rawtypes" )
      @PostMapping("/authenticateAndGenerateToken")
      public ResponseEntity<?> authenticateUser(@RequestBody LoginRequest loginRequest)
      if(loginRequest.getUsername().isEmpty()







      angular spring-boot spring-security angular2-jwt






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 9 at 19:46









      SK.

      248215




      248215



























          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',
          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%2f53232366%2fspring-boot-angular-jwt-not-getting-authentication-from-context%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown






























          active

          oldest

          votes













          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes















           

          draft saved


          draft discarded















































           


          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53232366%2fspring-boot-angular-jwt-not-getting-authentication-from-context%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

          Use pre created SQLite database for Android project in kotlin

          Darth Vader #20

          Ondo