|
| 1 | +package com.myapp.controller; |
| 2 | + |
| 3 | +import com.fasterxml.jackson.databind.ObjectMapper; |
| 4 | +import com.myapp.auth.TokenHandler; |
| 5 | +import com.myapp.dto.UserParams; |
| 6 | +import org.springframework.beans.factory.annotation.Autowired; |
| 7 | +import org.springframework.http.ResponseEntity; |
| 8 | +import org.springframework.security.authentication.AuthenticationManager; |
| 9 | +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; |
| 10 | +import org.springframework.security.core.Authentication; |
| 11 | +import org.springframework.security.core.AuthenticationException; |
| 12 | +import org.springframework.security.core.context.SecurityContextHolder; |
| 13 | +import org.springframework.security.core.userdetails.UserDetails; |
| 14 | +import org.springframework.security.core.userdetails.UserDetailsService; |
| 15 | +import org.springframework.web.bind.annotation.RequestBody; |
| 16 | +import org.springframework.web.bind.annotation.RequestMapping; |
| 17 | +import org.springframework.web.bind.annotation.RequestMethod; |
| 18 | +import org.springframework.web.bind.annotation.RestController; |
| 19 | + |
| 20 | +/** |
| 21 | + * Created by riccardo.causo on 17.10.2016. |
| 22 | + */ |
| 23 | +@RestController |
| 24 | +@RequestMapping("/api/login") |
| 25 | +public class AuthController { |
| 26 | + |
| 27 | + private final AuthenticationManager authenticationManager; |
| 28 | + private final TokenHandler tokenHandler; |
| 29 | + private final UserDetailsService userDetailsService; |
| 30 | + |
| 31 | + @Autowired |
| 32 | + AuthController( |
| 33 | + AuthenticationManager authenticationManager, |
| 34 | + TokenHandler tokenHandler, |
| 35 | + UserDetailsService userDetailsService |
| 36 | + ){ |
| 37 | + |
| 38 | + this.authenticationManager = authenticationManager; |
| 39 | + this.tokenHandler = tokenHandler; |
| 40 | + this.userDetailsService = userDetailsService; |
| 41 | + } |
| 42 | + |
| 43 | + |
| 44 | + @RequestMapping(method = RequestMethod.POST) |
| 45 | + public ResponseEntity<String> authenticationRequest(@RequestBody UserParams params) throws AuthenticationException { |
| 46 | + |
| 47 | + UsernamePasswordAuthenticationToken loginToken = params.toAuthenticationToken(); |
| 48 | + Authentication authentication = authenticationManager.authenticate(loginToken); |
| 49 | + |
| 50 | + SecurityContextHolder.getContext().setAuthentication(authentication); |
| 51 | + |
| 52 | + UserDetails userDetails = userDetailsService.loadUserByUsername(params.getEmail().get()); |
| 53 | + |
| 54 | + String token = tokenHandler.createTokenForUser(userDetails); |
| 55 | + |
| 56 | + // Return the token |
| 57 | + return ResponseEntity.ok().header("x-auth-token",token).body(""); |
| 58 | + } |
| 59 | + |
| 60 | + |
| 61 | +} |
0 commit comments