使用SpringSecurity进行权限控制需要完成以下几个步骤:
在项目的pom.xml文件中添加SpringSecurity的依赖,如下所示:
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>5.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>5.2.2.RELEASE</version>
</dependency>
在Spring的配置文件中添加SpringSecurity的配置,如下所示:
<http>
<intercept-url pattern="/admin/**" access="ROLE_ADMIN" />
<intercept-url pattern="/user/**" access="ROLE_ADMIN,ROLE_USER" />
<form-login login-page="/login" default-target-url="/index" />
<logout logout-success-url="/login" />
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="admin" password="admin" authorities="ROLE_ADMIN" />
<user name="user" password="user" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager>
其中,intercept-url
标签用于配置URL的访问权限,form-login
标签用于配置登录页和默认跳转页,logout
标签用于配置退出登录的跳转页,authentication-provider
标签用于配置用户的认证信息。
在Controller中添加SpringSecurity的注解,如下所示:
@RestController
@RequestMapping("/user")
@PreAuthorize("hasRole('ROLE_USER')")
public class UserController {
@GetMapping("/info")
public String getInfo() {
return "User info";
}
}
其中,@PreAuthorize
注解用于配置方法的访问权限。
通过以上三个步骤,就可以使用SpringSecurity进行权限控制了。关键词包括:SpringSecurity、权限控制、依赖、配置、注解、控制器、拦截URL、认证、角色权限、登录、退出、高亮颜色。