+/*
+ * Copyright 2020 Huawei Technologies Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.eliot.eliotbe.eliotk8sclient.controller;
+
+import java.util.Objects;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.ResponseEntity;
+import org.springframework.security.authentication.AuthenticationManager;
+import org.springframework.security.authentication.BadCredentialsException;
+import org.springframework.security.authentication.DisabledException;
+import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
+import org.springframework.security.core.userdetails.UserDetails;
+import org.springframework.web.bind.annotation.CrossOrigin;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RestController;
+import com.eliot.eliotbe.eliotk8sclient.service.JwtUserDetailsService;
+
+
+import com.eliot.eliotbe.eliotk8sclient.util.JwtTokenUtil;
+import com.eliot.eliotbe.eliotk8sclient.model.jwt.JwtRequest;
+import com.eliot.eliotbe.eliotk8sclient.model.jwt.JwtResponse;
+
+@RestController
+@CrossOrigin
+public class AuthenticationController {
+
+ @Autowired
+ private AuthenticationManager authenticationManager;
+
+ @Autowired
+ private JwtTokenUtil jwtTokenUtil;
+
+ @Autowired
+ private JwtUserDetailsService userDetailsService;
+
+ @RequestMapping(value = "/authenticate", method = RequestMethod.POST)
+ public ResponseEntity<JwtResponse> createAuthenticationToken(@RequestBody JwtRequest authenticationRequest) throws Exception {
+
+ authenticate(authenticationRequest.getUsername(), authenticationRequest.getPassword());
+
+ final UserDetails userDetails = userDetailsService
+ .loadUserByUsername(authenticationRequest.getUsername());
+
+ final String token = jwtTokenUtil.generateToken(userDetails);
+
+ return ResponseEntity.ok(new JwtResponse(token));
+ }
+
+ private void authenticate(String username, String password) throws Exception {
+ try {
+ authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
+ } catch (DisabledException e) {
+ throw new Exception("USER_DISABLED", e);
+ } catch (BadCredentialsException e) {
+ throw new Exception("INVALID_CREDENTIALS", e);
+ }
+ }
+}
\ No newline at end of file