[英]How to retrieve JWT token from back-end (Java Spring Boot) in my react.js front-end?
[英]How to connect authentication system with spring boot jwt to React.js
我使用 JAVA 和 spring 創建了一個在服務器端編寫的全棧系統,並使用 react.js 創建了一個客戶端我創建了一個 JWT 系統以連接系統。 該系統在服務器端工作,我想將它統一到適當的組件中由於某種原因沒有任何作用,重要的是要強調我對 react.js 是全新的,這是我用 react.js 創建的第一個項目
這是 login.jsx 組件:
import React, { Component } from 'react'
import AuthService from '../services/AuthService';
import "./Login.css";
class login extends Component{
constructor(props){
super(props);
this.state={
username: '',
password: '',
}
this.signin = this.signin.bind(this);
}
signin(){
let loginRequest = {username: this.state.username, password: this.state.password};
AuthService.signin(loginRequest).then(res=>{
this.props.history.push('/home');
});
console.log('employee => ' + JSON.stringify(loginRequest));
}
changeUserNameHandler= (event) => {
this.setState({username: event.target.value});
}
changePasswordHandler= (event) => {
this.setState({password: event.target.value});
}
render() {
return (
<section className="container">
<div className="row">
<div className="col-md-6">
<div className="card">
<form className="box">
<h1>Login</h1>
<p className="text-muted"> Please enter your User Name and Password!</p>
<input onChange={this.changeUsertNameHandler} autoComplete="off" type="text" name="username" placeholder="Username"/>
<input onChange={this.changePasswordHandler} autoComplete="off" type="password" name="password" placeholder="Password"/>
<a className="forgot text-muted" href="#">Forgot password?</a>
<input onClick={this.signin} type="submit" name="" value="Login" href="#"/>
<div className="col-md-12">
<ul className="social-network social-circle">
<li><a href="#" className="icoFacebook" title="Facebook"><i className="fab fa-facebook-f"></i></a></li>
<li><a href="#" className="icoGoogle" title="Google +"><i className="fab fa-google-plus"></i></a></li>
</ul>
</div>
<div className="form-group">
<div className="custom-control custom-checkbox">
</div>
</div>
</form>
</div>
</div>
</div>
</section>
);
}
}
export default login;
這是AuthController(java spring):
package com.example.coffeedemo.Controller;
import com.example.coffeedemo.model.ERole;
import com.example.coffeedemo.model.Role;
import com.example.coffeedemo.model.User;
import com.example.coffeedemo.repository.RoleRepository;
import com.example.coffeedemo.repository.UserRepository;
import com.example.coffeedemo.requests.LoginRequest;
import com.example.coffeedemo.requests.SignupRequest;
import com.example.coffeedemo.response.JwtResponse;
import com.example.coffeedemo.response.MessageResponse;
import com.example.coffeedemo.security.JwtUtils;
import com.example.coffeedemo.service.UserDetailsImpl;
import org.springframework.beans.factory.annotation.Autowired;
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.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/api/")
public class AuthController {
@Autowired
AuthenticationManager authenticationManager;
@Autowired
UserRepository userRepository;
@Autowired
RoleRepository roleRepository;
@Autowired
PasswordEncoder encoder;
@Autowired
JwtUtils jwtUtils;
@PostMapping("/signin")
public ResponseEntity<?> authenticateUser(@RequestBody LoginRequest loginRequest) {
System.out.println(userRepository.findByUsername(loginRequest.getUsername()));
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));
}
@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();
System.out.println(strRoles);
Set<Role> roles = new HashSet<>();
if (strRoles == null) {
Role userRole = roleRepository.findByName(ERole.ROLE_USER)
.orElseThrow(() -> new RuntimeException("Error: Role is not found."));
roles.add(userRole);
} else {
strRoles.forEach(role -> {
switch (role) {
case "admin":
Role adminRole = roleRepository.findByName(ERole.ROLE_ADMIN)
.orElseThrow(() -> new RuntimeException("Error: Role is not found."));
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);
}
});
}
user.setRoles(roles);
userRepository.save(user);
return ResponseEntity.ok(new MessageResponse("User registered successfully!"));
}
}
在當前情況下,當我嘗試連接時沒有任何反應..甚至打印到 console.log..
非常感謝幫助謝謝!!
將您的input
更改為普通的<button onClick={this.signin}>Login</button>
。
編輯,如果沒有幫助,請向我們展示您的AuthService.signin
function
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.