springboot 集成keycloak完成基于角色的权限认证
时间: 2023-10-19 18:29:27 浏览: 136
SpringBoot整合Shiro的代码详解
Spring Boot 集成 Keycloak 可以实现基于角色的权限认证。下面是一个简单的步骤:
1. 在 pom.xml 文件中添加 Keycloak 依赖:
```xml
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-spring-boot-starter</artifactId>
<version>${keycloak.version}</version>
</dependency>
```
2. 在 application.properties 文件中添加 Keycloak 配置:
```properties
keycloak.realm=your-realm
keycloak.auth-server-url=http://localhost:8080/auth
keycloak.ssl-required=external
keycloak.resource=your-client-id
keycloak.credentials.secret=your-client-secret
keycloak.use-resource-role-mappings=true
```
3. 创建一个 Keycloak 配置类:
```java
@Configuration
@EnableWebSecurity
@ComponentScan(basePackageClasses = KeycloakSecurityComponents.class)
public class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
KeycloakAuthenticationProvider keycloakAuthenticationProvider = keycloakAuthenticationProvider();
keycloakAuthenticationProvider.setGrantedAuthoritiesMapper(new SimpleAuthorityMapper());
auth.authenticationProvider(keycloakAuthenticationProvider);
}
@Bean
public KeycloakSpringBootConfigResolver keycloakConfigResolver() {
return new KeycloakSpringBootConfigResolver();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
http.authorizeRequests()
.antMatchers("/admin/**").hasRole("admin")
.anyRequest().permitAll();
}
}
```
4. 创建一个 Controller:
```java
@RestController
public class HomeController {
@GetMapping("/")
public String home() {
return "Welcome!";
}
@GetMapping("/admin")
public String admin() {
return "Welcome, admin!";
}
}
```
现在,当用户访问 /admin 路径时,只有拥有 admin 角色的用户才能访问该路径。
阅读全文