[英]Authentication with OAuth2 in Webflux Spring
我正在开发一个应用程序,在该应用程序中我希望具有基于角色的访问控制,但是不幸的是,我没有找到关于spring webflux用法的任何好例子。 我的oauth2.client.provider是Okta。
这是我的SecurityWebFilterChain:
@Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
return http
.authorizeExchange()
.pathMatchers("/*").permitAll()
.pathMatchers("/admin").hasRole("admins");
}
在本文中,我发现我应该配置资源服务器。 请给我一个提示。
您需要使用Spring Boot 2.1的里程碑发行版才能正常工作。 M3或更高级别可以解决问题。 为Spring Security 5.1 OIDC支持添加必要的依赖项:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-oauth2-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-oauth2-jose</artifactId>
</dependency>
然后创建一个Okta OIDC“ Web”应用并将您的设置复制到src/main/resources/application.yml
。
spring:
security:
oauth2:
client:
provider:
okta:
issuer-uri: https://dev-737523.oktapreview.com/oauth2/default
registration:
login:
okta:
client-id: {clientId}
client-secret: {clientSecret}
scope: openid email profile
重新启动您的应用程序,转到http:// localhost:8080 ,应将您重定向到Okta进行登录。输入有效的凭据,成功登录后,您将被重定向回您的应用程序。
要基于角色限制访问权限,您需要为用户创建组。
创建一个ROLE_ADMIN和ROLE_USER组(“ 用户” >“ 组” >“ 添加组” )并将用户添加到其中。 您可以使用注册时使用的帐户,也可以创建一个新用户(“ 用户” >“ 添加人” )。 导航到“ API” >“ 授权服务器” ,单击“ 授权服务器”选项卡,然后编辑默认选项卡。 点击索赔标签,然后添加索赔 。 将其命名为“组”或“角色”,并将其包含在ID令牌中。 将值类型设置为“ Groups”,并将过滤器设置为正则表达式“。*”(以包括所有内容)。
然后,您应该可以使用类似:
@Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
return http
.authorizeExchange()
.pathMatchers("/*").permitAll()
.pathMatchers("/admin").hasAuthority("ROLE_ADMIN");
}
您还应该能够使用本博客文章中提到的@PreAuthorize
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.