Skip to content

Instantly share code, notes, and snippets.

@rasheedamir
Created April 20, 2017 21:20
Show Gist options
  • Select an option

  • Save rasheedamir/908792e8490abf138260b13361cfd447 to your computer and use it in GitHub Desktop.

Select an option

Save rasheedamir/908792e8490abf138260b13361cfd447 to your computer and use it in GitHub Desktop.
package io.github.jhipster.sample.web.rest;
import io.github.jhipster.sample.security.jwt.JWTConfigurer;
import io.github.jhipster.sample.security.jwt.TokenProvider;
import io.github.jhipster.sample.web.rest.vm.LoginVM;
import java.util.Collections;
import com.codahale.metrics.annotation.Timed;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import javax.inject.Inject;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
@RestController
@RequestMapping("/api")
public class UserJWTController
{
@Inject
private TokenProvider tokenProvider;
@Inject
private AuthenticationManager authenticationManager;
@PostMapping("/authenticate")
@Timed
public ResponseEntity<?> authorize(@Valid @RequestBody LoginVM loginVM, HttpServletResponse response)
{
UsernamePasswordAuthenticationToken authenticationToken =
new UsernamePasswordAuthenticationToken(loginVM.getUsername(), loginVM.getPassword());
try
{
Authentication authentication = this.authenticationManager.authenticate(authenticationToken);
SecurityContextHolder.getContext().setAuthentication(authentication);
boolean rememberMe = (loginVM.isRememberMe() == null) ? false : loginVM.isRememberMe();
String jwt = tokenProvider.createToken(authentication, rememberMe);
response.addHeader(JWTConfigurer.AUTHORIZATION_HEADER, "Bearer " + jwt);
return ResponseEntity.ok(new JWTToken(jwt));
}
catch (AuthenticationException exception)
{
return new ResponseEntity<>(Collections.singletonMap("AuthenticationException",exception.getLocalizedMessage()), HttpStatus.UNAUTHORIZED);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment