vue+springmvc前后端分离开发(七)(restful接口与postman)

什么是restful接口?

  • restful是一种对接口的风格约束,并非一定要遵守
  • 在restful中
    • 一个URL代表一类资源
    • 用GET、PUT、DELETE、POST来操作资源,url中不包含动作
    • 因为http的无状态,所以客户端在向服务端请求时必须包含需要的全部信息
    • 超媒体即应用状态引擎,在一个资源的内容中可能包含下一个或上一个或者相关资源的url
    • 更多请网上搜索

如何在jpa的基础上添加restful接口?

  • 很简单,我们只需要添加rest repository依赖就可以了
    rest依赖
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
  • 如果你的领域类和repository的创建过程没有任何问题,在这个时候所有基本的接口都已经设置好了,不需要我们写任何一个RestController
  • 为了避免一些不必要的冲突,我们需要将接口的url统一加上api前缀,在application.yaml中进行如下设置(为了避免误会,给出全部代码)
spring:
  profiles:
    active:
    - dev
    
  application:
    name: kmhc
    
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/kmhc?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: Jhr000430@
    
  data:
    rest:
      base-path: /api
    
server:
  port: 9001

向restful接口发送请求

  • 首先我们需要安装postman,以便对接口进行测试(有关postman的使用方法请自行琢磨,很简单)

  • 我们向127.0.0.1:9001/api/users发送一个GET请求来获取全部用户信息
    向users发送GET请求

  • 可以看见因为spring security的原因,GET请求这个资源是未授权的,获取不到资源,下面讲解如何设置spring security对api的权限管理

用spring security管理api

  • 首先进入kmhc.security包,找到SecurityConfig文件,将文件修改成如下形式
package kmhc.security;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

	@Autowired
	private CustomUserDetailsService userDetailsService;
	
	@Autowired
	private DataSource dataSource;	

	
	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		auth
			.userDetailsService(userDetailsService)
			.passwordEncoder(encoder());
		auth
			.jdbcAuthentication()
			.dataSource(dataSource)
			.usersByUsernameQuery(
					"select username, password, enabled from users where username = ?"
					)
			.authoritiesByUsernameQuery(
					"select username, authority from authorities where user_id in (select user_id from users where username = ?)"
					)
			.groupAuthoritiesByUsername(
					"select g.id, g.group_name, ga.authority from user_groups g, group_members gm, group_authorities ga " +
					"where gm.user_id in (select user_id from users where username = ?) and g.id = ga.group_id and g.id = gm.group_id"
					);
		
	}
	
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http
			.csrf().disable()
			.cors()
			.and()
			.authorizeRequests()
			.antMatchers(HttpMethod.POST, "/api/users").permitAll()
			.antMatchers(HttpMethod.GET, "/api/users/{username}").permitAll()
			.antMatchers("/api/users/{username}").authenticated()
			.antMatchers(HttpMethod.GET, "/api/users").hasRole("ADMIN")	
			.antMatchers("/api/authorities/**").hasRole("ADMIN")
			.antMatchers("/api/groups/**").hasRole("ADMIN")
			.antMatchers("/api/groupAuthorities/**").hasRole("ADMIN")
			.and()
			.formLogin().disable()
			.httpBasic()
			.and()
			.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
			
	}
	
	@Bean
	public PasswordEncoder encoder() {
		return new BCryptPasswordEncoder();
	}
}
  • 可以看到其实这个文件相比之前只多了一个重载的configure()方法,这个方法用于管理对api的一些访问权限
  • 对configure(HttpSecurity http)方法进行解析
    • csrf.disable()用于关闭跨站请求伪造,在开发阶段尤其重要,不然发送的post请求都会收到403
    • cors()用于打开跨域,前后端分离时会用到
    • authorizeRequests()包含了对路由的一系列管理,这里的url都会统一加上ip地址
    • antMatchers()规定了一个url的请求权限,可以自由的配置请求方法和用户所必须拥有的权限
    • httpBasic()代表使用Basic Auth认证模式,不使用Session
    • 前后端分离开发中,http是无状态的,所以我们并不需要session
  • 修改好了以后,再次利用postman,这次需要先向接口发送一个post请求创建一个用户
    创建一个用户
  • 可以看到用户创建成功,并且返回了json格式的信息,其中包含了用户的基本信息和_links属性,里面有用户自身url的描述,用户权限url的描述等,符合超媒体即应用状态引擎

密码修改为密文保存

  • 虽然我们成功创建了一个用户,但是可以发现密码(原本)是明文的形式,encoder()组件并没有实际起作用,其实encoder()组件只负责进行密码的匹配,即将前端提交上来的明文和后端密文进行加密匹配
  • 所以我们需要手动对用户的保存过程进行加密,这里利用了rest repository自带的Handler来解决
  • 首先创建一个handler包
    创建handler包
  • 然后创建一个名叫UserEventHandler的类,并在里面写上如下代码
package kmhc.handler;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.rest.core.annotation.HandleBeforeCreate;
import org.springframework.data.rest.core.annotation.RepositoryEventHandler;
import org.springframework.security.crypto.password.PasswordEncoder;

import kmhc.domain.user.User;

@RepositoryEventHandler(User.class)
public class UserEventHandler {

	@Autowired
	private PasswordEncoder passwordEncoder;
	
	@HandleBeforeCreate
	public void handleUserBeforeCreate(User user) {
		user.setPassword(passwordEncoder.encode(user.getPassword()));
	}
}
  • 对上面代码进行解析
    • @RepositoryEventHandler(User.class)表明这是一个针对User的rest repository提供的事件处理器
    • 这里的PasswordEncoder是自动注入的,对应着我们定义的encoder()组件
    • @HandleBeforeCreate和它的名字一样,是在实例保存之前对实例进行处理,这里的操作就是对密码进行一个强加密
  • 写好了Handler以后,我们需要在某个地方使用这个Handler,如果不降它作为一个Bean返回的话是不能够起作用的,所以我们先创建config包,在这里面进行配置
    创建config包
  • 再在这个包中创建一个加了@Configuration的类,在这个类中返回UserEventHandler组件
package kmhc.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import kmhc.handler.UserEventHandler;

@Configuration
public class RepositoryConfig {

	@Bean
	public UserEventHandler userEventHandler() {
		return new UserEventHandler();
	}
}
  • 现在密码加密功能就正式起作用了,我们创建一个admin用户(图片请以自己看到的为准)
    用postman创建admin用户
  • 可以看到密码确实变成密文的形式保存起来了

至此,已经对restful接口规范和编写方式有了初步了解,还讲解了如何用spring security管理api以及如何解决一些容易错的问题,下一节会对rest repository做一个更加全面的讲解

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值