SpringBoot+Spring Security+JWT实现实现RESTful Api权限控制的方法权限控制的方法
主要介绍了SpringBoot+Spring Security+JWT实现RESTful Api权限控制的方法,文中通过示例代码介绍的非常详细,对大家的学习或
者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
摘要:用spring-boot开发RESTful API非常的方便,在生产环境中,对发布的API增加授权保护是非常必要的。现在我们来看如何利用JWT技术为API增
加授权保护,保证只有获得授权的用户才能够访问API。
一:开发一个简单的一:开发一个简单的API
在IDEA开发工具中新建一个maven工程,添加对应的依赖如下:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- spring-data-jpa -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.30</version>
</dependency>
<!-- spring-security 和 jwt -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.7.0</version>
</dependency>
新建一个UserController.java文件,在里面在中增加一个hello方法:
@RequestMapping("/hello")
@ResponseBody
public String hello(){
return "hello";
}
这样一个简单的RESTful API就开发好了。
现在我们运行一下程序看看效果,执行JwtauthApplication.java类中的main方法:
等待程序启动完成后,可以简单的通过curl工具进行API的调用,如下图:
评论0