一旦我们在Keycloak服务器中注册了客户端并设置了具有角色的各个用户帐户,我们就可以开始探索如何使用Spring Security和Keycloak Spring Boot适配器来保护资源。
将Spring Security和Keycloak 的JAR包添加到要保护的服务中
<dependencies>
<!-- OAuth2 Client dependency -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-oauth2-client</artifactId>
</dependency>
<!-- OAuth2 Client dependency -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
</dependencies>
spring:
security:
oauth2:
client:
registration:
login-client:
provider: keycloak
client-id: learning
client-secret: "BMF0NGhYC9Gk4nsjOXTiFc56rnPzHcuY"
authorization-grant-type: authorization_code
scope: openid,profile,roles,email
provider:
keycloak:
issuer-uri: "http://192.168.10.110:8073/realms/learning-realm"
@Override
protected void configure(HttpSecurity http)
throws Exception {
super.configure(http);
http.authorizeRequests()
.anyRequest().authenticated();
}
所有访问规则都在configure()方法内定义。我们将使用Spring传入的HttpSecurity类来定义我们的规则。在本例中,我们将限制对 organization 服务中的任何URL的访问,仅允许经过身份认证的用户。
@RestController
@RequestMapping(value="v1/organization")
public class OrganizationController {
@Autowired
private OrganizationService service;
@RolesAllowed({ "ADMIN", "USER" })
@RequestMapping(value="/{organizationId}",method = RequestMethod.GET)
public ResponseEntity<Organization> getOrganization(
@PathVariable("organizationId") String organizationId) {
return ResponseEntity.ok(service.findById(organizationId));
}
@RolesAllowed({ "ADMIN", "USER" })
@RequestMapping(value="/{organizationId}",method = RequestMethod.PUT)
public void updateOrganization( @PathVariable("organizationId")
String id, @RequestBody Organization organization) {
service.update(organization);
}
@RolesAllowed({ "ADMIN", "USER" })
@PostMapping
public ResponseEntity<Organization> saveOrganization(
@RequestBody Organization organization) {
return ResponseEntity.ok(service.create(organization));
}
@RolesAllowed("ADMIN")
@DeleteMapping(value="/{organizationId}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void deleteLicense(@PathVariable("organizationId")
String organizationId) {
service.delete(organizationId);
}
}