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()
angular spring-boot spring-security angular2-jwt
add a comment |
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()
angular spring-boot spring-security angular2-jwt
add a comment |
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()
angular spring-boot spring-security angular2-jwt
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
angular spring-boot spring-security angular2-jwt
asked Nov 9 at 19:46
SK.
248215
248215
add a comment |
add a comment |
active
oldest
votes
active
oldest
votes
active
oldest
votes
active
oldest
votes
active
oldest
votes
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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