前后端分离下保持状态是个问题,但是我这里不涉及分布式,所以用不上JWT,JWT根据项目情况来决定是否使用.
Authentication对象会记录用户的状态,所以不用定义一个token,从Authentication中
getAuthorities方法获取用户的状态
- 如果使用JWT来保持状态的话,就在拦截器上对token进行解码判断就行
springboot-security maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
先贴上Model代码:
package com.jlau.schoollocationsystem.model;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* Created by cxr1205628673 on 2020/3/16.
*/
@Document("user")
public class OrdinaryUser extends User implements UserDetails,Serializable{
//User要继承 UserDetails接口,实现是否可用、上锁、getAuthorties等方法
@Id
private String id;
private String username;
private String password;
private List<Role> roles;
public List<Role> getRoles() {
return roles;
}
public void setRoles(List<Role> roles) {
this.roles = roles;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
List<SimpleGrantedAuthority> auth = new ArrayList<>();
for (Role role:roles) {
auth.add(new SimpleGrantedAuthority(role.getName()));
}
return auth;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
@Entity
@Table(name = "role")
public class Role implements GrantedAuthority{
//Role类需要实现GrantedAuthority接口,让security判断是否有权限
@Id
@Column
@GeneratedValue
private Integer id;
@Column
private String name;
@JsonIgnore
@ManyToMany(mappedBy = "roles")
List<User> users;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String getAuthority() {
return name;
}
}
下面是websecurityconfig代码继承adaptor...
package com.jlau.schoollocationsystem.configuration;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jlau.schoollocationsystem.service.UserService;
import com.jlau.schoollocationsystem.utils.ResponseMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.co