超全的springboot+springsecurity实现前后端分离简单实现!
点击上方蓝色字体,选择“标星公众号”
优质文章,第一时间送达
1、前言部分
1.1、唠嗑部分(如何学习?)
1.2、技术支持
1.3、预期实现效果图
2、核心部分
2.1、springsecurity原理解释:
2.2、踩坑集锦
访问/login时必须要用post方法!, 访问的参数名必须为username和password
访问/logout时即可用post也可用get方法!
//springsecurity配置文件中的hasRole("")不能以ROLE开头,比如ROLE_USER就是错的,springsecurity会默认帮我们加上,但数据库的权限字段必须是ROLE_开头,否则读取不到
2.3、代码部分
com.google.code.gson
gson
2.8.2
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-security
mysql
mysql-connector-java
runtime
org.projectlombok
lombok
true
com.baomidou
mybatis-plus-boot-starter
3.4.1
org.springframework.boot
spring-boot-starter-test
test
org.junit.vintage
junit-vintage-engine
org.springframework.security
spring-security-config
5.3.4.RELEASE
org.springframework.security
spring-security-web
5.3.4.RELEASE
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Msg {
int code; //错误码
String Message; //消息提示
Mapdata=new HashMap (); //数据
//无权访问
public static Msg denyAccess(String message){
Msg result=new Msg();
result.setCode(300);
result.setMessage(message);
return result;
}
//操作成功
public static Msg success(String message){
Msg result=new Msg();
result.setCode(200);
result.setMessage(message);
return result;
}
//客户端操作失败
public static Msg fail(String message){
Msg result=new Msg();
result.setCode(400);
result.setMessage(message);
return result;
}
public Msg add(String key,Object value){
this.data.put(key,value);
return this;
}
}
@Data
public class User implements Serializable {
private Integer id;
private String account;
private String password;
private String role;
}
@Repository
public interface UserMapper extends BaseMapper{
}
public interface UserService{
}
@Service
public class UserServiceImpl extends ServiceImplimplements UserService,UserDetailsService {
@Autowired
UserMapper userMapper;
//加载用户
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
//mybatis-plus帮我们写好了sql语句,相当于 select * from user where account ='${account}'
QueryWrapperwrapper=new QueryWrapper<>();
wrapper.eq("account",s);
User user=userMapper.selectOne(wrapper); //user即为查询结果
if(user==null){
throw new UsernameNotFoundException("用户名错误!!");
}
//获取用户权限,并把其添加到GrantedAuthority中
ListgrantedAuthorities=new ArrayList<>();
GrantedAuthority grantedAuthority=new SimpleGrantedAuthority(user.getRole());
grantedAuthorities.add(grantedAuthority);
//方法的返回值要求返回UserDetails这个数据类型, UserDetails是接口,找它的实现类就好了
//new org.springframework.security.core.userdetails.User(String username,String password,Collection extends GrantedAuthority> authorities) 就是它的实现类
return new org.springframework.security.core.userdetails.User(s,user.getPassword(),grantedAuthorities);
}
}
@RestController
public class UserController {
@GetMapping("index")
public String index(){
return "index";
}
@GetMapping("hello")
public String hello(){
return "hello";
}
}
@Component
public class AuthenticationEnryPoint implements AuthenticationEntryPoint {
@Autowired
Gson gson;
//未登录时返回给前端数据
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
Msg result=Msg.fail("需要登录!!");
response.setContentType("application/json;charset=utf-8");
response.getWriter().write(gson.toJson(result));
}
}
//登录失败返回给前端消息
@Component
public class AuthenticationFailure implements AuthenticationFailureHandler{
@Autowired
Gson gson;
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
Msg msg=null;
if(e instanceof UsernameNotFoundException){
msg=Msg.fail(e.getMessage());
}else if(e instanceof BadCredentialsException){
msg=Msg.fail("密码错误!!");
}else {
msg=Msg.fail(e.getMessage());
}
//处理编码方式,防止中文乱码的情况
response.setContentType("text/json;charset=utf-8");
//返回给前台
response.getWriter().write(gson.toJson(msg));
}
}
@Component
public class AuthenticationSuccess implements AuthenticationSuccessHandler{
@Autowired
Gson gson;
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
//登录成功时返回给前端的数据
Msg result=Msg.success("登录成功!!!!!");
response.setContentType("application/json;charset=utf-8");
response.getWriter().write(gson.toJson(result));
}
}
@Component
public class AuthenticationLogout implements LogoutSuccessHandler{
@Autowired
Gson gson;
@Override
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
Msg result=Msg.success("注销成功");
response.setContentType("application/json;charset=utf-8");
response.getWriter().write(gson.toJson(result));
}
}
//无权访问
@Component
public class AccessDeny implements AccessDeniedHandler{
@Autowired
Gson gson;
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {
Msg result= Msg.denyAccess("无权访问,need Authorities!!");
response.setContentType("application/json;charset=utf-8");
response.getWriter().write(gson.toJson(result));
}
}
@Component
public class SessionInformationExpiredStrategy implements org.springframework.security.web.session.SessionInformationExpiredStrategy{
@Autowired
Gson gson;
@Override
public void onExpiredSessionDetected(SessionInformationExpiredEvent event) throws IOException, ServletException {
Msg result= Msg.fail("您的账号在异地登录,建议修改密码");
HttpServletResponse response=event.getResponse();
response.setContentType("application/json;charset=utf-8");
response.getWriter().write(gson.toJson(result));
}
}
@Component
public class SelfAuthenticationProvider implements AuthenticationProvider{
@Autowired
UserServiceImpl userServiceImpl;
@Autowired
BCryptPasswordEncoder bCryptPasswordEncoder;
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String account= authentication.getName(); //获取用户名
String password= (String) authentication.getCredentials(); //获取密码
UserDetails userDetails= userServiceImpl.loadUserByUsername(account);
boolean checkPassword= bCryptPasswordEncoder.matches(password,userDetails.getPassword());
if(!checkPassword){
throw new BadCredentialsException("密码不正确,请重新登录!");
}
return new UsernamePasswordAuthenticationToken(account,password,userDetails.getAuthorities());
}
@Override
public boolean supports(Class> aClass) {
return true;
}
}
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true) //开启权限注解,默认是关闭的
public class SpringsecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
AuthenticationEnryPoint authenticationEnryPoint; //未登录
@Autowired
AuthenticationSuccess authenticationSuccess; //登录成功
@Autowired
AuthenticationFailure authenticationFailure; //登录失败
@Autowired
AuthenticationLogout authenticationLogout; //注销
@Autowired
AccessDeny accessDeny; //无权访问
@Autowired
SessionInformationExpiredStrategy sessionInformationExpiredStrategy; //检测异地登录
@Autowired
SelfAuthenticationProvider selfAuthenticationProvider; //自定义认证逻辑处理
@Bean
public UserDetailsService userDetailsService() {
return new UserServiceImpl();
}
//加密方式
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
//认证
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(selfAuthenticationProvider);
}
//授权
@Override
protected void configure(HttpSecurity http) throws Exception {
//cors()解决跨域问题,csrf()会与restful风格冲突,默认springsecurity是开启的,所以要disable()关闭一下
http.cors().and().csrf().disable();
// /index需要权限为ROLE_USER才能访问 /hello需要权限为ROLE_ADMIN才能访问
http.authorizeRequests()
.antMatchers("/index").hasRole("USER")
.antMatchers("/hello").hasRole("ADMIN")
.and()
.formLogin() //开启登录
.permitAll() //允许所有人访问
.successHandler(authenticationSuccess) // 登录成功逻辑处理
.failureHandler(authenticationFailure) // 登录失败逻辑处理
.and()
.logout() //开启注销
.permitAll() //允许所有人访问
.logoutSuccessHandler(authenticationLogout) //注销逻辑处理
.deleteCookies("JSESSIONID") //删除cookie
.and().exceptionHandling()
.accessDeniedHandler(accessDeny) //权限不足的时候的逻辑处理
.authenticationEntryPoint(authenticationEnryPoint) //未登录是的逻辑处理
.and()
.sessionManagement()
.maximumSessions(1) //最多只能一个用户登录一个账号
.expiredSessionStrategy(sessionInformationExpiredStrategy) //异地登录的逻辑处理
;
}
}
server:
port: 80
spring:
datasource:
url: jdbc:mysql://localhost:3306/springsecurity_test?characterEncoding=utf8&serverTimezone=UTC
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:
https://blog.csdn.net/weixin_42375707/article/details/110678638
粉丝福利:Java从入门到入土学习路线图
???
?长按上方微信二维码 2 秒
感谢点赞支持下哈
评论