我正在尝试使用springboot验证从google的oauth请求中检索到的令牌。spring应用程序正确地重定向并返回一个令牌。但我想用这个令牌登录?如果令牌在axios上作为post请求的头传递,那么如何在spring中对令牌进行身份验证并为用户签名?令牌作为查询参数传递,我在前端访问vue中的令牌。我想对控制器中的signin方法执行post请求,但我不确定如何根据jwt验证令牌?
import User from '../models/user';
import {GOOGLE_AUTH_URL, FACEBOOK_AUTH_URL} from '../services/app.constants.js';
import TokenStorageService from '../services/token-storage.service.js';
//import AuthService from '../services/auth.service.js';
//import UserService from '../services/user.service.js';
import { API_BASE_URL } from '../services/app.constants.js';
import axios from 'axios';
export default {
name: 'Login',
data() {
return {
user: new User('', '', ''),
loading: false,
message: '',
googleURL: '',
facebookURL: '',
isLoggedIn: false,
isLoginFailed: false,
errorMessage: '',
currentUser: null,
};
},
computed: {
loggedIn() {
return this.$store.state.auth.status.loggedIn;
}
},
created() {
const token = this.$route.query.token;
console.log(token);
//const error = this.$route.query.error;
if(token){
axios.post(API_BASE_URL + 'api/auth/signin', {headers: { "accessToken" : token}})
}
this.googleURL = GOOGLE_AUTH_URL;
this.facebookURL = FACEBOOK_AUTH_URL;
if (this.loggedIn) {
this.$router.push('/profile/account');
}
},
methods: {
handleLogin() {
this.loading = true;
if (this.user.email && this.user.password) {
this.$store.dispatch('auth/login', this.user).then(
() => {
this.$router.push('/profile/account');
},
error => {
this.loading = false;
this.message =
(error.response && error.response.data && error.response.data.message) ||
error.message ||
error.toString();
}
);
}
},
login(user) {
TokenStorageService.saveUser(user);
this.isLoginFailed = false;
this.isLoggedIn = true;
this.currentUser = TokenStorageService.getUser();
window.location.reload();
},
}
};
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/api/auth")
public class AuthController {
@Autowired
AuthenticationManager authenticationManager;
@Autowired
UserService userService;
@Autowired
UserRepository userRepository;
@Autowired
RoleRepository roleRepository;
@Autowired
PasswordEncoder encoder;
@Autowired
JwtUtils jwtUtils;
@Autowired
TokenProvider tokenProvider;
@PostMapping("/signin")
public ResponseEntity<?> authenticateUser(@RequestBody LoginRequest loginRequest, Authentication auth) {
// System.out.println(loginRequest.getUsername());
// System.out.println(loginRequest.getPassword());
// Authentication authentication = authenticationManager.authenticate(
// new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()));
//
// SecurityContextHolder.getContext().setAuthentication(authentication);
// String jwt = jwtUtils.generateJwtToken(authentication);
//
// UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
// List<String> roles = userDetails.getAuthorities().stream()
// .map(item -> item.getAuthority())
// .collect(Collectors.toList());
//
// return ResponseEntity.ok(new JwtResponse(jwt,
// userDetails.getId(),
// userDetails.getUsername(),
// userDetails.getEmail(),
// roles));
if(auth.getCredentials() != null) {
System.out.println(auth.getName());
return ResponseEntity.ok("Ok");
} else {
System.out.println(loginRequest.getEmail() + " " + loginRequest.getPassword());
Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginRequest.getEmail(), loginRequest.getPassword()));
SecurityContextHolder.getContext().setAuthentication(authentication);
String jwt = tokenProvider.createToken(authentication);
LocalUser localUser = (LocalUser) authentication.getPrincipal();
return ResponseEntity.ok(new JwtAuthenticationResponse(jwt, GeneralUtils.buildUserInfo(localUser)));
}
}
@PostMapping("/signup")
public ResponseEntity<?> registerUser(@RequestBody SignUpRequest signUpRequest) {
// if (userRepository.existsByUsername(signUpRequest.getUsername())) {
// return ResponseEntity
// .badRequest()
// .body(new MessageResponse("Error: Username is already taken!"));
// }
//
// if (userRepository.existsByEmail(signUpRequest.getEmail())) {
// return ResponseEntity
// .badRequest()
// .body(new MessageResponse("Error: Email is already in use!"));
// }
//
// // Create new user's account
// User user = new User(signUpRequest.getUsername(),
// signUpRequest.getEmail(),
// encoder.encode(signUpRequest.getPassword()));
//
// Set<String> strRoles = signUpRequest.getRole();
// Set<Role> roles = new HashSet<>();
//
// if (strRoles == null) {
// Role userRole = roleRepository.findByName("ROLE_USER");
// roles.add(userRole);
// } else {
// strRoles.forEach(role -> {
// switch (role) {
// case "admin":
// Role adminRole = roleRepository.findByName("ROLE_ADMIN");
// roles.add(adminRole);
// break;
// case "mod":
// Role modRole = roleRepository.findByName(ERole.ROLE_MODERATOR)
// .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
// roles.add(modRole);
//
// break;
// default:
// Role userRole = roleRepository.findByName(ERole.ROLE_USER)
// .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
// roles.add(userRole);
// }
// });
// }
// Date now = new Date();
// user.setCreatedDate(now);
// user.setRoles(roles);
// userRepository.save(user);
try {
userService.registerNewUser(signUpRequest);
} catch (UserAlreadyExistAuthenticationException e) {
return new ResponseEntity<>(new ApiResponse(false, "Email Address already in use!"), HttpStatus.BAD_REQUEST);
}
return ResponseEntity.ok().body(new ApiResponse(true, "User registered successfully"));
//return ResponseEntity.ok(new MessageResponse("User registered successfully!"));
}
}
暂无答案!
目前还没有任何答案,快来回答吧!