2 * Copyright 2020 Huawei Technologies Co., Ltd.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 package com.eliot.eliotbe.eliotk8sclient.controller;
18 import java.util.Objects;
20 import org.springframework.beans.factory.annotation.Autowired;
21 import org.springframework.http.ResponseEntity;
22 import org.springframework.security.authentication.AuthenticationManager;
23 import org.springframework.security.authentication.BadCredentialsException;
24 import org.springframework.security.authentication.DisabledException;
25 import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
26 import org.springframework.security.core.userdetails.UserDetails;
27 import org.springframework.web.bind.annotation.CrossOrigin;
28 import org.springframework.web.bind.annotation.RequestBody;
29 import org.springframework.web.bind.annotation.RequestMapping;
30 import org.springframework.web.bind.annotation.RequestMethod;
31 import org.springframework.web.bind.annotation.RestController;
32 import com.eliot.eliotbe.eliotk8sclient.service.JwtUserDetailsService;
35 import com.eliot.eliotbe.eliotk8sclient.util.JwtTokenUtil;
36 import com.eliot.eliotbe.eliotk8sclient.model.jwt.JwtRequest;
37 import com.eliot.eliotbe.eliotk8sclient.model.jwt.JwtResponse;
41 public class AuthenticationController {
44 private AuthenticationManager authenticationManager;
47 private JwtTokenUtil jwtTokenUtil;
50 private JwtUserDetailsService userDetailsService;
52 @RequestMapping(value = "/authenticate", method = RequestMethod.POST)
53 public ResponseEntity<JwtResponse> createAuthenticationToken(@RequestBody JwtRequest authenticationRequest) throws Exception {
55 authenticate(authenticationRequest.getUsername(), authenticationRequest.getPassword());
57 final UserDetails userDetails = userDetailsService
58 .loadUserByUsername(authenticationRequest.getUsername());
60 final String token = jwtTokenUtil.generateToken(userDetails);
62 return ResponseEntity.ok(new JwtResponse(token));
65 private void authenticate(String username, String password) throws Exception {
67 authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
68 } catch (DisabledException e) {
69 throw new Exception("USER_DISABLED", e);
70 } catch (BadCredentialsException e) {
71 throw new Exception("INVALID_CREDENTIALS", e);