springboot实现登录接口并且返回token给前端使用
时间: 2024-03-26 19:42:25 浏览: 53
好的,您可以参考以下步骤实现:
1. 添加依赖:
在 `pom.xml` 文件中添加以下依赖:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
```
2. 配置 Security:
新建一个继承 `WebSecurityConfigurerAdapter` 的类,并且重写其中的方法:
```
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests()
.antMatchers(HttpMethod.POST, "/login").permitAll()
.anyRequest().authenticated()
.and().addFilter(new JWTAuthenticationFilter(authenticationManager()))
.addFilter(new JWTAuthorizationFilter(authenticationManager()));
}
}
```
3. 创建 User 实体类:
创建一个 User 实体类,用于存储用户信息。
```
@Entity
@Table(name = "users")
public class User implements UserDetails {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
private String password;
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return Collections.emptyList();
}
@Override
public String getPassword() {
return password;
}
@Override
public String getUsername() {
return username;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
}
```
4. 创建 UserDetailsService 实现类:
创建一个 UserDetailsService 实现类,用于从数据库中获取用户信息。
```
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
private UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userRepository.findByUsername(username);
if (user == null) {
throw new UsernameNotFoundException(username);
}
return user;
}
}
```
5. 创建 UserRepository 接口:
创建一个 UserRepository 接口,用于操作数据库。
```
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
User findByUsername(String username);
}
```
6. 创建 JWTAuthenticationFilter 和 JWTAuthorizationFilter:
创建 JWTAuthenticationFilter 和 JWTAuthorizationFilter,用于实现 JWT 认证和授权功能。
JWTAuthenticationFilter:
```
public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
private AuthenticationManager authenticationManager;
public JWTAuthenticationFilter(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
setFilterProcessesUrl("/login");
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
try {
User user = new ObjectMapper().readValue(request.getInputStream(), User.class);
return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword()));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
```
JWTAuthorizationFilter:
```
public class JWTAuthorizationFilter extends BasicAuthenticationFilter {
public JWTAuthorizationFilter(AuthenticationManager authenticationManager) {
super(authenticationManager);
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
String header = request.getHeader("Authorization");
if (header == null || !header.startsWith("Bearer ")) {
chain.doFilter(request, response);
return;
}
UsernamePasswordAuthenticationToken authentication = getAuthentication(request);
SecurityContextHolder.getContext().setAuthentication(authentication);
chain.doFilter(request, response);
}
private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
String token = request.getHeader("Authorization");
if (token != null) {
String user = Jwts.parser()
.setSigningKey("secret".getBytes())
.parseClaimsJws(token.replace("Bearer ", ""))
.getBody()
.getSubject();
if (user != null) {
return new UsernamePasswordAuthenticationToken(user, null, Collections.emptyList());
}
return null;
}
return null;
}
}
```
7. 创建 TokenController:
创建一个 TokenController,用于实现登录接口。
```
@RestController
public class TokenController {
@PostMapping("/login")
public ResponseEntity<?> login(@RequestBody User user) {
try {
Authentication authentication = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());
authentication = new JWTAuthenticationFilter(authenticationManager()).attemptAuthentication(new HttpServletRequestWrapper(null) {
@Override
public String getHeader(String name) {
return "Bearer " + Jwts.builder()
.setSubject(user.getUsername())
.setExpiration(new Date(System.currentTimeMillis() + 86400000))
.signWith(SignatureAlgorithm.HS512, "secret".getBytes())
.compact();
}
}, new HttpServletResponseWrapper(null));
SecurityContextHolder.getContext().setAuthentication(authentication);
return ResponseEntity.ok().header("Authorization", authentication.getCredentials().toString()).build();
} catch (AuthenticationException e) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
}
}
}
```
至此,就完成了一个简单的登录接口并且返回 token 的实现。当用户发送 POST 请求到 `/login` 接口时,若用户名和密码正确,则会返回一个包含 token 的响应头。
阅读全文